doxygen fixes
[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 2, 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_connection_lib.h"
28 #include "gnunet_container_lib.h"
29 #include "gnunet_os_lib.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_resolver_service.h"
32 #include "gnunet_server_lib.h"
33 #include "gnunet_service_lib.h"
34 #include "gnunet_signatures.h"
35 #include "gnunet_statistics_service.h"
36 #include "gnunet_transport_service.h"
37 #include "plugin_transport.h"
38 #include "transport.h"
39
40 #define DEBUG_TCP GNUNET_YES
41
42 /**
43  * How long until we give up on transmitting the welcome message?
44  */
45 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
46
47
48 /**
49  * Initial handshake message for a session.
50  */
51 struct WelcomeMessage
52 {
53   /**
54    * Type is GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME.
55    */
56   struct GNUNET_MessageHeader header;
57
58   /**
59    * Identity of the node connecting (TCP client)
60    */
61   struct GNUNET_PeerIdentity clientIdentity;
62
63 };
64
65
66 /**
67  * Encapsulation of all of the state of the plugin.
68  */
69 struct Plugin;
70
71
72 /**
73  * Information kept for each message that is yet to
74  * be transmitted.
75  */
76 struct PendingMessage
77 {
78
79   /**
80    * This is a doubly-linked list.
81    */
82   struct PendingMessage *next;
83
84   /**
85    * This is a doubly-linked list.
86    */
87   struct PendingMessage *prev;
88
89   /**
90    * The pending message
91    */
92   const char *msg;
93
94   /**
95    * Continuation function to call once the message
96    * has been sent.  Can be NULL if there is no
97    * continuation to call.
98    */
99   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
100
101   /**
102    * Closure for transmit_cont.
103    */
104   void *transmit_cont_cls;
105
106   /**
107    * Timeout value for the pending message.
108    */
109   struct GNUNET_TIME_Absolute timeout;
110
111   /**
112    * So that the gnunet-service-transport can group messages together,
113    * these pending messages need to accept a message buffer and size
114    * instead of just a GNUNET_MessageHeader.
115    */
116   size_t message_size;
117
118 };
119
120
121 /**
122  * Session handle for TCP connections.
123  */
124 struct Session
125 {
126
127   /**
128    * Stored in a linked list.
129    */
130   struct Session *next;
131
132   /**
133    * Pointer to the global plugin struct.
134    */
135   struct Plugin *plugin;
136
137   /**
138    * The client (used to identify this connection)
139    */
140   struct GNUNET_SERVER_Client *client;
141
142   /**
143    * Messages currently pending for transmission
144    * to this peer, if any.
145    */
146   struct PendingMessage *pending_messages_head;
147
148   /**
149    * Messages currently pending for transmission
150    * to this peer, if any.
151    */
152   struct PendingMessage *pending_messages_tail;
153
154   /**
155    * Handle for pending transmission request.
156    */
157   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
158
159   /**
160    * To whom are we talking to (set to our identity
161    * if we are still waiting for the welcome message)
162    */
163   struct GNUNET_PeerIdentity target;
164
165   /**
166    * ID of task used to delay receiving more to throttle sender.
167    */
168   GNUNET_SCHEDULER_TaskIdentifier receive_delay_task;
169
170   /**
171    * Address of the other peer (either based on our 'connect'
172    * call or on our 'accept' call).
173    */
174   void *connect_addr;
175
176   /**
177    * Last activity on this connection.  Used to select preferred
178    * connection.
179    */
180   struct GNUNET_TIME_Absolute last_activity;
181
182   /**
183    * Length of connect_addr.
184    */
185   size_t connect_alen;
186
187   /**
188    * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
189    */
190   int expecting_welcome;
191
192   /**
193    * Was this a connection that was inbound (we accepted)? (GNUNET_YES/GNUNET_NO)
194    */
195   int inbound;
196
197 };
198
199
200 /**
201  * Encapsulation of all of the state of the plugin.
202  */
203 struct Plugin
204 {
205   /**
206    * Our environment.
207    */
208   struct GNUNET_TRANSPORT_PluginEnvironment *env;
209
210   /**
211    * The listen socket.
212    */
213   struct GNUNET_CONNECTION_Handle *lsock;
214
215   /**
216    * List of open TCP sessions.
217    */
218   struct Session *sessions;
219
220   /**
221    * Handle for the statistics service.
222    */
223   struct GNUNET_STATISTICS_Handle *statistics;
224
225   /**
226    * Handle to the network service.
227    */
228   struct GNUNET_SERVICE_Context *service;
229
230   /**
231    * Handle to the server for this service.
232    */
233   struct GNUNET_SERVER_Handle *server;
234
235   /**
236    * Copy of the handler array where the closures are
237    * set to this struct's instance.
238    */
239   struct GNUNET_SERVER_MessageHandler *handlers;
240
241   /**
242    * Handle for request of hostname resolution, non-NULL if pending.
243    */
244   struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
245
246   /**
247    * ID of task used to update our addresses when one expires.
248    */
249   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
250
251   /**
252    * Port that we are actually listening on.
253    */
254   uint16_t open_port;
255
256   /**
257    * Port that the user said we would have visible to the
258    * rest of the world.
259    */
260   uint16_t adv_port;
261
262 };
263
264
265 /**
266  * Find the session handle for the given client.
267  *
268  * @return NULL if no matching session exists
269  */
270 static struct Session *
271 find_session_by_client (struct Plugin *plugin,
272                         const struct GNUNET_SERVER_Client *client)
273 {
274   struct Session *ret;
275
276   ret = plugin->sessions;
277   while ((ret != NULL) && (client != ret->client))
278     ret = ret->next;
279   return ret;
280 }
281
282
283 /**
284  * Create a new session.  Also queues a welcome message.
285  *
286  * @param plugin us
287  * @param target peer to connect to
288  * @param client client to use
289  * @return new session object
290  */
291 static struct Session *
292 create_session (struct Plugin *plugin,
293                 const struct GNUNET_PeerIdentity *target,
294                 struct GNUNET_SERVER_Client *client)
295 {
296   struct Session *ret;
297   struct PendingMessage *pm;
298   struct WelcomeMessage welcome;
299
300   GNUNET_assert (client != NULL);
301   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
302                    "tcp",
303                    "Creating new session for peer `%4s'\n",
304                    GNUNET_i2s (target));
305   ret = GNUNET_malloc (sizeof (struct Session));
306   ret->last_activity = GNUNET_TIME_absolute_get ();
307   ret->plugin = plugin;
308   ret->next = plugin->sessions;
309   plugin->sessions = ret;
310   ret->client = client;
311   ret->target = *target;
312   ret->expecting_welcome = GNUNET_YES;
313   pm = GNUNET_malloc (sizeof (struct PendingMessage) + sizeof (struct WelcomeMessage));
314   pm->msg = (const char*) &pm[1];
315   pm->message_size = sizeof (struct WelcomeMessage);
316   welcome.header.size = htons (sizeof (struct WelcomeMessage));
317   welcome.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
318   welcome.clientIdentity = *plugin->env->my_identity;
319   memcpy (&pm[1], &welcome, sizeof (welcome));
320   pm->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
321   GNUNET_STATISTICS_update (plugin->env->stats,
322                             gettext_noop ("# bytes currently in TCP buffers"),
323                             pm->message_size,
324                             GNUNET_NO);      
325   GNUNET_CONTAINER_DLL_insert (ret->pending_messages_head,
326                                ret->pending_messages_tail,
327                                pm);
328   GNUNET_STATISTICS_update (plugin->env->stats,
329                             gettext_noop ("# TCP sessions active"),
330                             1,
331                             GNUNET_NO);      
332   return ret;
333 }
334
335
336 /**
337  * If we have pending messages, ask the server to
338  * transmit them (schedule the respective tasks, etc.)
339  *
340  * @param session for which session should we do this
341  */
342 static void process_pending_messages (struct Session *session);
343
344
345 /**
346  * Function called to notify a client about the socket
347  * being ready to queue more data.  "buf" will be
348  * NULL and "size" zero if the socket was closed for
349  * writing in the meantime.
350  *
351  * @param cls closure
352  * @param size number of bytes available in buf
353  * @param buf where the callee should write the message
354  * @return number of bytes written to buf
355  */
356 static size_t
357 do_transmit (void *cls, size_t size, void *buf)
358 {
359   struct Session *session = cls;
360   struct GNUNET_PeerIdentity pid;
361   struct Plugin *plugin;
362   struct PendingMessage *pos;
363   struct PendingMessage *hd;
364   struct PendingMessage *tl;
365   struct GNUNET_TIME_Absolute now;
366   char *cbuf;
367   size_t ret;
368
369   session->transmit_handle = NULL;
370   plugin = session->plugin;
371   if (buf == NULL)
372     {
373 #if DEBUG_TCP
374       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
375                        "tcp",
376                        "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
377                        GNUNET_i2s (&session->target));
378 #endif
379       /* timeout; cancel all messages that have already expired */
380       hd = NULL;
381       tl = NULL;
382       ret = 0;
383       now = GNUNET_TIME_absolute_get ();
384       while ( (NULL != (pos = session->pending_messages_head)) &&
385               (pos->timeout.value <= now.value) )
386         {
387           GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
388                                        session->pending_messages_tail,
389                                        pos);
390 #if DEBUG_TCP
391           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
392                            "tcp",
393                            "Failed to transmit %u byte message to `%4s'.\n",
394                            pos->message_size,
395                            GNUNET_i2s (&session->target));
396 #endif
397           ret += pos->message_size;
398           GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
399         }
400       /* do this call before callbacks (so that if callbacks destroy
401          session, they have a chance to cancel actions done by this
402          call) */
403       process_pending_messages (session);  
404       pid = session->target;
405       /* no do callbacks and do not use session again since
406          the callbacks may abort the session */
407       while (NULL != (pos = hd))
408         {
409           GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
410           if (pos->transmit_cont != NULL)
411             pos->transmit_cont (pos->transmit_cont_cls,
412                                 &pid, GNUNET_SYSERR);
413           GNUNET_free (pos);
414         }
415       GNUNET_STATISTICS_update (plugin->env->stats,
416                                 gettext_noop ("# bytes currently in TCP buffers"),
417                                 - (int64_t) ret,
418                                 GNUNET_NO); 
419       GNUNET_STATISTICS_update (plugin->env->stats,
420                                 gettext_noop ("# bytes discarded by TCP (timeout)"),
421                                 ret,
422                                 GNUNET_NO);      
423       return 0;
424     }
425   /* copy all pending messages that would fit */
426   ret = 0;
427   cbuf = buf;
428   hd = NULL;
429   tl = NULL;
430   while (NULL != (pos = session->pending_messages_head)) 
431     {
432       if (ret + pos->message_size > size) 
433         break;
434       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
435                                    session->pending_messages_tail,
436                                    pos);
437       GNUNET_assert (size >= pos->message_size);
438       memcpy (cbuf, pos->msg, pos->message_size);
439       cbuf += pos->message_size;
440       ret += pos->message_size;
441       size -= pos->message_size;
442       GNUNET_CONTAINER_DLL_insert_after (hd, tl, tl, pos);
443     }
444   /* schedule 'continuation' before callbacks so that callbacks that
445      cancel everything don't cause us to use a session that no longer
446      exists... */
447   process_pending_messages (session);  
448   session->last_activity = GNUNET_TIME_absolute_get ();
449   pid = session->target;
450   /* we'll now call callbacks that may cancel the session; hence
451      we should not use 'session' after this point */
452   while (NULL != (pos = hd))
453     {
454       GNUNET_CONTAINER_DLL_remove (hd, tl, pos);
455       if (pos->transmit_cont != NULL)
456         pos->transmit_cont (pos->transmit_cont_cls,
457                             &pid, GNUNET_OK);
458       GNUNET_free (pos);
459     }
460   GNUNET_assert (hd == NULL);
461   GNUNET_assert (tl == NULL);
462 #if DEBUG_TCP > 1
463   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
464                    "tcp", "Transmitting %u bytes\n", ret);
465 #endif
466   GNUNET_STATISTICS_update (plugin->env->stats,
467                             gettext_noop ("# bytes currently in TCP buffers"),
468                             - (int64_t) ret,
469                             GNUNET_NO);       
470   GNUNET_STATISTICS_update (plugin->env->stats,
471                             gettext_noop ("# bytes transmitted via TCP"),
472                             ret,
473                             GNUNET_NO);      
474   return ret;
475 }
476
477
478 /**
479  * If we have pending messages, ask the server to
480  * transmit them (schedule the respective tasks, etc.)
481  *
482  * @param session for which session should we do this
483  */
484 static void
485 process_pending_messages (struct Session *session)
486 {
487   struct PendingMessage *pm;
488
489   GNUNET_assert (session->client != NULL);
490   if (session->transmit_handle != NULL)
491     return;
492   if (NULL == (pm = session->pending_messages_head))
493     return;
494   session->transmit_handle
495     = GNUNET_SERVER_notify_transmit_ready (session->client,
496                                            pm->message_size,
497                                            GNUNET_TIME_absolute_get_remaining
498                                            (pm->timeout),
499                                            &do_transmit, session);
500 }
501
502
503 /**
504  * Functions with this signature are called whenever we need
505  * to close a session due to a disconnect or failure to
506  * establish a connection.
507  *
508  * @param session session to close down
509  */
510 static void
511 disconnect_session (struct Session *session)
512 {
513   struct Session *prev;
514   struct Session *pos;
515   struct PendingMessage *pm;
516
517 #if DEBUG_TCP
518   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
519                    "tcp",
520                    "Disconnecting from `%4s' at %s (session %p).\n",
521                    GNUNET_i2s (&session->target),
522                    (session->connect_addr != NULL) ?
523                    GNUNET_a2s (session->connect_addr,
524                                session->connect_alen) : "*", session);
525 #endif
526   /* remove from session list */
527   prev = NULL;
528   pos = session->plugin->sessions;
529   while (pos != session)
530     {
531       prev = pos;
532       pos = pos->next;
533     }
534   if (prev == NULL)
535     session->plugin->sessions = session->next;
536   else
537     prev->next = session->next;
538   session->plugin->env->session_end (session->plugin->env->cls,
539                             &session->target,
540                             session);
541   /* clean up state */
542   if (session->transmit_handle != NULL)
543     {
544       GNUNET_CONNECTION_notify_transmit_ready_cancel
545         (session->transmit_handle);
546       session->transmit_handle = NULL;
547     }
548   while (NULL != (pm = session->pending_messages_head))
549     {
550 #if DEBUG_TCP
551       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
552                        "tcp",
553                        pm->transmit_cont != NULL
554                        ? "Could not deliver message to `%4s'.\n"
555                        :
556                        "Could not deliver message to `%4s', notifying.\n",
557                        GNUNET_i2s (&session->target));
558 #endif
559       GNUNET_STATISTICS_update (session->plugin->env->stats,
560                                 gettext_noop ("# bytes currently in TCP buffers"),
561                                 - (int64_t) pm->message_size,
562                                 GNUNET_NO);      
563       GNUNET_STATISTICS_update (session->plugin->env->stats,
564                                 gettext_noop ("# bytes discarded by TCP (disconnect)"),
565                                 pm->message_size,
566                                 GNUNET_NO);      
567       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
568                                    session->pending_messages_tail,
569                                    pm);
570       if (NULL != pm->transmit_cont)
571         pm->transmit_cont (pm->transmit_cont_cls,
572                            &session->target, GNUNET_SYSERR);
573       GNUNET_free (pm);
574     }
575   GNUNET_break (session->client != NULL);
576   if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
577     {
578       GNUNET_SCHEDULER_cancel (session->plugin->env->sched,
579                                session->receive_delay_task);
580       GNUNET_SERVER_receive_done (session->client, 
581                                   GNUNET_SYSERR);       
582     }
583   GNUNET_SERVER_client_drop (session->client);
584   GNUNET_STATISTICS_update (session->plugin->env->stats,
585                             gettext_noop ("# TCP sessions active"),
586                             -1,
587                             GNUNET_NO);      
588   GNUNET_free_non_null (session->connect_addr);
589   GNUNET_free (session);
590 }
591
592
593 /**
594  * Given two otherwise equivalent sessions, pick the better one.
595  * 
596  * @param s1 one session (also default)
597  * @param s2 other session
598  * @return "better" session (more active)
599  */
600 static struct Session *
601 select_better_session (struct Session *s1,
602                        struct Session *s2)
603 {
604   if (s1 == NULL)
605     return s2;
606   if (s2 == NULL)
607     return s1;
608   if ( (s1->expecting_welcome == GNUNET_NO) &&
609        (s2->expecting_welcome == GNUNET_YES) )
610     return s1;
611   if ( (s1->expecting_welcome == GNUNET_YES) &&
612        (s2->expecting_welcome == GNUNET_NO) )
613     return s2;
614   if (s1->last_activity.value < s2->last_activity.value)
615     return s2;
616   if (s1->last_activity.value > s2->last_activity.value)
617     return s1;
618   if ( (GNUNET_YES == s1->inbound) &&
619        (GNUNET_NO  == s2->inbound) )
620     return s1;
621   if ( (GNUNET_NO  == s1->inbound) &&
622        (GNUNET_YES == s2->inbound) )
623     return s2;
624   return s1;
625 }
626
627
628 /**
629  * Function that can be used by the transport service to transmit
630  * a message using the plugin.   Note that in the case of a
631  * peer disconnecting, the continuation MUST be called
632  * prior to the disconnect notification itself.  This function
633  * will be called with this peer's HELLO message to initiate
634  * a fresh connection to another peer.
635  *
636  * @param cls closure
637  * @param target who should receive this message
638  * @param msg the message to transmit
639  * @param msgbuf_size number of bytes in 'msg'
640  * @param priority how important is the message (most plugins will
641  *                 ignore message priority and just FIFO)
642  * @param timeout how long to wait at most for the transmission (does not
643  *                require plugins to discard the message after the timeout,
644  *                just advisory for the desired delay; most plugins will ignore
645  *                this as well)
646  * @param session which session must be used (or NULL for "any")
647  * @param addr the address to use (can be NULL if the plugin
648  *                is "on its own" (i.e. re-use existing TCP connection))
649  * @param addrlen length of the address in bytes
650  * @param force_address GNUNET_YES if the plugin MUST use the given address,
651  *                GNUNET_NO means the plugin may use any other address and
652  *                GNUNET_SYSERR means that only reliable existing
653  *                bi-directional connections should be used (regardless
654  *                of address)
655  * @param cont continuation to call once the message has
656  *        been transmitted (or if the transport is ready
657  *        for the next transmission call; or if the
658  *        peer disconnected...); can be NULL
659  * @param cont_cls closure for cont
660  * @return number of bytes used (on the physical network, with overheads);
661  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
662  *         and does NOT mean that the message was not transmitted (DV)
663  */
664 static ssize_t
665 tcp_plugin_send (void *cls,
666                  const struct GNUNET_PeerIdentity *target,
667                  const char *msg,
668                  size_t msgbuf_size,
669                  uint32_t priority,
670                  struct GNUNET_TIME_Relative timeout,
671                  struct Session *session,
672                  const void *addr,
673                  size_t addrlen,
674                  int force_address,
675                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
676 {
677   struct Plugin *plugin = cls;
678   struct Session *cand_session;
679   struct Session *next;
680   struct PendingMessage *pm;
681   struct GNUNET_CONNECTION_Handle *sa;
682   int af;
683
684   GNUNET_STATISTICS_update (plugin->env->stats,
685                             gettext_noop ("# bytes TCP was asked to transmit"),
686                             msgbuf_size,
687                             GNUNET_NO);      
688   /* FIXME: we could do this a cheaper with a hash table
689      where we could restrict the iteration to entries that match
690      the target peer... */
691   if (session == NULL)
692     {
693       cand_session = NULL;
694       next = plugin->sessions;
695       while (NULL != (session = next)) 
696         {
697           next = session->next;
698           GNUNET_assert (session->client != NULL);
699           if (0 != memcmp (target,
700                            &session->target, 
701                            sizeof (struct GNUNET_PeerIdentity)))
702             continue;
703           if ( ( (GNUNET_SYSERR == force_address) &&
704                  (session->expecting_welcome == GNUNET_NO) ) ||
705                (GNUNET_NO == force_address) )   
706             {
707               cand_session = select_better_session (cand_session,
708                                                     session);
709               continue;
710             }
711           if (GNUNET_SYSERR == force_address)
712             continue;
713           GNUNET_break (GNUNET_YES == force_address);
714           if (addr == NULL)
715             {
716               GNUNET_break (0);
717               break;
718             }
719           if (session->inbound == GNUNET_YES) 
720             continue;
721           if (addrlen != session->connect_alen)
722             continue;
723           if (0 != memcmp (session->connect_addr,
724                            addr,
725                            addrlen))
726             continue;
727           cand_session = select_better_session (cand_session,
728                                                 session);             
729         }
730       session = cand_session;
731     }
732   if ( (session == NULL) &&
733        (addr == NULL) )
734     {
735 #if DEBUG_TCP
736       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
737                        "tcp",
738                        "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
739                        GNUNET_i2s (target));
740 #endif
741       GNUNET_STATISTICS_update (plugin->env->stats,
742                                 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
743                                 msgbuf_size,
744                                 GNUNET_NO);      
745       return -1;
746     }
747   if (session == NULL)
748     {
749       if (sizeof (struct sockaddr_in) == addrlen)
750         {
751           af = AF_INET;
752         }
753       else if (sizeof (struct sockaddr_in6) == addrlen)
754         {
755           af = AF_INET6;
756         }
757       else
758         {
759           GNUNET_break_op (0);
760           return -1;
761         }
762       sa = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
763                                                    af, addr, addrlen,
764                                                    GNUNET_SERVER_MAX_MESSAGE_SIZE);
765       if (sa == NULL)
766         {
767 #if DEBUG_TCP
768           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
769                            "tcp",
770                            "Failed to create connection to `%4s' at `%s'\n",
771                            GNUNET_i2s (target),
772                            GNUNET_a2s (addr, addrlen));
773 #endif
774           GNUNET_STATISTICS_update (plugin->env->stats,
775                                     gettext_noop ("# bytes discarded by TCP (failed to connect)"),
776                                     msgbuf_size,
777                                     GNUNET_NO);      
778           return -1;
779         }
780 #if DEBUG_TCP
781       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
782                        "tcp",
783                        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
784                        GNUNET_i2s (target),
785                        GNUNET_a2s (addr, addrlen));
786 #endif
787       session = create_session (plugin,
788                                 target,
789                                 GNUNET_SERVER_connect_socket (plugin->server,
790                                                               sa));
791       session->connect_addr = GNUNET_malloc (addrlen);
792       memcpy (session->connect_addr,
793               addr,
794               addrlen);
795       session->connect_alen = addrlen;
796     }
797   GNUNET_assert (session != NULL);
798   GNUNET_assert (session->client != NULL);
799   GNUNET_STATISTICS_update (plugin->env->stats,
800                             gettext_noop ("# bytes currently in TCP buffers"),
801                             msgbuf_size,
802                             GNUNET_NO);      
803   /* create new message entry */
804   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
805   pm->msg = (const char*) &pm[1];
806   memcpy (&pm[1], msg, msgbuf_size);
807   pm->message_size = msgbuf_size;
808   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
809   pm->transmit_cont = cont;
810   pm->transmit_cont_cls = cont_cls;
811
812   /* append pm to pending_messages list */
813   GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
814                                      session->pending_messages_tail,
815                                      session->pending_messages_tail,
816                                      pm);
817 #if DEBUG_TCP
818   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
819                    "tcp",
820                    "Asked to transmit %u bytes to `%s', added message to list.\n",
821                    msgbuf_size,
822                    GNUNET_i2s (target));
823 #endif
824   process_pending_messages (session);
825   return msgbuf_size;
826 }
827
828
829 /**
830  * Function that can be called to force a disconnect from the
831  * specified neighbour.  This should also cancel all previously
832  * scheduled transmissions.  Obviously the transmission may have been
833  * partially completed already, which is OK.  The plugin is supposed
834  * to close the connection (if applicable) and no longer call the
835  * transmit continuation(s).
836  *
837  * Finally, plugin MUST NOT call the services's receive function to
838  * notify the service that the connection to the specified target was
839  * closed after a getting this call.
840  *
841  * @param cls closure
842  * @param target peer for which the last transmission is
843  *        to be cancelled
844  */
845 static void
846 tcp_plugin_disconnect (void *cls,
847                        const struct GNUNET_PeerIdentity *target)
848 {
849   struct Plugin *plugin = cls;
850   struct Session *session;
851   struct Session *next;
852   struct PendingMessage *pm;
853
854 #if DEBUG_TCP
855   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
856                    "tcp",
857                    "Asked to cancel session with `%4s'\n",
858                    GNUNET_i2s (target));
859 #endif
860   next = plugin->sessions;
861   while (NULL != (session = next))
862     {
863       next = session->next;
864       if (0 != memcmp (target,
865                        &session->target,
866                        sizeof (struct GNUNET_PeerIdentity)))
867         continue;
868       pm = session->pending_messages_head;
869       while (pm != NULL)
870         {
871           pm->transmit_cont = NULL;
872           pm->transmit_cont_cls = NULL;
873           pm = pm->next;
874         }
875       disconnect_session (session);
876     }
877 }
878
879
880 /**
881  * Context for address to string conversion.
882  */
883 struct PrettyPrinterContext
884 {
885   /**
886    * Function to call with the result.
887    */
888   GNUNET_TRANSPORT_AddressStringCallback asc;
889
890   /**
891    * Clsoure for 'asc'.
892    */
893   void *asc_cls;
894
895   /**
896    * Port to add after the IP address.
897    */
898   uint16_t port;
899 };
900
901
902 /**
903  * Append our port and forward the result.
904  *
905  * @param cls the 'struct PrettyPrinterContext*'
906  * @param hostname hostname part of the address
907  */
908 static void
909 append_port (void *cls, const char *hostname)
910 {
911   struct PrettyPrinterContext *ppc = cls;
912   char *ret;
913
914   if (hostname == NULL)
915     {
916       ppc->asc (ppc->asc_cls, NULL);
917       GNUNET_free (ppc);
918       return;
919     }
920   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
921   ppc->asc (ppc->asc_cls, ret);
922   GNUNET_free (ret);
923 }
924
925
926 /**
927  * Convert the transports address to a nice, human-readable
928  * format.
929  *
930  * @param cls closure
931  * @param type name of the transport that generated the address
932  * @param addr one of the addresses of the host, NULL for the last address
933  *        the specific address format depends on the transport
934  * @param addrlen length of the address
935  * @param numeric should (IP) addresses be displayed in numeric form?
936  * @param timeout after how long should we give up?
937  * @param asc function to call on each string
938  * @param asc_cls closure for asc
939  */
940 static void
941 tcp_plugin_address_pretty_printer (void *cls,
942                                    const char *type,
943                                    const void *addr,
944                                    size_t addrlen,
945                                    int numeric,
946                                    struct GNUNET_TIME_Relative timeout,
947                                    GNUNET_TRANSPORT_AddressStringCallback asc,
948                                    void *asc_cls)
949 {
950   struct Plugin *plugin = cls;
951   const struct sockaddr_in *v4;
952   const struct sockaddr_in6 *v6;
953   struct PrettyPrinterContext *ppc;
954
955   if ((addrlen != sizeof (struct sockaddr_in)) &&
956       (addrlen != sizeof (struct sockaddr_in6)))
957     {
958       /* invalid address */
959       GNUNET_break_op (0);
960       asc (asc_cls, NULL);
961       return;
962     }
963   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
964   ppc->asc = asc;
965   ppc->asc_cls = asc_cls;
966   if (addrlen == sizeof (struct sockaddr_in))
967     {
968       v4 = (const struct sockaddr_in *) addr;
969       ppc->port = ntohs (v4->sin_port);
970     }
971   else
972     {
973       v6 = (const struct sockaddr_in6 *) addr;
974       ppc->port = ntohs (v6->sin6_port);
975
976     }
977   GNUNET_RESOLVER_hostname_get (plugin->env->sched,
978                                 plugin->env->cfg,
979                                 addr,
980                                 addrlen,
981                                 !numeric, timeout, &append_port, ppc);
982 }
983
984
985 /**
986  * Check if the given port is plausible (must be either
987  * our listen port or our advertised port).  If it is
988  * neither, we return one of these two ports at random.
989  *
990  * @param plugin global variables
991  * @param in_port port number to check
992  * @return either in_port or a more plausible port
993  */
994 static uint16_t
995 check_port (struct Plugin *plugin, uint16_t in_port)
996 {
997   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
998     return in_port;
999   return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1000                                     2) == 0)
1001     ? plugin->open_port : plugin->adv_port;
1002 }
1003
1004
1005 /**
1006  * Another peer has suggested an address for this peer and transport
1007  * plugin.  Check that this could be a valid address.
1008  *
1009  * @param cls closure, our 'struct Plugin*'
1010  * @param addr pointer to the address
1011  * @param addrlen length of addr
1012  * @return GNUNET_OK if this is a plausible address for this peer
1013  *         and transport
1014  */
1015 static int
1016 tcp_plugin_check_address (void *cls, void *addr, size_t addrlen)
1017 {
1018   struct Plugin *plugin = cls;
1019   char buf[sizeof (struct sockaddr_in6)];
1020   struct sockaddr_in *v4;
1021   struct sockaddr_in6 *v6;
1022
1023   if ((addrlen != sizeof (struct sockaddr_in)) &&
1024       (addrlen != sizeof (struct sockaddr_in6)))
1025     {
1026       GNUNET_break_op (0);
1027       return GNUNET_SYSERR;
1028     }
1029   memcpy (buf, addr, sizeof (struct sockaddr_in6));
1030   if (addrlen == sizeof (struct sockaddr_in))
1031     {
1032       v4 = (struct sockaddr_in *) buf;
1033       v4->sin_port = htons (check_port (plugin, ntohs (v4->sin_port)));
1034     }
1035   else
1036     {
1037       v6 = (struct sockaddr_in6 *) buf;
1038       v6->sin6_port = htons (check_port (plugin, ntohs (v6->sin6_port)));
1039     }
1040 #if DEBUG_TCP
1041   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1042                    "tcp",
1043                    "Informing transport service about my address `%s'.\n",
1044                    GNUNET_a2s (addr, addrlen));
1045 #endif
1046   return GNUNET_OK;
1047 }
1048
1049
1050 /**
1051  * We've received a welcome from this peer via TCP.  Possibly create a
1052  * fresh client record and send back our welcome.
1053  *
1054  * @param cls closure
1055  * @param client identification of the client
1056  * @param message the actual message
1057  */
1058 static void
1059 handle_tcp_welcome (void *cls,
1060                     struct GNUNET_SERVER_Client *client,
1061                     const struct GNUNET_MessageHeader *message)
1062 {
1063   struct Plugin *plugin = cls;
1064   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
1065   struct Session *session;
1066   size_t alen;
1067   void *vaddr;
1068
1069 #if DEBUG_TCP
1070   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1071                    "tcp",
1072                    "Received %s message from a `%4s/%p'.\n", 
1073                    "WELCOME",
1074                    GNUNET_i2s (&wm->clientIdentity), client);
1075 #endif
1076   GNUNET_STATISTICS_update (plugin->env->stats,
1077                             gettext_noop ("# TCP WELCOME messages received"),
1078                             1,
1079                             GNUNET_NO);      
1080   session = find_session_by_client (plugin, client);
1081   if (session == NULL)
1082     {
1083       GNUNET_SERVER_client_keep (client);
1084       session = create_session (plugin,
1085                                 &wm->clientIdentity, client);
1086       session->inbound = GNUNET_YES;
1087       if (GNUNET_OK ==
1088           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
1089         {
1090 #if DEBUG_TCP
1091           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1092                            "tcp",
1093                            "Found address `%s' for incoming connection %p\n",
1094                            GNUNET_a2s (vaddr, alen),
1095                            client);
1096 #endif
1097           session->connect_addr = vaddr;
1098           session->connect_alen = alen;
1099         }
1100       else
1101         {
1102 #if DEBUG_TCP
1103           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1104                            "tcp",
1105                            "Did not obtain TCP socket address for incoming connection\n");
1106 #endif
1107         }
1108 #if DEBUG_TCP
1109       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1110                        "tcp",
1111                        "Creating new session %p for connection %p\n",
1112                        session, client);
1113 #endif
1114       process_pending_messages (session);
1115     }
1116   if (session->expecting_welcome != GNUNET_YES)
1117     {
1118       GNUNET_break_op (0);
1119       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1120       return;
1121     }
1122   session->last_activity = GNUNET_TIME_absolute_get ();
1123   session->expecting_welcome = GNUNET_NO;
1124   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1125 }
1126
1127
1128 /**
1129  * Task to signal the server that we can continue
1130  * receiving from the TCP client now.
1131  *
1132  * @param cls the 'struct Session*'
1133  * @param tc task context (unused)
1134  */
1135 static void
1136 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1137 {
1138   struct Session *session = cls;
1139   struct GNUNET_TIME_Relative delay;
1140
1141   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
1142   delay = session->plugin->env->receive (session->plugin->env->cls,
1143                                          &session->target,
1144                                          NULL, 0, 
1145                                          session,
1146                                          NULL, 0);
1147   if (delay.value == 0)
1148     GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1149   else
1150     session->receive_delay_task = 
1151       GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1152                                     delay, &delayed_done, session);
1153 }
1154
1155
1156 /**
1157  * We've received data for this peer via TCP.  Unbox,
1158  * compute latency and forward.
1159  *
1160  * @param cls closure
1161  * @param client identification of the client
1162  * @param message the actual message
1163  */
1164 static void
1165 handle_tcp_data (void *cls,
1166                  struct GNUNET_SERVER_Client *client,
1167                  const struct GNUNET_MessageHeader *message)
1168 {
1169   struct Plugin *plugin = cls;
1170   struct Session *session;
1171   struct GNUNET_TIME_Relative delay;
1172
1173   if (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type))
1174     {
1175       /* We don't want to propagate WELCOME messages up! */
1176       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1177       return; 
1178     }    
1179   session = find_session_by_client (plugin, client);
1180   if ( (NULL == session) || (GNUNET_NO != session->expecting_welcome))
1181     {
1182       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1183       return;
1184     }
1185   session->last_activity = GNUNET_TIME_absolute_get ();
1186 #if DEBUG_TCP
1187   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1188                    "tcp", 
1189                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
1190                    (unsigned int) ntohs (message->size), 
1191                    (unsigned int) ntohs (message->type),
1192                    GNUNET_i2s (&session->target));
1193 #endif
1194   GNUNET_STATISTICS_update (plugin->env->stats,
1195                             gettext_noop ("# bytes received via TCP"),
1196                             ntohs (message->size),
1197                             GNUNET_NO); 
1198   delay = plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1199                                 session, 
1200                                 (GNUNET_YES == session->inbound) ? NULL : session->connect_addr,
1201                                 (GNUNET_YES == session->inbound) ? 0 : session->connect_alen);
1202   if (delay.value == 0)
1203     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1204   else
1205     session->receive_delay_task = 
1206       GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1207                                     delay, &delayed_done, session);
1208 }
1209
1210
1211 /**
1212  * Handlers for the various TCP messages.
1213  */
1214 static struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1215   {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
1216    sizeof (struct WelcomeMessage)},
1217   {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
1218   {NULL, NULL, 0, 0}
1219 };
1220
1221
1222 /**
1223  * Functions with this signature are called whenever a peer
1224  * is disconnected on the network level.
1225  *
1226  * @param cls closure
1227  * @param client identification of the client
1228  */
1229 static void
1230 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1231 {
1232   struct Plugin *plugin = cls;
1233   struct Session *session;
1234
1235   if (client == NULL)
1236     return;
1237   session = find_session_by_client (plugin, client);
1238   if (session == NULL)
1239     return;                     /* unknown, nothing to do */
1240 #if DEBUG_TCP
1241   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1242                    "tcp",
1243                    "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1244                    GNUNET_i2s (&session->target),
1245                    (session->connect_addr != NULL) ?
1246                    GNUNET_a2s (session->connect_addr,
1247                                session->connect_alen) : "*", client);
1248 #endif
1249   disconnect_session (session);
1250 }
1251
1252
1253 /**
1254  * Add the IP of our network interface to the list of
1255  * our external IP addresses.
1256  */
1257 static int
1258 process_interfaces (void *cls,
1259                     const char *name,
1260                     int isDefault,
1261                     const struct sockaddr *addr, socklen_t addrlen)
1262 {
1263   struct Plugin *plugin = cls;
1264   int af;
1265   struct sockaddr_in *v4;
1266   struct sockaddr_in6 *v6;
1267
1268   af = addr->sa_family;
1269   if (af == AF_INET)
1270     {
1271       v4 = (struct sockaddr_in *) addr;
1272       v4->sin_port = htons (plugin->adv_port);
1273     }
1274   else
1275     {
1276       GNUNET_assert (af == AF_INET6);
1277       v6 = (struct sockaddr_in6 *) addr;
1278       v6->sin6_port = htons (plugin->adv_port);
1279     }
1280   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1281                    GNUNET_ERROR_TYPE_BULK,
1282                    "tcp", _("Found address `%s' (%s)\n"),
1283                    GNUNET_a2s (addr, addrlen), name);
1284   plugin->env->notify_address (plugin->env->cls,
1285                                "tcp",
1286                                addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
1287   return GNUNET_OK;
1288 }
1289
1290
1291 /**
1292  * Function called by the resolver for each address obtained from DNS
1293  * for our own hostname.  Add the addresses to the list of our
1294  * external IP addresses.
1295  *
1296  * @param cls closure
1297  * @param addr one of the addresses of the host, NULL for the last address
1298  * @param addrlen length of the address
1299  */
1300 static void
1301 process_hostname_ips (void *cls,
1302                       const struct sockaddr *addr, socklen_t addrlen)
1303 {
1304   struct Plugin *plugin = cls;
1305
1306   if (addr == NULL)
1307     {
1308       plugin->hostname_dns = NULL;
1309       return;
1310     }
1311   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1312 }
1313
1314
1315 /**
1316  * Entry point for the plugin.
1317  */
1318 void *
1319 libgnunet_plugin_transport_tcp_init (void *cls)
1320 {
1321   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1322   struct GNUNET_TRANSPORT_PluginFunctions *api;
1323   struct Plugin *plugin;
1324   struct GNUNET_SERVICE_Context *service;
1325   unsigned long long aport;
1326   unsigned long long bport;
1327   unsigned int i;
1328
1329   service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
1330   if (service == NULL)
1331     {
1332       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1333                        "tcp",
1334                        _
1335                        ("Failed to start service for `%s' transport plugin.\n"),
1336                        "tcp");
1337       return NULL;
1338     }
1339   aport = 0;
1340   if ((GNUNET_OK !=
1341        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1342                                               "transport-tcp",
1343                                               "PORT",
1344                                               &bport)) ||
1345       (bport > 65535) ||
1346       ((GNUNET_OK ==
1347         GNUNET_CONFIGURATION_get_value_number (env->cfg,
1348                                                "transport-tcp",
1349                                                "ADVERTISED-PORT",
1350                                                &aport)) && (aport > 65535)))
1351     {
1352       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1353                        "tcp",
1354                        _
1355                        ("Require valid port number for service `%s' in configuration!\n"),
1356                        "transport-tcp");
1357       GNUNET_SERVICE_stop (service);
1358       return NULL;
1359     }
1360   if (aport == 0)
1361     aport = bport;
1362   plugin = GNUNET_malloc (sizeof (struct Plugin));
1363   plugin->open_port = bport;
1364   plugin->adv_port = aport;
1365   plugin->env = env;
1366   plugin->lsock = NULL;
1367   plugin->statistics = NULL;
1368   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1369   api->cls = plugin;
1370   api->send = &tcp_plugin_send;
1371   api->disconnect = &tcp_plugin_disconnect;
1372   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
1373   api->check_address = &tcp_plugin_check_address;
1374   plugin->service = service;
1375   plugin->server = GNUNET_SERVICE_get_server (service);
1376   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
1377   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
1378   for (i = 0;
1379        i <
1380        sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
1381        i++)
1382     plugin->handlers[i].callback_cls = plugin;
1383   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
1384
1385   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1386                    "tcp", _("TCP transport listening on port %llu\n"), bport);
1387   if (aport != bport)
1388     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1389                      "tcp",
1390                      _("TCP transport advertises itself as being on port %llu\n"),
1391                      aport);
1392   GNUNET_SERVER_disconnect_notify (plugin->server, 
1393                                    &disconnect_notify,
1394                                    plugin);
1395   /* FIXME: do the two calls below periodically again and
1396      not just once (since the info we get might change...) */
1397   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
1398   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
1399                                                            env->cfg,
1400                                                            AF_UNSPEC,
1401                                                            HOSTNAME_RESOLVE_TIMEOUT,
1402                                                            &process_hostname_ips,
1403                                                            plugin);
1404   return api;
1405 }
1406
1407
1408 /**
1409  * Exit point from the plugin.
1410  */
1411 void *
1412 libgnunet_plugin_transport_tcp_done (void *cls)
1413 {
1414   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1415   struct Plugin *plugin = api->cls;
1416   struct Session *session;
1417
1418   while (NULL != (session = plugin->sessions))
1419     disconnect_session (session);
1420   if (NULL != plugin->hostname_dns)
1421     {
1422       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
1423       plugin->hostname_dns = NULL;
1424     }
1425   GNUNET_SERVICE_stop (plugin->service);
1426   GNUNET_free (plugin->handlers);
1427   GNUNET_free (plugin);
1428   GNUNET_free (api);
1429   return NULL;
1430 }
1431
1432 /* end of plugin_transport_tcp.c */