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