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