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