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