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