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