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