fix
[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_CONTAINER_DLL_insert (ret->pending_messages_head,
312                                ret->pending_messages_tail,
313                                pm);
314   GNUNET_STATISTICS_update (plugin->env->stats,
315                             gettext_noop ("# TCP sessions active"),
316                             1,
317                             GNUNET_NO);      
318   return ret;
319 }
320
321
322 /**
323  * If we have pending messages, ask the server to
324  * transmit them (schedule the respective tasks, etc.)
325  *
326  * @param session for which session should we do this
327  */
328 static void process_pending_messages (struct Session *session);
329
330
331 /**
332  * Function called to notify a client about the socket
333  * being ready to queue more data.  "buf" will be
334  * NULL and "size" zero if the socket was closed for
335  * writing in the meantime.
336  *
337  * @param cls closure
338  * @param size number of bytes available in buf
339  * @param buf where the callee should write the message
340  * @return number of bytes written to buf
341  */
342 static size_t
343 do_transmit (void *cls, size_t size, void *buf)
344 {
345   struct Session *session = cls;
346   struct PendingMessage *pm;
347   char *cbuf;
348
349   size_t ret;
350
351   session->transmit_handle = NULL;
352   if (buf == NULL)
353     {
354 #if DEBUG_TCP
355       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
356                        "tcp",
357                        "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
358                        GNUNET_i2s (&session->target));
359 #endif
360       /* timeout */
361       while (NULL != (pm = session->pending_messages_head))
362         {
363           GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
364                                        session->pending_messages_tail,
365                                        pm);
366 #if DEBUG_TCP
367           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
368                            "tcp",
369                            "Failed to transmit %u byte message to `%4s'.\n",
370                            pm->message_size,
371                            GNUNET_i2s (&session->target));
372 #endif
373           GNUNET_STATISTICS_update (session->plugin->env->stats,
374                                     gettext_noop ("# bytes discarded by TCP (timeout)"),
375                                     pm->message_size,
376                                     GNUNET_NO);      
377           if (pm->transmit_cont != NULL)
378             pm->transmit_cont (pm->transmit_cont_cls,
379                                &session->target, GNUNET_SYSERR);
380           GNUNET_free (pm);
381         }
382       return 0;
383     }
384   ret = 0;
385   cbuf = buf;
386   while (NULL != (pm = session->pending_messages_head))
387     {
388       if (size < pm->message_size)
389         break;
390       memcpy (cbuf, pm->msg, pm->message_size);
391       cbuf += pm->message_size;
392       ret += pm->message_size;
393       size -= pm->message_size;
394       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
395                                    session->pending_messages_tail,
396                                    pm);
397       if (pm->transmit_cont != NULL)
398         pm->transmit_cont (pm->transmit_cont_cls,
399                            &session->target, GNUNET_OK);
400       GNUNET_free (pm);
401     }
402   if (session->client != NULL)
403     process_pending_messages (session);
404 #if DEBUG_TCP > 1
405   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
406                    "tcp", "Transmitting %u bytes\n", ret);
407 #endif
408   GNUNET_STATISTICS_update (session->plugin->env->stats,
409                             gettext_noop ("# bytes transmitted via TCP"),
410                             ret,
411                             GNUNET_NO);      
412   return ret;
413 }
414
415
416 /**
417  * If we have pending messages, ask the server to
418  * transmit them (schedule the respective tasks, etc.)
419  *
420  * @param session for which session should we do this
421  */
422 static void
423 process_pending_messages (struct Session *session)
424 {
425   struct PendingMessage *pm;
426   GNUNET_assert (session->client != NULL);
427   if (session->transmit_handle != NULL)
428     return;
429   if (NULL == (pm = session->pending_messages_head))
430     return;
431   session->transmit_handle
432     = GNUNET_SERVER_notify_transmit_ready (session->client,
433                                            pm->message_size,
434                                            GNUNET_TIME_absolute_get_remaining
435                                            (pm->timeout),
436                                            &do_transmit, session);
437 }
438
439
440 /**
441  * Functions with this signature are called whenever we need
442  * to close a session due to a disconnect or failure to
443  * establish a connection.
444  *
445  * @param session session to close down
446  */
447 static void
448 disconnect_session (struct Session *session)
449 {
450   struct Session *prev;
451   struct Session *pos;
452   struct PendingMessage *pm;
453
454 #if DEBUG_TCP
455   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
456                    "tcp",
457                    "Disconnecting from `%4s' at %s (session %p).\n",
458                    GNUNET_i2s (&session->target),
459                    (session->connect_addr != NULL) ?
460                    GNUNET_a2s (session->connect_addr,
461                                session->connect_alen) : "*", session);
462 #endif
463   /* remove from session list */
464   prev = NULL;
465   pos = session->plugin->sessions;
466   while (pos != session)
467     {
468       prev = pos;
469       pos = pos->next;
470     }
471   if (prev == NULL)
472     session->plugin->sessions = session->next;
473   else
474     prev->next = session->next;
475   /* clean up state */
476   if (session->transmit_handle != NULL)
477     {
478       GNUNET_CONNECTION_notify_transmit_ready_cancel
479         (session->transmit_handle);
480       session->transmit_handle = NULL;
481     }
482   while (NULL != (pm = session->pending_messages_head))
483     {
484 #if DEBUG_TCP
485       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
486                        "tcp",
487                        pm->transmit_cont != NULL
488                        ? "Could not deliver message to `%4s'.\n"
489                        :
490                        "Could not deliver message to `%4s', notifying.\n",
491                        GNUNET_i2s (&session->target));
492 #endif
493       GNUNET_CONTAINER_DLL_remove (session->pending_messages_head,
494                                    session->pending_messages_tail,
495                                    pm);
496       if (NULL != pm->transmit_cont)
497         pm->transmit_cont (pm->transmit_cont_cls,
498                            &session->target, GNUNET_SYSERR);
499       GNUNET_free (pm);
500     }
501   if (GNUNET_NO == session->expecting_welcome)
502     {
503 #if DEBUG_TCP
504       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
505                        "tcp",
506                        "Notifying transport service about loss of connection with `%4s'.\n",
507                        GNUNET_i2s (&session->target));
508 #endif
509       /* Data session that actually went past the initial handshake;
510          transport service may know about this one, so we need to
511          notify transport service about disconnect */
512       // FIXME: we should have a very clear connect-disconnect
513       // protocol with gnunet-service-transport! 
514       // FIXME: but this is not possible for all plugins, so what gives?
515     }
516   if (session->receive_delay_task != GNUNET_SCHEDULER_NO_TASK)
517     {
518       GNUNET_SCHEDULER_cancel (session->plugin->env->sched,
519                                session->receive_delay_task);
520       if (session->client != NULL)
521         {
522           GNUNET_SERVER_receive_done (session->client, 
523                                       GNUNET_SYSERR);
524         }
525     }
526   if (session->client != NULL)
527     {
528       GNUNET_SERVER_client_drop (session->client);
529       session->client = NULL;
530     } 
531   GNUNET_STATISTICS_update (session->plugin->env->stats,
532                             gettext_noop ("# TCP sessions active"),
533                             -1,
534                             GNUNET_NO);      
535   GNUNET_free_non_null (session->connect_addr);
536   GNUNET_free (session);
537 }
538
539
540 /**
541  * Function that can be used by the transport service to transmit
542  * a message using the plugin.   Note that in the case of a
543  * peer disconnecting, the continuation MUST be called
544  * prior to the disconnect notification itself.  This function
545  * will be called with this peer's HELLO message to initiate
546  * a fresh connection to another peer.
547  *
548  * @param cls closure
549  * @param target who should receive this message
550  * @param msg the message to transmit
551  * @param msgbuf_size number of bytes in 'msg'
552  * @param priority how important is the message (most plugins will
553  *                 ignore message priority and just FIFO)
554  * @param timeout how long to wait at most for the transmission (does not
555  *                require plugins to discard the message after the timeout,
556  *                just advisory for the desired delay; most plugins will ignore
557  *                this as well)
558  * @param addr the address to use (can be NULL if the plugin
559  *                is "on its own" (i.e. re-use existing TCP connection))
560  * @param addrlen length of the address in bytes
561  * @param force_address GNUNET_YES if the plugin MUST use the given address,
562  *                otherwise the plugin may use other addresses or
563  *                existing connections (if available)
564  * @param cont continuation to call once the message has
565  *        been transmitted (or if the transport is ready
566  *        for the next transmission call; or if the
567  *        peer disconnected...); can be NULL
568  * @param cont_cls closure for cont
569  * @return number of bytes used (on the physical network, with overheads);
570  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
571  *         and does NOT mean that the message was not transmitted (DV)
572  */
573 static ssize_t
574 tcp_plugin_send (void *cls,
575                  const struct GNUNET_PeerIdentity *target,
576                  const char *msg,
577                  size_t msgbuf_size,
578                  uint32_t priority,
579                  struct GNUNET_TIME_Relative timeout,
580                  const void *addr,
581                  size_t addrlen,
582                  int force_address,
583                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
584 {
585   struct Plugin *plugin = cls;
586   struct Session *session;
587   struct PendingMessage *pm;
588   struct GNUNET_CONNECTION_Handle *sa;
589   int af;
590
591   GNUNET_STATISTICS_update (plugin->env->stats,
592                             gettext_noop ("# bytes TCP was asked to transmit"),
593                             msgbuf_size,
594                             GNUNET_NO);      
595   session = plugin->sessions;
596   /* FIXME: we could do this a cheaper with a hash table
597      where we could restrict the iteration to entries that match
598      the target peer... */
599   while ( (session != NULL) &&
600           (session->client != NULL) &&
601           ( (0 != memcmp (target,
602                           &session->target, 
603                           sizeof (struct GNUNET_PeerIdentity))) ||
604             ( (GNUNET_YES == force_address) &&
605               (addr != NULL) &&
606               ( (addrlen != session->connect_alen) ||
607                 (0 != memcmp (session->connect_addr,
608                               addr,
609                               addrlen)) ) ) ) )
610     session = session->next;
611   if ( (session == NULL) &&
612        (addr == NULL) )
613     {
614 #if DEBUG_TCP
615       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
616                        "tcp",
617                        "Asked to transmit to `%4s' without address and I have no existing connection (failing).\n",
618                        GNUNET_i2s (target));
619 #endif
620       GNUNET_STATISTICS_update (plugin->env->stats,
621                                 gettext_noop ("# bytes discarded by TCP (no address and no connection)"),
622                                 msgbuf_size,
623                                 GNUNET_NO);      
624       return -1;
625     }
626   if (session == NULL)
627     {
628       if (sizeof (struct sockaddr_in) == addrlen)
629         af = AF_INET;
630       else if (sizeof (struct sockaddr_in6) == addrlen)
631         af = AF_INET6;
632       else
633         {
634           GNUNET_break_op (0);
635           return -1;
636         }
637       sa = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
638                                                    af, addr, addrlen,
639                                                    GNUNET_SERVER_MAX_MESSAGE_SIZE);
640       if (sa == NULL)
641         {
642 #if DEBUG_TCP
643           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
644                            "tcp",
645                            "Failed to create connection to `%4s' at `%s'\n",
646                            GNUNET_i2s (target),
647                            GNUNET_a2s (addr, addrlen));
648 #endif
649           GNUNET_STATISTICS_update (plugin->env->stats,
650                                     gettext_noop ("# bytes discarded by TCP (failed to connect)"),
651                                     msgbuf_size,
652                                     GNUNET_NO);      
653           return -1;
654         }
655
656 #if DEBUG_TCP
657       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
658                        "tcp",
659                        "Asked to transmit to `%4s', creating fresh session using address `%s'.\n",
660                        GNUNET_i2s (target),
661                        GNUNET_a2s (addr, addrlen));
662 #endif
663       session = create_session (plugin,
664                                 target,
665                                 GNUNET_SERVER_connect_socket (plugin->server,
666                                                               sa));
667       session->connect_addr = GNUNET_malloc (addrlen);
668       memcpy (session->connect_addr,
669               addr,
670               addrlen);
671       session->connect_alen = addrlen;
672     }
673   GNUNET_assert (session != NULL);
674   GNUNET_assert (session->client != NULL);
675
676   /* create new message entry */
677   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msgbuf_size);
678   pm->msg = (const char*) &pm[1];
679   memcpy (&pm[1], msg, msgbuf_size);
680   pm->message_size = msgbuf_size;
681   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
682   pm->transmit_cont = cont;
683   pm->transmit_cont_cls = cont_cls;
684
685   /* append pm to pending_messages list */
686   GNUNET_CONTAINER_DLL_insert_after (session->pending_messages_head,
687                                      session->pending_messages_tail,
688                                      session->pending_messages_tail,
689                                      pm);
690 #if DEBUG_TCP
691   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
692                    "tcp",
693                    "Asked to transmit %u bytes to `%s', added message to list.\n",
694                    msgbuf_size,
695                    GNUNET_i2s (target));
696 #endif
697   process_pending_messages (session);
698   return msgbuf_size;
699 }
700
701
702 /**
703  * Function that can be called to force a disconnect from the
704  * specified neighbour.  This should also cancel all previously
705  * scheduled transmissions.  Obviously the transmission may have been
706  * partially completed already, which is OK.  The plugin is supposed
707  * to close the connection (if applicable) and no longer call the
708  * transmit continuation(s).
709  *
710  * Finally, plugin MUST NOT call the services's receive function to
711  * notify the service that the connection to the specified target was
712  * closed after a getting this call.
713  *
714  * @param cls closure
715  * @param target peer for which the last transmission is
716  *        to be cancelled
717  */
718 static void
719 tcp_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
720 {
721   struct Plugin *plugin = cls;
722   struct Session *session;
723   struct PendingMessage *pm;
724
725 #if DEBUG_TCP
726   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
727                    "tcp",
728                    "Asked to cancel session with `%4s'\n",
729                    GNUNET_i2s (target));
730 #endif
731   session = plugin->sessions;
732   while (NULL != session)
733     {
734       if (0 == memcmp (target,
735                        &session->target,
736                        sizeof (struct GNUNET_PeerIdentity)))
737         {
738           pm = session->pending_messages_head;
739           while (pm != NULL)
740             {
741               pm->transmit_cont = NULL;
742               pm->transmit_cont_cls = NULL;
743               pm = pm->next;
744             }
745           if (session->client != NULL)
746             {
747               GNUNET_SERVER_client_drop (session->client);
748               session->client = NULL;
749             }
750           /* rest of the clean-up of the session will be done as part of
751              disconnect_notify which should be triggered any time now
752              (or which may be triggering this call in the first place) */
753         }
754       session = session->next;
755     }
756 }
757
758
759 struct PrettyPrinterContext
760 {
761   GNUNET_TRANSPORT_AddressStringCallback asc;
762   void *asc_cls;
763   uint16_t port;
764 };
765
766
767 /**
768  * Append our port and forward the result.
769  */
770 static void
771 append_port (void *cls, const char *hostname)
772 {
773   struct PrettyPrinterContext *ppc = cls;
774   char *ret;
775
776   if (hostname == NULL)
777     {
778       ppc->asc (ppc->asc_cls, NULL);
779       GNUNET_free (ppc);
780       return;
781     }
782   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
783   ppc->asc (ppc->asc_cls, ret);
784   GNUNET_free (ret);
785 }
786
787
788 /**
789  * Convert the transports address to a nice, human-readable
790  * format.
791  *
792  * @param cls closure
793  * @param type name of the transport that generated the address
794  * @param addr one of the addresses of the host, NULL for the last address
795  *        the specific address format depends on the transport
796  * @param addrlen length of the address
797  * @param numeric should (IP) addresses be displayed in numeric form?
798  * @param timeout after how long should we give up?
799  * @param asc function to call on each string
800  * @param asc_cls closure for asc
801  */
802 static void
803 tcp_plugin_address_pretty_printer (void *cls,
804                                    const char *type,
805                                    const void *addr,
806                                    size_t addrlen,
807                                    int numeric,
808                                    struct GNUNET_TIME_Relative timeout,
809                                    GNUNET_TRANSPORT_AddressStringCallback asc,
810                                    void *asc_cls)
811 {
812   struct Plugin *plugin = cls;
813   const struct sockaddr_in *v4;
814   const struct sockaddr_in6 *v6;
815   struct PrettyPrinterContext *ppc;
816
817   if ((addrlen != sizeof (struct sockaddr_in)) &&
818       (addrlen != sizeof (struct sockaddr_in6)))
819     {
820       /* invalid address */
821       GNUNET_break_op (0);
822       asc (asc_cls, NULL);
823       return;
824     }
825   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
826   ppc->asc = asc;
827   ppc->asc_cls = asc_cls;
828   if (addrlen == sizeof (struct sockaddr_in))
829     {
830       v4 = (const struct sockaddr_in *) addr;
831       ppc->port = ntohs (v4->sin_port);
832     }
833   else
834     {
835       v6 = (const struct sockaddr_in6 *) addr;
836       ppc->port = ntohs (v6->sin6_port);
837
838     }
839   GNUNET_RESOLVER_hostname_get (plugin->env->sched,
840                                 plugin->env->cfg,
841                                 addr,
842                                 addrlen,
843                                 !numeric, timeout, &append_port, ppc);
844 }
845
846
847 /**
848  * Check if the given port is plausible (must be either
849  * our listen port or our advertised port).  If it is
850  * neither, we return one of these two ports at random.
851  *
852  * @return either in_port or a more plausible port
853  */
854 static uint16_t
855 check_port (struct Plugin *plugin, uint16_t in_port)
856 {
857   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
858     return in_port;
859   return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
860                                     2) == 0)
861     ? plugin->open_port : plugin->adv_port;
862 }
863
864
865 /**
866  * Another peer has suggested an address for this peer and transport
867  * plugin.  Check that this could be a valid address.
868  *
869  * @param cls closure
870  * @param addr pointer to the address
871  * @param addrlen length of addr
872  * @return GNUNET_OK if this is a plausible address for this peer
873  *         and transport
874  */
875 static int
876 tcp_plugin_check_address (void *cls, void *addr, size_t addrlen)
877 {
878   struct Plugin *plugin = cls;
879   char buf[sizeof (struct sockaddr_in6)];
880   struct sockaddr_in *v4;
881   struct sockaddr_in6 *v6;
882
883   if ((addrlen != sizeof (struct sockaddr_in)) &&
884       (addrlen != sizeof (struct sockaddr_in6)))
885     {
886       GNUNET_break_op (0);
887       return GNUNET_SYSERR;
888     }
889   memcpy (buf, addr, sizeof (struct sockaddr_in6));
890   if (addrlen == sizeof (struct sockaddr_in))
891     {
892       v4 = (struct sockaddr_in *) buf;
893       v4->sin_port = htons (check_port (plugin, ntohs (v4->sin_port)));
894     }
895   else
896     {
897       v6 = (struct sockaddr_in6 *) buf;
898       v6->sin6_port = htons (check_port (plugin, ntohs (v6->sin6_port)));
899     }
900 #if DEBUG_TCP
901   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
902                    "tcp",
903                    "Informing transport service about my address `%s'.\n",
904                    GNUNET_a2s (addr, addrlen));
905 #endif
906   return GNUNET_OK;
907 }
908
909
910 /**
911  * We've received a welcome from this peer via TCP.  Possibly create a
912  * fresh client record and send back our welcome.
913  *
914  * @param cls closure
915  * @param client identification of the client
916  * @param message the actual message
917  */
918 static void
919 handle_tcp_welcome (void *cls,
920                     struct GNUNET_SERVER_Client *client,
921                     const struct GNUNET_MessageHeader *message)
922 {
923   struct Plugin *plugin = cls;
924   const struct WelcomeMessage *wm = (const struct WelcomeMessage *) message;
925   struct Session *session;
926   size_t alen;
927   void *vaddr;
928
929 #if DEBUG_TCP
930   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
931                    "tcp",
932                    "Received %s message from a `%4s/%p'.\n", 
933                    "WELCOME",
934                    GNUNET_i2s (&wm->clientIdentity), client);
935 #endif
936   GNUNET_STATISTICS_update (plugin->env->stats,
937                             gettext_noop ("# TCP WELCOME messages received"),
938                             1,
939                             GNUNET_NO);      
940   session = find_session_by_client (plugin, client);
941   if (session == NULL)
942     {
943       GNUNET_SERVER_client_keep (client);
944       session = create_session (plugin,
945                                 &wm->clientIdentity, client);
946       if (GNUNET_OK ==
947           GNUNET_SERVER_client_get_address (client, &vaddr, &alen))
948         {
949 #if DEBUG_TCP
950           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
951                            "tcp",
952                            "Found address `%s' for incoming connection %p\n",
953                            GNUNET_a2s (vaddr, alen),
954                            client);
955 #endif
956           session->connect_addr = vaddr;
957           session->connect_alen = alen;
958         }
959       else
960         {
961 #if DEBUG_TCP
962           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
963                            "tcp",
964                            "Did not obtain TCP socket address for incoming connection\n");
965 #endif
966         }
967 #if DEBUG_TCP
968       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
969                        "tcp",
970                        "Creating new session %p for connection %p\n",
971                        session, client);
972 #endif
973       process_pending_messages (session);
974     }
975   if (session->expecting_welcome != GNUNET_YES)
976     {
977       GNUNET_break_op (0);
978       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
979       return;
980     }
981   session->expecting_welcome = GNUNET_NO;
982   GNUNET_SERVER_receive_done (client, GNUNET_OK);
983 }
984
985
986 /**
987  * Task to signal the server that we can continue
988  * receiving from the TCP client now.
989  */
990 static void
991 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
992 {
993   struct Session *session = cls;
994   struct GNUNET_TIME_Relative delay;
995
996   session->receive_delay_task = GNUNET_SCHEDULER_NO_TASK;
997   delay = session->plugin->env->receive (session->plugin->env->cls,
998                                          &session->target,
999                                          NULL, 0, NULL, 0);
1000   if (delay.value == 0)
1001     GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1002   else
1003     session->receive_delay_task = 
1004       GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1005                                     delay, &delayed_done, session);
1006 }
1007
1008
1009 /**
1010  * We've received data for this peer via TCP.  Unbox,
1011  * compute latency and forward.
1012  *
1013  * @param cls closure
1014  * @param client identification of the client
1015  * @param message the actual message
1016  */
1017 static void
1018 handle_tcp_data (void *cls,
1019                  struct GNUNET_SERVER_Client *client,
1020                  const struct GNUNET_MessageHeader *message)
1021 {
1022   struct Plugin *plugin = cls;
1023   struct Session *session;
1024   struct GNUNET_TIME_Relative delay;
1025
1026   session = find_session_by_client (plugin, client);
1027   if (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME == ntohs(message->type))
1028     {
1029       /* We don't want to propagate WELCOME messages up! */
1030       GNUNET_SERVER_receive_done (client, GNUNET_OK);
1031       return; 
1032     }    
1033   if ( (NULL == session) || (GNUNET_NO != session->expecting_welcome))
1034     {
1035       GNUNET_break_op (0);
1036       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1037       return;
1038     }
1039 #if DEBUG_TCP
1040   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1041                    "tcp", 
1042                    "Passing %u bytes of type %u from `%4s' to transport service.\n",
1043                    (unsigned int) ntohs (message->size), 
1044                    (unsigned int) ntohs (message->type),
1045                    GNUNET_i2s (&session->target));
1046 #endif
1047   GNUNET_STATISTICS_update (plugin->env->stats,
1048                             gettext_noop ("# bytes received via TCP"),
1049                             ntohs (message->size),
1050                             GNUNET_NO); 
1051   delay = plugin->env->receive (plugin->env->cls, &session->target, message, 1,
1052                                 session->connect_addr,
1053                                 session->connect_alen);
1054
1055   if (delay.value == 0)
1056     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1057   else
1058     session->receive_delay_task = 
1059       GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1060                                     delay, &delayed_done, session);
1061 }
1062
1063
1064 /**
1065  * Handlers for the various TCP messages.
1066  */
1067 static struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1068   {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME,
1069    sizeof (struct WelcomeMessage)},
1070   {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_ALL, 0},
1071   {NULL, NULL, 0, 0}
1072 };
1073
1074
1075 /**
1076  * Functions with this signature are called whenever a peer
1077  * is disconnected on the network level.
1078  *
1079  * @param cls closure
1080  * @param client identification of the client
1081  */
1082 static void
1083 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1084 {
1085   struct Plugin *plugin = cls;
1086   struct Session *session;
1087
1088   if (client == NULL)
1089     return;
1090   session = find_session_by_client (plugin, client);
1091   if (session == NULL)
1092     return;                     /* unknown, nothing to do */
1093 #if DEBUG_TCP
1094   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1095                    "tcp",
1096                    "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1097                    GNUNET_i2s (&session->target),
1098                    (session->connect_addr != NULL) ?
1099                    GNUNET_a2s (session->connect_addr,
1100                                session->connect_alen) : "*", client);
1101 #endif
1102   disconnect_session (session);
1103 }
1104
1105
1106 /**
1107  * Add the IP of our network interface to the list of
1108  * our external IP addresses.
1109  */
1110 static int
1111 process_interfaces (void *cls,
1112                     const char *name,
1113                     int isDefault,
1114                     const struct sockaddr *addr, socklen_t addrlen)
1115 {
1116   struct Plugin *plugin = cls;
1117   int af;
1118   struct sockaddr_in *v4;
1119   struct sockaddr_in6 *v6;
1120
1121   af = addr->sa_family;
1122   if (af == AF_INET)
1123     {
1124       v4 = (struct sockaddr_in *) addr;
1125       v4->sin_port = htons (plugin->adv_port);
1126     }
1127   else
1128     {
1129       GNUNET_assert (af == AF_INET6);
1130       v6 = (struct sockaddr_in6 *) addr;
1131       v6->sin6_port = htons (plugin->adv_port);
1132     }
1133   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1134                    GNUNET_ERROR_TYPE_BULK,
1135                    "tcp", _("Found address `%s' (%s)\n"),
1136                    GNUNET_a2s (addr, addrlen), name);
1137   plugin->env->notify_address (plugin->env->cls,
1138                                "tcp",
1139                                addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
1140   return GNUNET_OK;
1141 }
1142
1143
1144 /**
1145  * Function called by the resolver for each address obtained from DNS
1146  * for our own hostname.  Add the addresses to the list of our
1147  * external IP addresses.
1148  *
1149  * @param cls closure
1150  * @param addr one of the addresses of the host, NULL for the last address
1151  * @param addrlen length of the address
1152  */
1153 static void
1154 process_hostname_ips (void *cls,
1155                       const struct sockaddr *addr, socklen_t addrlen)
1156 {
1157   struct Plugin *plugin = cls;
1158
1159   if (addr == NULL)
1160     {
1161       plugin->hostname_dns = NULL;
1162       return;
1163     }
1164   process_interfaces (plugin, "<hostname>", GNUNET_YES, addr, addrlen);
1165 }
1166
1167
1168 /**
1169  * Entry point for the plugin.
1170  */
1171 void *
1172 libgnunet_plugin_transport_tcp_init (void *cls)
1173 {
1174   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1175   struct GNUNET_TRANSPORT_PluginFunctions *api;
1176   struct Plugin *plugin;
1177   struct GNUNET_SERVICE_Context *service;
1178   unsigned long long aport;
1179   unsigned long long bport;
1180   unsigned int i;
1181
1182   service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
1183   if (service == NULL)
1184     {
1185       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
1186                        "tcp",
1187                        _
1188                        ("Failed to start service for `%s' transport plugin.\n"),
1189                        "tcp");
1190       return NULL;
1191     }
1192   aport = 0;
1193   if ((GNUNET_OK !=
1194        GNUNET_CONFIGURATION_get_value_number (env->cfg,
1195                                               "transport-tcp",
1196                                               "PORT",
1197                                               &bport)) ||
1198       (bport > 65535) ||
1199       ((GNUNET_OK ==
1200         GNUNET_CONFIGURATION_get_value_number (env->cfg,
1201                                                "transport-tcp",
1202                                                "ADVERTISED-PORT",
1203                                                &aport)) && (aport > 65535)))
1204     {
1205       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
1206                        "tcp",
1207                        _
1208                        ("Require valid port number for service `%s' in configuration!\n"),
1209                        "transport-tcp");
1210       GNUNET_SERVICE_stop (service);
1211       return NULL;
1212     }
1213   if (aport == 0)
1214     aport = bport;
1215   plugin = GNUNET_malloc (sizeof (struct Plugin));
1216   plugin->open_port = bport;
1217   plugin->adv_port = aport;
1218   plugin->env = env;
1219   plugin->lsock = NULL;
1220   plugin->statistics = NULL;
1221   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1222   api->cls = plugin;
1223   api->send = &tcp_plugin_send;
1224   api->disconnect = &tcp_plugin_disconnect;
1225   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
1226   api->check_address = &tcp_plugin_check_address;
1227   plugin->service = service;
1228   plugin->server = GNUNET_SERVICE_get_server (service);
1229   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
1230   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
1231   for (i = 0;
1232        i <
1233        sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
1234        i++)
1235     plugin->handlers[i].callback_cls = plugin;
1236   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
1237
1238   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1239                    "tcp", _("TCP transport listening on port %llu\n"), bport);
1240   if (aport != bport)
1241     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1242                      "tcp",
1243                      _
1244                      ("TCP transport advertises itself as being on port %llu\n"),
1245                      aport);
1246   GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify,
1247                                    plugin);
1248   /* FIXME: do the two calls below periodically again and
1249      not just once (since the info we get might change...) */
1250   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
1251   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
1252                                                            env->cfg,
1253                                                            AF_UNSPEC,
1254                                                            HOSTNAME_RESOLVE_TIMEOUT,
1255                                                            &process_hostname_ips,
1256                                                            plugin);
1257   return api;
1258 }
1259
1260
1261 /**
1262  * Exit point from the plugin.
1263  */
1264 void *
1265 libgnunet_plugin_transport_tcp_done (void *cls)
1266 {
1267   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1268   struct Plugin *plugin = api->cls;
1269   struct Session *session;
1270
1271   while (NULL != (session = plugin->sessions))
1272     disconnect_session (session);
1273   if (NULL != plugin->hostname_dns)
1274     {
1275       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
1276       plugin->hostname_dns = NULL;
1277     }
1278   GNUNET_SERVICE_stop (plugin->service);
1279   GNUNET_free (plugin->handlers);
1280   GNUNET_free (plugin);
1281   GNUNET_free (api);
1282   return NULL;
1283 }
1284
1285 /* end of plugin_transport_tcp.c */