further simplify API
[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 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_os_lib.h"
31 #include "gnunet_peerinfo_service.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  * After how long do we expire an address that we
46  * learned from another peer if it is not reconfirmed
47  * by anyone?
48  */
49 #define LEARNED_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 6)
50
51 /**
52  * How long until we give up on transmitting the welcome message?
53  */
54 #define WELCOME_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
55
56 /**
57  * How long until we give up on transmitting the welcome message?
58  */
59 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
60
61 /**
62  * For how many messages back to we keep transmission times?
63  */
64 #define ACK_LOG_SIZE 32
65
66
67
68 /**
69  * Message used to ask a peer to validate receipt (to check an address
70  * from a HELLO).  Followed by the address used.  Note that the
71  * recipients response does not affirm that he has this address,
72  * only that he got the challenge message.
73  */
74 struct ValidationChallengeMessage
75 {
76
77   /**
78    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PING
79    */
80   struct GNUNET_MessageHeader header;
81
82   /**
83    * Random challenge number (in network byte order).
84    */
85   uint32_t challenge GNUNET_PACKED;
86
87   /**
88    * Who is the intended recipient?
89    */
90   struct GNUNET_PeerIdentity target;
91
92 };
93
94
95 /**
96  * Message used to validate a HELLO.  The challenge is included in the
97  * confirmation to make matching of replies to requests possible.  The
98  * signature signs the original challenge number, our public key, the
99  * sender's address (so that the sender can check that the address we
100  * saw is plausible for him and possibly detect a MiM attack) and a
101  * timestamp (to limit replay).<p>
102  *
103  * This message is followed by the address of the
104  * client that we are observing (which is part of what
105  * is being signed).
106  */
107 struct ValidationChallengeResponse
108 {
109
110   /**
111    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PONG
112    */
113   struct GNUNET_MessageHeader header;
114
115   /**
116    * For padding, always zero.
117    */
118   uint32_t reserved GNUNET_PACKED;
119
120   /**
121    * Signature.
122    */
123   struct GNUNET_CRYPTO_RsaSignature signature;
124
125   /**
126    * What are we signing and why?
127    */
128   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
129
130   /**
131    * Random challenge number (in network byte order).
132    */
133   uint32_t challenge GNUNET_PACKED;
134
135   /**
136    * Who signed this message?
137    */
138   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded signer;
139
140 };
141
142
143
144 /**
145  * Initial handshake message for a session.  This header
146  * is followed by the address that the other peer used to
147  * connect to us (so that we may learn it) or the address
148  * that the other peer got from the accept call.
149  */
150 struct WelcomeMessage
151 {
152   struct GNUNET_MessageHeader header;
153
154   /**
155    * Identity of the node connecting (TCP client)
156    */
157   struct GNUNET_PeerIdentity clientIdentity;
158
159 };
160
161
162 /**
163  * Encapsulation for normal TCP traffic.
164  */
165 struct DataMessage
166 {
167   struct GNUNET_MessageHeader header;
168
169   /**
170    * For alignment.
171    */
172   uint32_t reserved GNUNET_PACKED;
173
174   /**
175    * Number of the last message that was received from the other peer.
176    */
177   uint64_t ack_in GNUNET_PACKED;
178
179   /**
180    * Number of this outgoing message.
181    */
182   uint64_t ack_out GNUNET_PACKED;
183
184   /**
185    * How long was sending this ack delayed by the other peer
186    * (estimate).  The receiver of this message can use the delay
187    * between sending his message number 'ack' and receiving this ack
188    * minus the delay as an estimate of the round-trip time.
189    */
190   struct GNUNET_TIME_RelativeNBO delay;
191
192 };
193
194
195 /**
196  * Encapsulation of all of the state of the plugin.
197  */
198 struct Plugin;
199
200
201 /**
202  * Information kept for each message that is yet to
203  * be transmitted.
204  */
205 struct PendingMessage
206 {
207
208   /**
209    * This is a linked list.
210    */
211   struct PendingMessage *next;
212
213   /**
214    * The pending message, pointer to the end
215    * of this struct, do not free!
216    */
217   struct GNUNET_MessageHeader *msg;
218
219   /**
220    * Continuation function to call once the message
221    * has been sent.  Can be  NULL if there is no
222    * continuation to call.
223    */
224   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
225
226   /**
227    * Closure for transmit_cont.
228    */
229   void *transmit_cont_cls;
230
231   /**
232    * Timeout value for the pending message.
233    */
234   struct GNUNET_TIME_Absolute timeout;
235
236   /**
237    * GNUNET_YES if this is a welcome message;
238    * otherwise this should be a DATA message.
239    */
240   int is_welcome;
241
242 };
243
244
245 /**
246  * Session handle for TCP connections.
247  */
248 struct Session
249 {
250
251   /**
252    * Stored in a linked list.
253    */
254   struct Session *next;
255
256   /**
257    * Pointer to the global plugin struct.
258    */
259   struct Plugin *plugin;
260
261   /**
262    * The client (used to identify this connection)
263    */
264   struct GNUNET_SERVER_Client *client;
265
266   /**
267    * gnunet-service-transport context for this connection.
268    */
269   struct ReadyList *service_context;
270
271   /**
272    * Messages currently pending for transmission
273    * to this peer, if any.
274    */
275   struct PendingMessage *pending_messages;
276
277   /**
278    * Handle for pending transmission request.
279    */
280   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
281
282   /**
283    * To whom are we talking to (set to our identity
284    * if we are still waiting for the welcome message)
285    */
286   struct GNUNET_PeerIdentity target;
287
288   /**
289    * At what time did we reset last_received last?
290    */
291   struct GNUNET_TIME_Absolute last_quota_update;
292
293   /**
294    * Context for our iteration to find HELLOs for this peer.  NULL
295    * after iteration has completed.
296    */
297   struct GNUNET_PEERINFO_IteratorContext *ic;
298
299   /**
300    * Address of the other peer if WE initiated the connection
301    * (and hence can be sure what it is), otherwise NULL.
302    */
303   void *connect_addr;
304
305   /**
306    * How many bytes have we received since the "last_quota_update"
307    * timestamp?
308    */
309   uint64_t last_received;
310
311   /**
312    * Our current latency estimate (in ms).
313    */
314   double latency_estimate;
315
316   /**
317    * Time when we generated the last ACK_LOG_SIZE acks.
318    * (the "last" refers to the "out_msg_counter" here)
319    */
320   struct GNUNET_TIME_Absolute gen_time[ACK_LOG_SIZE];
321
322   /**
323    * Our current sequence number.
324    */
325   uint64_t out_msg_counter;
326
327   /**
328    * Highest received incoming sequence number.
329    */
330   uint64_t max_in_msg_counter;
331
332   /**
333    * Number of bytes per ms that this peer is allowed
334    * to send to us.
335    */
336   uint32_t quota_in;
337
338   /**
339    * Length of connect_addr, can be 0.
340    */
341   size_t connect_alen;
342
343   /**
344    * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
345    * GNUNET_SYSERR is used to mark non-welcoming connections (HELLO
346    * validation only).
347    */
348   int expecting_welcome;
349
350 };
351
352
353 /**
354  * Encapsulation of all of the state of the plugin.
355  */
356 struct Plugin
357 {
358   /**
359    * Our environment.
360    */
361   struct GNUNET_TRANSPORT_PluginEnvironment *env;
362
363   /**
364    * The listen socket.
365    */
366   struct GNUNET_CONNECTION_Handle *lsock;
367
368   /**
369    * List of open TCP sessions.
370    */
371   struct Session *sessions;
372
373   /**
374    * Handle for the statistics service.
375    */
376   struct GNUNET_STATISTICS_Handle *statistics;
377
378   /**
379    * Handle to the network service.
380    */
381   struct GNUNET_SERVICE_Context *service;
382
383   /**
384    * Handle to the server for this service.
385    */
386   struct GNUNET_SERVER_Handle *server;
387
388   /**
389    * Copy of the handler array where the closures are
390    * set to this struct's instance.
391    */
392   struct GNUNET_SERVER_MessageHandler *handlers;
393
394   /**
395    * Handle for request of hostname resolution, non-NULL if pending.
396    */
397   struct GNUNET_RESOLVER_RequestHandle *hostname_dns;
398
399   /**
400    * ID of task used to update our addresses when one expires.
401    */
402   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
403
404   /**
405    * Port that we are actually listening on.
406    */
407   uint16_t open_port;
408
409   /**
410    * Port that the user said we would have visible to the
411    * rest of the world.
412    */
413   uint16_t adv_port;
414
415 };
416
417
418 /**
419  * Find the session handle for the given peer.
420  */
421 static struct Session *
422 find_session_by_target (struct Plugin *plugin,
423                         const struct GNUNET_PeerIdentity *target)
424 {
425   struct Session *ret;
426
427   ret = plugin->sessions;
428   while ((ret != NULL) &&
429          ( (GNUNET_SYSERR == ret->expecting_welcome) ||
430            (0 != memcmp (target,
431                          &ret->target, sizeof (struct GNUNET_PeerIdentity)))))
432     ret = ret->next;
433   return ret;
434 }
435
436
437 /**
438  * Find the session handle for the given peer.
439  */
440 static struct Session *
441 find_session_by_client (struct Plugin *plugin,
442                         const struct GNUNET_SERVER_Client *client)
443 {
444   struct Session *ret;
445
446   ret = plugin->sessions;
447   while ((ret != NULL) && (client != ret->client))
448     ret = ret->next;
449   return ret;
450 }
451
452
453 /**
454  * Create a welcome message.
455  */
456 static struct PendingMessage *
457 create_welcome (size_t addrlen, const void *addr, struct Plugin *plugin)
458 {
459   struct PendingMessage *pm;
460   struct WelcomeMessage *welcome;
461
462   pm = GNUNET_malloc (sizeof (struct PendingMessage) +
463                       sizeof (struct WelcomeMessage) + addrlen);
464   pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
465   welcome = (struct WelcomeMessage *) &pm[1];
466   welcome->header.size = htons (sizeof (struct WelcomeMessage) + addrlen);
467   welcome->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME);
468   GNUNET_CRYPTO_hash (plugin->env->my_public_key,
469                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
470                       &welcome->clientIdentity.hashPubKey);
471   memcpy (&welcome[1], addr, addrlen);
472   pm->timeout = GNUNET_TIME_relative_to_absolute (WELCOME_TIMEOUT);
473   pm->is_welcome = GNUNET_YES;
474   return pm;
475 }
476
477
478 /**
479  * Create a new session using the specified address
480  * for the welcome message.
481  *
482  * @param plugin us
483  * @param target peer to connect to
484  * @param client client to use
485  * @param addrlen IPv4 or IPv6
486  * @param addr either struct sockaddr_in or struct sockaddr_in6
487  * @return NULL connection failed / invalid address
488  */
489 static struct Session *
490 create_session (struct Plugin *plugin,
491                 const struct GNUNET_PeerIdentity *target,
492                 struct GNUNET_SERVER_Client *client,
493                 const void *addr, size_t addrlen)
494 {
495   struct Session *ret;
496
497   ret = GNUNET_malloc (sizeof (struct Session));
498   ret->plugin = plugin;
499   ret->next = plugin->sessions;
500   plugin->sessions = ret;
501   ret->client = client;
502   ret->target = *target;
503   ret->last_quota_update = GNUNET_TIME_absolute_get ();
504   ret->quota_in = plugin->env->default_quota_in;
505   ret->expecting_welcome = GNUNET_YES;
506   ret->pending_messages = create_welcome (addrlen, addr, plugin);
507   return ret;
508 }
509
510
511 /**
512  * If we have pending messages, ask the server to
513  * transmit them (schedule the respective tasks, etc.)
514  *
515  * @param session for which session should we do this
516  */
517 static void process_pending_messages (struct Session *session);
518
519
520 /**
521  * Function called to notify a client about the socket
522  * begin ready to queue more data.  "buf" will be
523  * NULL and "size" zero if the socket was closed for
524  * writing in the meantime.
525  *
526  * @param cls closure
527  * @param size number of bytes available in buf
528  * @param buf where the callee should write the message
529  * @return number of bytes written to buf
530  */
531 static size_t
532 do_transmit (void *cls, size_t size, void *buf)
533 {
534   struct Session *session = cls;
535   struct PendingMessage *pm;
536   char *cbuf;
537   uint16_t msize;
538   size_t ret;
539   struct DataMessage *dm;
540
541   session->transmit_handle = NULL;
542   if (buf == NULL)
543     {
544 #if DEBUG_TCP
545       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
546                        "tcp", 
547                        "Timeout trying to transmit to peer `%4s', discarding message queue.\n",
548                        GNUNET_i2s(&session->target));
549 #endif
550       /* timeout */
551       while (NULL != (pm = session->pending_messages))
552         {
553           session->pending_messages = pm->next;
554 #if DEBUG_TCP
555           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
556                            "tcp", 
557                            "Failed to transmit message of type %u to `%4s'.\n",
558                            ntohs(pm->msg->type),
559                            GNUNET_i2s(&session->target));
560 #endif
561           if (pm->transmit_cont != NULL)
562             pm->transmit_cont (pm->transmit_cont_cls,
563                                session->service_context,
564                                &session->target, GNUNET_SYSERR);            
565           GNUNET_free (pm);
566         }
567       return 0;
568     }
569   ret = 0;
570   cbuf = buf;
571   while (NULL != (pm = session->pending_messages))
572     {
573       if (pm->is_welcome)
574         {
575           if (size < (msize = ntohs (pm->msg->size)))
576             break;
577           memcpy (cbuf, pm->msg, msize);
578           cbuf += msize;
579           ret += msize;
580           size -= msize;
581         }
582       else
583         {
584           if (size <
585               sizeof (struct DataMessage) + (msize = ntohs (pm->msg->size)))
586             break;
587           dm = (struct DataMessage *) cbuf;
588           dm->header.size = htons (sizeof (struct DataMessage) + msize);
589           dm->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_DATA);
590           dm->ack_out = GNUNET_htonll (++session->out_msg_counter);
591           dm->ack_in = GNUNET_htonll (session->max_in_msg_counter);
592           cbuf += sizeof (struct DataMessage);
593           ret += sizeof (struct DataMessage);
594           size -= sizeof (struct DataMessage);
595           memcpy (cbuf, pm->msg, msize);
596           cbuf += msize;
597           ret += msize;
598           size -= msize;
599         }
600       session->pending_messages = pm->next;
601       if (pm->transmit_cont != NULL)
602         pm->transmit_cont (pm->transmit_cont_cls,
603                            session->service_context,
604                            &session->target, GNUNET_OK);
605       GNUNET_free (pm);
606       session->gen_time[session->out_msg_counter % ACK_LOG_SIZE]
607         = GNUNET_TIME_absolute_get ();
608     }
609   process_pending_messages (session);
610 #if DEBUG_TCP
611   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
612                    "tcp", "Transmitting %u bytes\n", ret);
613 #endif
614   return ret;
615 }
616
617
618 /**
619  * If we have pending messages, ask the server to
620  * transmit them (schedule the respective tasks, etc.)
621  *
622  * @param session for which session should we do this
623  */
624 static void
625 process_pending_messages (struct Session *session)
626 {
627   GNUNET_assert (session->client != NULL);
628   if (session->pending_messages == NULL)
629     return;
630   if (session->transmit_handle != NULL)
631     return;
632   session->transmit_handle
633     = GNUNET_SERVER_notify_transmit_ready (session->client,
634                                            ntohs (session->
635                                                   pending_messages->msg->
636                                                   size) +
637                                            (session->
638                                             pending_messages->is_welcome ? 0 :
639                                             sizeof (struct DataMessage)),
640                                            GNUNET_TIME_absolute_get_remaining
641                                            (session->
642                                             pending_messages[0].timeout),
643                                            &do_transmit, session);
644 }
645
646
647
648 /**
649  * Create a new session connecting to the specified
650  * target at the specified address.  The session will
651  * be used to verify an address in a HELLO and should
652  * not expect to receive a WELCOME.
653  *
654  * @param plugin us
655  * @param target peer to connect to
656  * @param addrlen IPv4 or IPv6
657  * @param addr either struct sockaddr_in or struct sockaddr_in6
658  * @return NULL connection failed / invalid address
659  */
660 static struct Session *
661 connect_and_create_validation_session (struct Plugin *plugin,
662                                        const struct GNUNET_PeerIdentity *target,
663                                        const void *addr, size_t addrlen)
664 {
665   struct GNUNET_SERVER_Client *client;
666   struct GNUNET_CONNECTION_Handle *conn;
667   struct Session *session;
668   int af;
669
670   if (addrlen == sizeof (struct sockaddr_in))
671     af = AF_INET;
672   else if (addrlen == sizeof (struct sockaddr_in6))
673     af = AF_INET6;    
674   else
675     {
676       GNUNET_break_op (0);
677       return NULL;              /* invalid address */
678     }
679   conn = GNUNET_CONNECTION_create_from_sockaddr (plugin->env->sched,
680                                                      af,
681                                                      addr,
682                                                      addrlen,
683                                                      GNUNET_SERVER_MAX_MESSAGE_SIZE);
684   if (conn == NULL)
685     {
686 #if DEBUG_TCP
687       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
688                        "tcp",
689                        "Failed to create connection to peer at `%s'.\n",
690                        GNUNET_a2s(addr, addrlen));
691 #endif
692       return NULL;
693     }
694   client = GNUNET_SERVER_connect_socket (plugin->server, conn);
695   GNUNET_assert (client != NULL);
696   session = create_session (plugin, target, client, addr, addrlen);
697   /* kill welcome */
698   GNUNET_free (session->pending_messages);
699   session->pending_messages = NULL;
700   session->connect_alen = addrlen;
701   session->connect_addr = GNUNET_malloc (addrlen);
702   session->expecting_welcome = GNUNET_SYSERR;  
703   memcpy (session->connect_addr, addr, addrlen);
704 #if DEBUG_TCP
705   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
706                    "tcp",
707                    "Creating new session %p with `%s' for `%4s' based on `%s' request.\n",
708                    session, 
709                    GNUNET_a2s (addr, addrlen),
710                    GNUNET_i2s (&session->target),
711                    "VALIDATE");
712 #endif
713   return session;
714 }
715
716
717 /**
718  * Function that can be used by the transport service to validate that
719  * another peer is reachable at a particular address (even if we
720  * already have a connection to this peer, this function is required
721  * to establish a new one).
722  *
723  * @param cls closure
724  * @param target who should receive this message
725  * @param challenge challenge code to use
726  * @param addrlen length of the address
727  * @param addr the address
728  * @param timeout how long should we try to transmit these?
729  * @return GNUNET_OK if the transmission has been scheduled
730  */
731 static int
732 tcp_plugin_validate (void *cls,
733                      const struct GNUNET_PeerIdentity *target,
734                      uint32_t challenge,
735                      struct GNUNET_TIME_Relative timeout,
736                      const void *addr, size_t addrlen)
737 {
738   struct Plugin *plugin = cls;
739   struct Session *session;
740   struct PendingMessage *pm;
741   struct ValidationChallengeMessage *vcm;
742
743   session = connect_and_create_validation_session (plugin, target, addr, addrlen);
744   if (session == NULL)
745     {
746 #if DEBUG_TCP
747       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
748                        "tcp", "Failed to create fresh session.\n");
749 #endif
750       return GNUNET_SYSERR;
751     }
752   pm = GNUNET_malloc (sizeof (struct PendingMessage) +
753                       sizeof (struct ValidationChallengeMessage) + addrlen);
754   pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
755   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
756   pm->is_welcome = GNUNET_YES;
757   vcm = (struct ValidationChallengeMessage*) &pm[1];
758   vcm->header.size =
759     htons (sizeof (struct ValidationChallengeMessage) + addrlen);
760   vcm->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PING);
761   vcm->challenge = htonl(challenge);
762   vcm->target = *target;
763   memcpy (&vcm[1], addr, addrlen);
764   GNUNET_assert (session->pending_messages == NULL);
765   session->pending_messages = pm;
766   process_pending_messages (session);
767   return GNUNET_OK;
768 }
769
770
771 /**
772  * Functions with this signature are called whenever we need
773  * to close a session due to a disconnect or failure to
774  * establish a connection.
775  *
776  * @param session session to close down
777  */
778 static void
779 disconnect_session (struct Session *session)
780 {
781   struct Session *prev;
782   struct Session *pos;
783   struct PendingMessage *pm;
784
785 #if DEBUG_TCP
786   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
787                    "tcp",
788                    "Disconnecting from `%4s' at %s (session %p).\n", 
789                    GNUNET_i2s(&session->target),
790                    (session->connect_addr != NULL) ? 
791                    GNUNET_a2s(session->connect_addr,
792                               session->connect_alen) : "*",
793                    session);
794 #endif
795   /* remove from session list */
796   prev = NULL;
797   pos = session->plugin->sessions;
798   while (pos != session)
799     {
800       prev = pos;
801       pos = pos->next;
802     }
803   if (prev == NULL)
804     session->plugin->sessions = session->next;
805   else
806     prev->next = session->next;
807   /* clean up state */
808   if (session->ic != NULL)
809     {
810       GNUNET_PEERINFO_iterate_cancel (session->ic);
811       session->ic = NULL;
812     }
813   if (session->transmit_handle != NULL)
814     {
815       GNUNET_CONNECTION_notify_transmit_ready_cancel (session->transmit_handle);
816       session->transmit_handle = NULL;
817     }
818   while (NULL != (pm = session->pending_messages))
819     {
820 #if DEBUG_TCP
821       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
822                        "tcp",
823                        pm->transmit_cont != NULL 
824                        ? "Could not deliver message of type %u to `%4s'.\n" 
825                        : "Could not deliver message of type %u to `%4s', notifying.\n",
826                        ntohs(pm->msg->type),                   
827                        GNUNET_i2s(&session->target));
828 #endif
829       session->pending_messages = pm->next;
830       if (NULL != pm->transmit_cont)
831         pm->transmit_cont (pm->transmit_cont_cls,
832                            session->service_context,
833                            &session->target, GNUNET_SYSERR);
834       GNUNET_free (pm);
835     }
836   if (GNUNET_NO == session->expecting_welcome)
837     {
838 #if DEBUG_TCP
839       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
840                        "tcp",
841                        "Notifying transport service about loss of data connection with `%4s'.\n",
842                        GNUNET_i2s(&session->target));
843 #endif
844       /* Data session that actually went past the 
845          initial handshake; transport service may
846          know about this one, so we need to 
847          notify transport service about disconnect */
848       session->plugin->env->receive (session->plugin->env->cls,
849                                      session->service_context,
850                                      GNUNET_TIME_UNIT_ZERO,
851                                      &session->target, NULL);
852     }
853   if (session->client != NULL)
854     {
855       GNUNET_SERVER_client_drop (session->client);
856       session->client = NULL;
857     }
858   GNUNET_free_non_null (session->connect_addr);
859   GNUNET_free (session);
860 }
861
862
863 /**
864  * Iterator callback to go over all addresses.  If we get
865  * a TCP address, increment the counter
866  *
867  * @param cls closure, points to the counter
868  * @param tname name of the transport
869  * @param expiration expiration time
870  * @param addr the address
871  * @param addrlen length of the address
872  * @return GNUNET_OK to keep the address,
873  *         GNUNET_NO to delete it from the HELLO
874  *         GNUNET_SYSERR to stop iterating (but keep current address)
875  */
876 static int
877 count_tcp_addresses (void *cls,
878                      const char *tname,
879                      struct GNUNET_TIME_Absolute expiration,
880                      const void *addr, size_t addrlen)
881 {
882   unsigned int *counter = cls;
883
884   if (0 != strcmp (tname, "tcp"))
885     return GNUNET_OK;           /* not one of ours */
886   (*counter)++;
887   return GNUNET_OK;             /* failed to connect */
888 }
889
890
891 struct ConnectContext
892 {
893   struct Plugin *plugin;
894
895   struct GNUNET_CONNECTION_Handle *sa;
896
897   struct PendingMessage *welcome;
898
899   unsigned int pos;
900 };
901
902
903 /**
904  * Iterator callback to go over all addresses.  If we get
905  * the "pos" TCP address, try to connect to it.
906  *
907  * @param cls closure
908  * @param tname name of the transport
909  * @param expiration expiration time
910  * @param addrlen length of the address
911  * @param addr the address
912  * @return GNUNET_OK to keep the address,
913  *         GNUNET_NO to delete it from the HELLO
914  *         GNUNET_SYSERR to stop iterating (but keep current address)
915  */
916 static int
917 try_connect_to_address (void *cls,
918                         const char *tname,
919                         struct GNUNET_TIME_Absolute expiration,
920                         const void *addr, size_t addrlen)
921 {
922   struct ConnectContext *cc = cls;
923   int af;
924
925   if (0 != strcmp (tname, "tcp"))
926     return GNUNET_OK;           /* not one of ours */
927   if (sizeof (struct sockaddr_in) == addrlen)
928     af = AF_INET;
929   else if (sizeof (struct sockaddr_in6) == addrlen)
930     af = AF_INET6;
931   else
932     {
933       /* not a valid address */
934       GNUNET_break (0);
935       return GNUNET_NO;
936     }
937   if (0 == cc->pos--)
938     {
939       cc->welcome = create_welcome (addrlen, addr, cc->plugin);
940       cc->sa =
941         GNUNET_CONNECTION_create_from_sockaddr (cc->plugin->env->sched,
942                                                     af, addr, addrlen,
943                                                     GNUNET_SERVER_MAX_MESSAGE_SIZE);
944 #if DEBUG_TCP
945       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
946                        "tcp", 
947                        "Connecting using address %s.\n",
948                        GNUNET_a2s(addr, addrlen));
949 #endif
950       return GNUNET_SYSERR;
951     }
952   return GNUNET_OK;             /* failed to connect */
953 }
954
955
956 /**
957  * Type of an iterator over the hosts.  Note that each
958  * host will be called with each available protocol.
959  *
960  * @param cls closure
961  * @param peer id of the peer, NULL for last call
962  * @param hello hello message for the peer (can be NULL)
963  * @param trust amount of trust we have in the peer
964  */
965 static void
966 session_try_connect (void *cls,
967                      const struct GNUNET_PeerIdentity *peer,
968                      const struct GNUNET_HELLO_Message *hello, uint32_t trust)
969 {
970   struct Session *session = cls;
971   unsigned int count;
972   struct ConnectContext cctx;
973   struct PendingMessage *pm;
974
975   if (peer == NULL)
976     {
977       session->ic = NULL;
978       /* last call, destroy session if we are still not
979          connected */
980       if (session->client != NULL)
981         {
982 #if DEBUG_TCP
983           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
984                            "tcp",
985                            "Now connected to `%4s', now processing messages.\n",
986                            GNUNET_i2s(&session->target));
987 #endif
988           process_pending_messages (session);
989         }
990       else
991         {
992 #if DEBUG_TCP
993           GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
994                            "tcp",
995                            "Failed to connect to `%4s' (no working `%s'), closing session.\n",
996                            GNUNET_i2s(&session->target),
997                            "HELLO");
998 #endif
999           disconnect_session (session);
1000         }
1001       return;
1002     }
1003   if ((hello == NULL) || (session->client != NULL))
1004     {
1005       GNUNET_break (0);         /* should this ever happen!? */
1006       return;
1007     }
1008   count = 0;
1009   GNUNET_HELLO_iterate_addresses (hello,
1010                                   GNUNET_NO, &count_tcp_addresses, &count);
1011   if (count == 0)
1012     {
1013 #if DEBUG_TCP
1014       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1015                        "tcp",
1016                        "Asked to connect to `%4s', but have no addresses to try.\n",
1017                        GNUNET_i2s(&session->target));
1018 #endif
1019       return;
1020     }
1021   cctx.plugin = session->plugin;
1022   cctx.sa = NULL;
1023   cctx.welcome = NULL;
1024   cctx.pos = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1025   GNUNET_HELLO_iterate_addresses (hello,
1026                                   GNUNET_NO, &try_connect_to_address, &cctx);
1027   if (cctx.sa == NULL)
1028     {
1029 #if DEBUG_TCP
1030       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1031                        "tcp",
1032                        "Asked to connect, but all addresses failed.\n");
1033 #endif
1034       GNUNET_free_non_null (cctx.welcome);
1035       return;
1036     }
1037   session->client = GNUNET_SERVER_connect_socket (session->plugin->server,
1038                                                   cctx.sa);
1039 #if DEBUG_TCP
1040   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1041               "Connected to `%4s' for session %p\n",
1042               GNUNET_i2s(&session->target),
1043               session->client);
1044 #endif
1045   if (session->client == NULL)
1046     {
1047       GNUNET_break (0);         /* how could this happen? */
1048       GNUNET_free_non_null (cctx.welcome);
1049       return;
1050     }
1051   pm = cctx.welcome;
1052   /* prepend (!) */
1053   pm->next = session->pending_messages;
1054   session->pending_messages = pm;
1055 #if DEBUG_TCP
1056   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1057                    "tcp",
1058                    "Connected to `%4s', now sending `%s' message.\n",
1059                    GNUNET_i2s(&session->target),
1060                    "WELCOME");
1061 #endif
1062 }
1063
1064
1065 /**
1066  * Function that can be used by the transport service to transmit
1067  * a message using the plugin.
1068  *
1069  * @param cls closure
1070  * @param service_context value passed to the transport-service
1071  *        to identify the neighbour
1072  * @param target who should receive this message
1073  * @param priority how important is the message
1074  * @param msg the message to transmit
1075  * @param timeout when should we time out (give up) if we can not transmit?
1076  * @param cont continuation to call once the message has
1077  *        been transmitted (or if the transport is ready
1078  *        for the next transmission call; or if the
1079  *        peer disconnected...)
1080  * @param cont_cls closure for cont
1081  */
1082 static void 
1083 tcp_plugin_send (void *cls,
1084                  struct ReadyList *service_context,
1085                  const struct GNUNET_PeerIdentity *target,   
1086                  unsigned int priority,
1087                  const struct GNUNET_MessageHeader *msg,
1088                  struct GNUNET_TIME_Relative timeout,
1089                  GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1090 {
1091   struct Plugin *plugin = cls;
1092   struct Session *session;
1093   struct PendingMessage *pm;
1094   struct PendingMessage *pme;
1095
1096   session = find_session_by_target (plugin, target);  
1097   pm = GNUNET_malloc (sizeof (struct PendingMessage) + ntohs (msg->size));
1098   pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
1099   memcpy (pm->msg, msg, ntohs (msg->size));
1100   pm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1101   pm->transmit_cont = cont;
1102   pm->transmit_cont_cls = cont_cls;
1103   if (session == NULL)
1104     {
1105       session = GNUNET_malloc (sizeof (struct Session));
1106 #if DEBUG_TCP
1107       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1108                        "tcp",
1109                        "Asked to transmit, creating fresh session %p.\n",
1110                        session);
1111 #endif
1112       session->next = plugin->sessions;
1113       plugin->sessions = session;
1114       session->plugin = plugin;
1115       session->target = *target;
1116       session->last_quota_update = GNUNET_TIME_absolute_get ();
1117       session->quota_in = plugin->env->default_quota_in;
1118       session->expecting_welcome = GNUNET_YES;
1119       session->pending_messages = pm;
1120       session->service_context = service_context;
1121       session->ic = GNUNET_PEERINFO_iterate (plugin->env->cfg,
1122                                              plugin->env->sched,
1123                                              target,
1124                                              0, timeout, &session_try_connect, session);
1125       return;
1126     }
1127   GNUNET_assert (session != NULL);
1128   GNUNET_assert (session->client != NULL);
1129   session->service_context = service_context;
1130   /* append pm to pending_messages list */
1131   pme = session->pending_messages;
1132   if (pme == NULL)
1133     {
1134       session->pending_messages = pm;
1135     }
1136   else
1137     {
1138       while (NULL != pme->next)
1139         pme = pme->next;
1140       pme->next = pm;
1141     }
1142 #if DEBUG_TCP
1143   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1144                    "tcp", "Asked to transmit, added message to list.\n");
1145 #endif
1146   process_pending_messages (session);
1147 }
1148
1149
1150
1151 /**
1152  * Function that can be called to force a disconnect from the
1153  * specified neighbour.  This should also cancel all previously
1154  * scheduled transmissions.  Obviously the transmission may have been
1155  * partially completed already, which is OK.  The plugin is supposed
1156  * to close the connection (if applicable) and no longer call the
1157  * transmit continuation(s).
1158  *
1159  * Finally, plugin MUST NOT call the services's receive function to
1160  * notify the service that the connection to the specified target was
1161  * closed after a getting this call.
1162  *
1163  * @param cls closure
1164  * @param service_context must correspond to the service context
1165  *        of the corresponding Transmit call; the plugin should
1166  *        not cancel a send call made with a different service
1167  *        context pointer!  Never NULL.
1168  * @param target peer for which the last transmission is
1169  *        to be cancelled
1170  */
1171 static void
1172 tcp_plugin_cancel (void *cls,
1173                    struct ReadyList *service_context,
1174                    const struct GNUNET_PeerIdentity *target)
1175 {
1176   struct Plugin *plugin = cls;
1177   struct Session *session;
1178   struct PendingMessage *pm;
1179   
1180   session = find_session_by_target (plugin, target);
1181   if (session == NULL)
1182     {
1183       GNUNET_break (0);
1184       return;
1185     }
1186 #if DEBUG_TCP
1187   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1188                    "tcp",
1189                    "Asked to cancel session %p with `%4s'\n",
1190                    plugin_context,
1191                    GNUNET_i2s(target));
1192 #endif
1193   pm = session->pending_messages;
1194   while (pm != NULL)
1195     {
1196       pm->transmit_cont = NULL;
1197       pm->transmit_cont_cls = NULL;
1198       pm = pm->next;
1199     }
1200   session->service_context = NULL;
1201   if (session->client != NULL)
1202     {
1203       GNUNET_SERVER_client_drop (session->client);
1204       session->client = NULL;
1205     }
1206   /* rest of the clean-up of the session will be done as part of
1207      disconnect_notify which should be triggered any time now 
1208      (or which may be triggering this call in the first place) */
1209 }
1210
1211
1212 struct PrettyPrinterContext
1213 {
1214   GNUNET_TRANSPORT_AddressStringCallback asc;
1215   void *asc_cls;
1216   uint16_t port;
1217 };
1218
1219
1220 /**
1221  * Append our port and forward the result.
1222  */
1223 static void
1224 append_port (void *cls, const char *hostname)
1225 {
1226   struct PrettyPrinterContext *ppc = cls;
1227   char *ret;
1228
1229   if (hostname == NULL)
1230     {
1231       ppc->asc (ppc->asc_cls, NULL);
1232       GNUNET_free (ppc);
1233       return;
1234     }
1235   GNUNET_asprintf (&ret, "%s:%d", hostname, ppc->port);
1236   ppc->asc (ppc->asc_cls, ret);
1237   GNUNET_free (ret);
1238 }
1239
1240
1241 /**
1242  * Convert the transports address to a nice, human-readable
1243  * format.
1244  *
1245  * @param cls closure
1246  * @param type name of the transport that generated the address
1247  * @param addr one of the addresses of the host, NULL for the last address
1248  *        the specific address format depends on the transport
1249  * @param addrlen length of the address
1250  * @param numeric should (IP) addresses be displayed in numeric form?
1251  * @param timeout after how long should we give up?
1252  * @param asc function to call on each string
1253  * @param asc_cls closure for asc
1254  */
1255 static void
1256 tcp_plugin_address_pretty_printer (void *cls,
1257                                    const char *type,
1258                                    const void *addr,
1259                                    size_t addrlen,
1260                                    int numeric,
1261                                    struct GNUNET_TIME_Relative timeout,
1262                                    GNUNET_TRANSPORT_AddressStringCallback asc,
1263                                    void *asc_cls)
1264 {
1265   struct Plugin *plugin = cls;
1266   const struct sockaddr_in *v4;
1267   const struct sockaddr_in6 *v6;
1268   struct PrettyPrinterContext *ppc;
1269
1270   if ((addrlen != sizeof (struct sockaddr_in)) &&
1271       (addrlen != sizeof (struct sockaddr_in6)))
1272     {
1273       /* invalid address */
1274       GNUNET_break_op (0);
1275       asc (asc_cls, NULL);
1276       return;
1277     }
1278   ppc = GNUNET_malloc (sizeof (struct PrettyPrinterContext));
1279   ppc->asc = asc;
1280   ppc->asc_cls = asc_cls;
1281   if (addrlen == sizeof (struct sockaddr_in))
1282     {
1283       v4 = (const struct sockaddr_in *) addr;
1284       ppc->port = ntohs (v4->sin_port);
1285     }
1286   else
1287     {
1288       v6 = (const struct sockaddr_in6 *) addr;
1289       ppc->port = ntohs (v6->sin6_port);
1290
1291     }
1292   GNUNET_RESOLVER_hostname_get (plugin->env->sched,
1293                                 plugin->env->cfg,
1294                                 addr,
1295                                 addrlen,
1296                                 !numeric, timeout, &append_port, ppc);
1297 }
1298
1299
1300 /**
1301  * Update the last-received and bandwidth quota values
1302  * for this session.
1303  *
1304  * @param session session to update
1305  * @param force set to GNUNET_YES if we should update even
1306  *        though the minimum refresh time has not yet expired
1307  */
1308 static void
1309 update_quota (struct Session *session, int force)
1310 {
1311   struct GNUNET_TIME_Absolute now;
1312   unsigned long long delta;
1313   unsigned long long total_allowed;
1314   unsigned long long total_remaining;
1315
1316   now = GNUNET_TIME_absolute_get ();
1317   delta = now.value - session->last_quota_update.value;
1318   if ((delta < MIN_QUOTA_REFRESH_TIME) && (!force))
1319     return;                     /* too early, not enough data */
1320
1321   total_allowed = session->quota_in * delta;
1322   if (total_allowed > session->last_received)
1323     {
1324       /* got less than acceptable */
1325       total_remaining = total_allowed - session->last_received;
1326       session->last_received = 0;
1327       delta = total_remaining / session->quota_in;      /* bonus seconds */
1328       if (delta > MAX_BANDWIDTH_CARRY)
1329         delta = MAX_BANDWIDTH_CARRY;    /* limit amount of carry-over */
1330     }
1331   else
1332     {
1333       /* got more than acceptable */
1334       session->last_received -= total_allowed;
1335       delta = 0;
1336     }
1337   session->last_quota_update.value = now.value - delta;
1338 }
1339
1340
1341 /**
1342  * Set a quota for receiving data from the given peer; this is a
1343  * per-transport limit.  The transport should limit its read/select
1344  * calls to stay below the quota (in terms of incoming data).
1345  *
1346  * @param cls closure
1347  * @param target the peer for whom the quota is given
1348  * @param quota_in quota for receiving/sending data in bytes per ms
1349  */
1350 static void
1351 tcp_plugin_set_receive_quota (void *cls,
1352                               const struct GNUNET_PeerIdentity *target,
1353                               uint32_t quota_in)
1354 {
1355   struct Plugin *plugin = cls;
1356   struct Session *session;
1357
1358   session = find_session_by_target (plugin, target);
1359   if (session == NULL)
1360     return; /* peer must have disconnected, ignore */
1361   if (session->quota_in != quota_in)
1362     {
1363       update_quota (session, GNUNET_YES);
1364       if (session->quota_in > quota_in)
1365         session->last_quota_update = GNUNET_TIME_absolute_get ();
1366       session->quota_in = quota_in;
1367     }
1368 }
1369
1370
1371 /**
1372  * Check if the given port is plausible (must be either
1373  * our listen port or our advertised port).  If it is
1374  * neither, we return one of these two ports at random.
1375  *
1376  * @return either in_port or a more plausible port
1377  */
1378 static uint16_t
1379 check_port (struct Plugin *plugin, uint16_t in_port)
1380 {
1381   if ((in_port == plugin->adv_port) || (in_port == plugin->open_port))
1382     return in_port;
1383   return (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1384                                     2) == 0)
1385     ? plugin->open_port : plugin->adv_port;
1386 }
1387
1388
1389 /**
1390  * Another peer has suggested an address for this
1391  * peer and transport plugin.  Check that this could be a valid
1392  * address.  If so, consider adding it to the list
1393  * of addresses.
1394  *
1395  * @param cls closure
1396  * @param addr pointer to the address
1397  * @param addrlen length of addr
1398  * @return GNUNET_OK if this is a plausible address for this peer
1399  *         and transport
1400  */
1401 static int
1402 tcp_plugin_address_suggested (void *cls, const void *addr, size_t addrlen)
1403 {
1404   struct Plugin *plugin = cls;
1405   char buf[sizeof (struct sockaddr_in6)];
1406   struct sockaddr_in *v4;
1407   struct sockaddr_in6 *v6;
1408
1409   if ((addrlen != sizeof (struct sockaddr_in)) &&
1410       (addrlen != sizeof (struct sockaddr_in6)))
1411     {
1412       GNUNET_break_op (0);
1413       return GNUNET_SYSERR;
1414     }
1415   memcpy (buf, addr, sizeof (struct sockaddr_in6));
1416   if (addrlen == sizeof (struct sockaddr_in))
1417     {
1418       v4 = (struct sockaddr_in *) buf;
1419       v4->sin_port = htons (check_port (plugin, ntohs (v4->sin_port)));
1420     }
1421   else
1422     {
1423       v6 = (struct sockaddr_in6 *) buf;
1424       v6->sin6_port = htons (check_port (plugin, ntohs (v6->sin6_port)));
1425     }
1426 #if DEBUG_TCP
1427   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1428                    "tcp",
1429                    "Informing transport service about my address `%s'.\n",
1430                    GNUNET_a2s(addr, addrlen));
1431 #endif
1432   plugin->env->notify_address (plugin->env->cls,
1433                                "tcp",
1434                                buf, addrlen, LEARNED_ADDRESS_EXPIRATION);
1435   return GNUNET_OK;
1436 }
1437
1438
1439 /**
1440  * Send a validation challenge response.
1441  */
1442 static size_t
1443 send_vcr (void *cls,
1444           size_t size,
1445           void *buf)
1446 {
1447   struct ValidationChallengeResponse *vcr = cls;
1448   uint16_t msize;
1449
1450   if (NULL == buf)
1451     {
1452       GNUNET_free (vcr);
1453       return 0;
1454     }
1455   msize = ntohs(vcr->header.size);
1456   GNUNET_assert (size >= msize);
1457   memcpy (buf, vcr, msize);
1458   GNUNET_free (vcr);
1459   return msize;
1460 }
1461
1462
1463 /**
1464  * We've received a PING from this peer via TCP.
1465  * Send back our PONG.
1466  *
1467  * @param cls closure
1468  * @param client identification of the client
1469  * @param message the actual message
1470  */
1471 static void
1472 handle_tcp_ping (void *cls,
1473                  struct GNUNET_SERVER_Client *client,
1474                  const struct GNUNET_MessageHeader *message)
1475 {
1476   struct Plugin *plugin = cls;
1477   const struct ValidationChallengeMessage *vcm;
1478   struct ValidationChallengeResponse *vcr;
1479   uint16_t msize;
1480   size_t addrlen;
1481   void *addr;
1482
1483 #if DEBUG_TRANSPORT
1484   if (GNUNET_OK ==
1485       GNUNET_SERVER_client_get_address (client,
1486                                         (void **) &addr,
1487                                         &addrlen))
1488     {
1489       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1490                   "Processing `%s' from `%s'\n",
1491                   "PING",
1492                   GNUNET_a2s (addr, addrlen));
1493       GNUNET_free (addr);
1494     }
1495 #endif
1496   msize = ntohs (message->size);
1497   if (msize < sizeof (struct ValidationChallengeMessage))
1498     {
1499       GNUNET_break_op (0);
1500       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1501       return;
1502     }
1503   vcm = (const struct ValidationChallengeMessage *) message;
1504   if (0 != memcmp (&vcm->target,
1505                    plugin->env->my_identity, sizeof (struct GNUNET_PeerIdentity)))
1506     {
1507       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1508                   _("Received `%s' message not destined for me!\n"), "PING");
1509       /* TODO: call statistics */
1510       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1511       return;
1512     }
1513   msize -= sizeof (struct ValidationChallengeMessage);
1514   if (GNUNET_OK !=
1515       tcp_plugin_address_suggested (plugin, &vcm[1], msize))
1516     {
1517       GNUNET_break_op (0);
1518       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1519       return;
1520     }
1521   if (GNUNET_OK !=
1522       GNUNET_SERVER_client_get_address (client,
1523                                         &addr,
1524                                         &addrlen))
1525     {
1526       GNUNET_break (0);
1527       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1528       return;
1529     }
1530   vcr = GNUNET_malloc (sizeof (struct ValidationChallengeResponse) + addrlen);
1531   vcr->header.size = htons (sizeof (struct ValidationChallengeResponse) + addrlen);
1532   vcr->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PONG);
1533   vcr->purpose.size =
1534     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1535            sizeof (uint32_t) +
1536            sizeof ( struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
1537            addrlen);
1538   vcr->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING);
1539   vcr->challenge = vcm->challenge;
1540   vcr->signer = *plugin->env->my_public_key;
1541   memcpy (&vcr[1],
1542           addr,
1543           addrlen);
1544   GNUNET_assert (GNUNET_OK ==
1545                  GNUNET_CRYPTO_rsa_sign (plugin->env->my_private_key,
1546                                          &vcr->purpose,
1547                                          &vcr->signature));
1548 #if EXTRA_CHECKS
1549   GNUNET_assert (GNUNET_OK ==
1550                  GNUNET_CRYPTO_rsa_verify
1551                  (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING,
1552                   &vcr->purpose,
1553                   &vcr->signature,
1554                   plugin->env->my_public_key));
1555 #endif
1556   GNUNET_free (addr);
1557   if (NULL ==
1558       GNUNET_SERVER_notify_transmit_ready (client,
1559                                            sizeof (struct ValidationChallengeResponse) + addrlen,
1560                                            GNUNET_TIME_UNIT_SECONDS,
1561                                            &send_vcr,
1562                                            vcr))
1563     {
1564       GNUNET_break (0);
1565       GNUNET_free (vcr);
1566     }
1567   /* after a PING, we always close the connection */
1568   GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1569 }
1570
1571
1572 /**
1573  * Handle PONG-message.
1574  *
1575  * @param cls handle for this plugin
1576  * @param client from where did we receive the PONG
1577  * @param message the actual message
1578  */
1579 static void
1580 handle_tcp_pong (void *cls,
1581                  struct GNUNET_SERVER_Client *client,
1582                  const struct GNUNET_MessageHeader *message)
1583 {
1584   struct Plugin *plugin = cls;
1585   const struct ValidationChallengeResponse *vcr;
1586   struct GNUNET_PeerIdentity peer;
1587   char *sender_addr;
1588   size_t addrlen;
1589   const struct sockaddr *addr;
1590   struct sockaddr_in v4;
1591   struct sockaddr_in6 v6;
1592
1593 #if DEBUG_TRANSPORT
1594   struct sockaddr *claddr;
1595
1596   if (GNUNET_OK ==
1597       GNUNET_SERVER_client_get_address (client,
1598                                         (void**) &claddr,
1599                                         &addrlen))
1600     {
1601       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1602                   "Processing `%s' from `%s'\n",
1603                   "PONG",
1604                   GNUNET_a2s (claddr, addrlen));
1605       GNUNET_free (claddr);
1606     }
1607 #endif
1608   if (ntohs(message->size) < sizeof(struct ValidationChallengeResponse))
1609     {
1610       GNUNET_break_op (0);
1611       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1612       return;
1613     }
1614   addrlen = ntohs(message->size) - sizeof(struct ValidationChallengeResponse);
1615   vcr = (const struct ValidationChallengeResponse *) message;
1616   if ( (ntohl(vcr->purpose.size) !=
1617         sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
1618         sizeof (uint32_t) +
1619         sizeof ( struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
1620         addrlen))
1621     {
1622       GNUNET_break_op (0);
1623       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1624       return;
1625     }
1626   if (GNUNET_OK !=
1627       GNUNET_CRYPTO_rsa_verify
1628       (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_TCP_PING, 
1629        &vcr->purpose,
1630        &vcr->signature, 
1631        &vcr->signer))
1632     {
1633       GNUNET_break_op (0);
1634       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1635       return;
1636     }
1637   GNUNET_CRYPTO_hash (&vcr->signer,
1638                       sizeof(  struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1639                       &peer.hashPubKey);
1640   addr = (const struct sockaddr*) &vcr[1];
1641   if (addrlen == sizeof (struct sockaddr_in))
1642     {
1643       memcpy (&v4, addr, sizeof (struct sockaddr_in));
1644       v4.sin_port = htons(check_port (plugin, ntohs (v4.sin_port)));
1645       sender_addr = GNUNET_strdup (GNUNET_a2s((const struct sockaddr*) &v4,
1646                                               addrlen));
1647     }
1648   else if (addrlen == sizeof (struct sockaddr_in6))
1649     {
1650       memcpy (&v6, addr, sizeof (struct sockaddr_in6));
1651       v6.sin6_port = htons(check_port (plugin, ntohs (v6.sin6_port)));
1652       sender_addr = GNUNET_strdup (GNUNET_a2s((const struct sockaddr*) &v6,
1653                                               addrlen));
1654     }
1655   else
1656     {
1657       GNUNET_break_op (0); 
1658       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1659       return;
1660     }
1661   plugin->env->notify_validation (plugin->env->cls,
1662                                   "tcp",
1663                                   &peer,
1664                                   ntohl(vcr->challenge),
1665                                   sender_addr);
1666   GNUNET_free (sender_addr);
1667   /* after a PONG, we always close the connection */
1668   GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);  
1669 }
1670
1671
1672 /**
1673  * We've received a welcome from this peer via TCP.
1674  * Possibly create a fresh client record and send back
1675  * our welcome.
1676  *
1677  * @param cls closure
1678  * @param client identification of the client
1679  * @param message the actual message
1680  */
1681 static void
1682 handle_tcp_welcome (void *cls,
1683                     struct GNUNET_SERVER_Client *client,
1684                     const struct GNUNET_MessageHeader *message)
1685 {
1686   struct Plugin *plugin = cls;
1687   struct Session *session_c;
1688   const struct WelcomeMessage *wm;
1689   uint16_t msize;
1690   uint32_t addrlen;
1691   size_t alen;
1692   void *vaddr;
1693   const struct sockaddr *addr;
1694
1695   msize = ntohs (message->size);
1696   if (msize < sizeof (struct WelcomeMessage))
1697     {
1698       GNUNET_break_op (0);
1699       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1700       return;
1701     }
1702   wm = (const struct WelcomeMessage *) message;
1703 #if DEBUG_TCP
1704   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1705                    "tcp",
1706                    "Received `%s' message from `%4s/%p'.\n", "WELCOME",
1707                    GNUNET_i2s(&wm->clientIdentity),
1708                    client);
1709 #endif
1710   session_c = find_session_by_client (plugin, client);
1711   if (session_c == NULL)
1712     {
1713       vaddr = NULL;
1714       GNUNET_SERVER_client_get_address (client, &vaddr, &alen);
1715       GNUNET_SERVER_client_keep (client);
1716       session_c = create_session (plugin,
1717                                   &wm->clientIdentity, client, vaddr, alen);
1718 #if DEBUG_TCP
1719       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1720                        "tcp",
1721                        "Creating new session %p for incoming `%s' message.\n",
1722                        session_c, "WELCOME");
1723 #endif
1724       GNUNET_free_non_null (vaddr);
1725       process_pending_messages (session_c);
1726     }
1727   if (session_c->expecting_welcome != GNUNET_YES)
1728     {
1729       GNUNET_break_op (0);
1730       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1731       return;
1732     }
1733   session_c->expecting_welcome = GNUNET_NO;
1734   if (0 < (addrlen = msize - sizeof (struct WelcomeMessage)))
1735     {
1736       addr = (const struct sockaddr *) &wm[1];
1737       tcp_plugin_address_suggested (plugin, addr, addrlen);
1738     }
1739   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1740 }
1741
1742
1743 /**
1744  * Calculate how long we should delay reading from the TCP socket to
1745  * ensure that we stay within our bandwidth limits (push back).
1746  *
1747  * @param session for which client should this be calculated
1748  */
1749 static struct GNUNET_TIME_Relative
1750 calculate_throttle_delay (struct Session *session)
1751 {
1752   struct GNUNET_TIME_Relative ret;
1753   struct GNUNET_TIME_Absolute now;
1754   uint64_t del;
1755   uint64_t avail;
1756   uint64_t excess;
1757
1758   now = GNUNET_TIME_absolute_get ();
1759   del = now.value - session->last_quota_update.value;
1760   if (del > MAX_BANDWIDTH_CARRY)
1761     {
1762       update_quota (session, GNUNET_YES);
1763       del = now.value - session->last_quota_update.value;
1764       GNUNET_assert (del <= MAX_BANDWIDTH_CARRY);
1765     }
1766   if (session->quota_in == 0)
1767     session->quota_in = 1;      /* avoid divison by zero */
1768   avail = del * session->quota_in;
1769   if (avail > session->last_received)
1770     return GNUNET_TIME_UNIT_ZERO;       /* can receive right now */
1771   excess = session->last_received - avail;
1772   ret.value = excess / session->quota_in;
1773   return ret;
1774 }
1775
1776
1777 /**
1778  * Task to signal the server that we can continue
1779  * receiving from the TCP client now.
1780  */
1781 static void
1782 delayed_done (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1783 {
1784   struct Session *session = cls;
1785   GNUNET_SERVER_receive_done (session->client, GNUNET_OK);
1786 }
1787
1788
1789 /**
1790  * We've received data for this peer via TCP.  Unbox,
1791  * compute latency and forward.
1792  *
1793  * @param cls closure
1794  * @param client identification of the client
1795  * @param message the actual message
1796  */
1797 static void
1798 handle_tcp_data (void *cls,
1799                  struct GNUNET_SERVER_Client *client,
1800                  const struct GNUNET_MessageHeader *message)
1801 {
1802   struct Plugin *plugin = cls;
1803   struct Session *session;
1804   const struct DataMessage *dm;
1805   uint16_t msize;
1806   const struct GNUNET_MessageHeader *msg;
1807   struct GNUNET_TIME_Relative latency;
1808   struct GNUNET_TIME_Absolute ttime;
1809   struct GNUNET_TIME_Absolute now;
1810   struct GNUNET_TIME_Relative delay;
1811   uint64_t ack_in;
1812
1813   msize = ntohs (message->size);
1814   if ((msize <
1815        sizeof (struct DataMessage) + sizeof (struct GNUNET_MessageHeader)))
1816     {
1817       GNUNET_break_op (0);
1818       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1819       return;
1820     }
1821   session = find_session_by_client (plugin, client);
1822   if ((NULL == session) || (GNUNET_NO != session->expecting_welcome))
1823     {
1824       GNUNET_break_op (0);
1825       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1826       return;
1827     }
1828 #if DEBUG_TCP
1829   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1830                    "tcp", "Receiving %u bytes from `%4s'.\n",
1831                    msize,
1832                    GNUNET_i2s(&session->target));
1833 #endif
1834   dm = (const struct DataMessage *) message;
1835   session->max_in_msg_counter = GNUNET_MAX (session->max_in_msg_counter,
1836                                             GNUNET_ntohll (dm->ack_out));
1837   msg = (const struct GNUNET_MessageHeader *) &dm[1];
1838   if (msize != sizeof (struct DataMessage) + ntohs (msg->size))
1839     {
1840       GNUNET_break_op (0);
1841       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1842       return;
1843     }
1844   /* estimate latency */
1845   ack_in = GNUNET_ntohll (dm->ack_in);
1846   if ((ack_in <= session->out_msg_counter) &&
1847       (session->out_msg_counter - ack_in < ACK_LOG_SIZE))
1848     {
1849       delay = GNUNET_TIME_relative_ntoh (dm->delay);
1850       ttime = session->gen_time[ack_in % ACK_LOG_SIZE];
1851       now = GNUNET_TIME_absolute_get ();
1852       if (delay.value > now.value - ttime.value)
1853         delay.value = 0;        /* not plausible */
1854       /* update (round-trip) latency using ageing; we
1855          use 7:1 so that we can reasonably quickly react
1856          to changes, but not so fast that latency is largely
1857          jitter... */
1858       session->latency_estimate
1859         = ((7 * session->latency_estimate) +
1860            (now.value - ttime.value - delay.value)) / 8;
1861     }
1862   latency.value = (uint64_t) session->latency_estimate;
1863   /* deliver on */
1864 #if DEBUG_TCP
1865   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1866                    "tcp",
1867                    "Forwarding data of type %u to transport service.\n",
1868                    ntohs (msg->type));
1869 #endif
1870   session->service_context
1871     = plugin->env->receive (plugin->env->cls,
1872                             session->service_context,
1873                             latency, &session->target, msg);
1874   /* update bandwidth used */
1875   session->last_received += msize;
1876   update_quota (session, GNUNET_NO);
1877
1878   delay = calculate_throttle_delay (session);
1879   if (delay.value == 0)
1880     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1881   else
1882     GNUNET_SCHEDULER_add_delayed (session->plugin->env->sched,
1883                                   delay, &delayed_done, session);
1884 }
1885
1886
1887 /**
1888  * Handlers for the various TCP messages.
1889  */
1890 static struct GNUNET_SERVER_MessageHandler my_handlers[] = {
1891   {&handle_tcp_ping, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PING, 0},
1892   {&handle_tcp_pong, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_PONG, 0},
1893   {&handle_tcp_welcome, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_WELCOME, 0},
1894   {&handle_tcp_data, NULL, GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_DATA, 0},
1895   {NULL, NULL, 0, 0}
1896 };
1897
1898
1899 static void
1900 create_tcp_handlers (struct Plugin *plugin)
1901 {
1902   unsigned int i;
1903   plugin->handlers = GNUNET_malloc (sizeof (my_handlers));
1904   memcpy (plugin->handlers, my_handlers, sizeof (my_handlers));
1905   for (i = 0;
1906        i <
1907        sizeof (my_handlers) / sizeof (struct GNUNET_SERVER_MessageHandler);
1908        i++)
1909     plugin->handlers[i].callback_cls = plugin;
1910   GNUNET_SERVER_add_handlers (plugin->server, plugin->handlers);
1911 }
1912
1913
1914 /**
1915  * Functions with this signature are called whenever a peer
1916  * is disconnected on the network level.
1917  *
1918  * @param cls closure
1919  * @param client identification of the client
1920  */
1921 static void
1922 disconnect_notify (void *cls, struct GNUNET_SERVER_Client *client)
1923 {
1924   struct Plugin *plugin = cls;
1925   struct Session *session;
1926
1927   session = find_session_by_client (plugin, client);
1928   if (session == NULL)
1929     return;                     /* unknown, nothing to do */
1930 #if DEBUG_TCP
1931   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1932                    "tcp",
1933                    "Destroying session of `%4s' with %s (%p) due to network-level disconnect.\n",
1934                    GNUNET_i2s(&session->target),
1935                    (session->connect_addr != NULL) ? 
1936                    GNUNET_a2s(session->connect_addr,
1937                               session->connect_alen) : "*",
1938                    client);
1939 #endif
1940   disconnect_session (session);
1941 }
1942
1943
1944 /**
1945  * Add the IP of our network interface to the list of
1946  * our external IP addresses.
1947  */
1948 static int
1949 process_interfaces (void *cls,
1950                     const char *name,
1951                     int isDefault,
1952                     const struct sockaddr *addr, socklen_t addrlen)
1953 {
1954   struct Plugin *plugin = cls;
1955   int af;
1956   struct sockaddr_in *v4;
1957   struct sockaddr_in6 *v6;
1958
1959   af = addr->sa_family;
1960   if (af == AF_INET)
1961     {
1962       v4 = (struct sockaddr_in *) addr;
1963       v4->sin_port = htons (plugin->adv_port);
1964     }
1965   else
1966     {
1967       GNUNET_assert (af == AF_INET6);
1968       v6 = (struct sockaddr_in6 *) addr;
1969       v6->sin6_port = htons (plugin->adv_port);
1970     }
1971   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO |
1972                    GNUNET_ERROR_TYPE_BULK,
1973                    "tcp", _("Found address `%s' (%s)\n"), 
1974                    GNUNET_a2s(addr, addrlen), name);
1975   plugin->env->notify_address (plugin->env->cls,
1976                                "tcp",
1977                                addr, addrlen, GNUNET_TIME_UNIT_FOREVER_REL);
1978   return GNUNET_OK;
1979 }
1980
1981
1982 /**
1983  * Function called by the resolver for each address obtained from DNS
1984  * for our own hostname.  Add the addresses to the list of our
1985  * external IP addresses.
1986  *
1987  * @param cls closure
1988  * @param addr one of the addresses of the host, NULL for the last address
1989  * @param addrlen length of the address
1990  */
1991 static void
1992 process_hostname_ips (void *cls,
1993                       const struct sockaddr *addr, socklen_t addrlen)
1994 {
1995   struct Plugin *plugin = cls;
1996
1997   if (addr == NULL)
1998     {
1999       plugin->hostname_dns = NULL;
2000       return;
2001     }
2002   process_interfaces (plugin,
2003                       "<hostname>",
2004                       GNUNET_YES,
2005                       addr,
2006                       addrlen);
2007 }
2008
2009
2010 /**
2011  * Entry point for the plugin.
2012  */
2013 void *
2014 libgnunet_plugin_transport_tcp_init (void *cls)
2015 {
2016   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2017   struct GNUNET_TRANSPORT_PluginFunctions *api;
2018   struct Plugin *plugin;
2019   struct GNUNET_SERVICE_Context *service;
2020   unsigned long long aport;
2021   unsigned long long bport;
2022
2023   service = GNUNET_SERVICE_start ("transport-tcp", env->sched, env->cfg);
2024   if (service == NULL)
2025     {
2026       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING,
2027                        "tcp",
2028                        _
2029                        ("Failed to start service for `%s' transport plugin.\n"),
2030                        "tcp");
2031       return NULL;
2032     }
2033   aport = 0;
2034   if ((GNUNET_OK !=
2035        GNUNET_CONFIGURATION_get_value_number (env->cfg,
2036                                               "transport-tcp",
2037                                               "PORT",
2038                                               &bport)) ||
2039       (bport > 65535) ||
2040       ((GNUNET_OK ==
2041         GNUNET_CONFIGURATION_get_value_number (env->cfg,
2042                                                "transport-tcp",
2043                                                "ADVERTISED-PORT",
2044                                                &aport)) && (aport > 65535)))
2045     {
2046       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
2047                        "tcp",
2048                        _
2049                        ("Require valid port number for service `%s' in configuration!\n"),
2050                        "transport-tcp");
2051       GNUNET_SERVICE_stop (service);
2052       return NULL;
2053     }
2054   if (aport == 0)
2055     aport = bport;
2056   plugin = GNUNET_malloc (sizeof (struct Plugin));
2057   plugin->open_port = bport;
2058   plugin->adv_port = aport;
2059   plugin->env = env;
2060   plugin->lsock = NULL;
2061   plugin->statistics = NULL;
2062   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
2063   api->cls = plugin;
2064   api->validate = &tcp_plugin_validate;
2065   api->send = &tcp_plugin_send;
2066   api->cancel = &tcp_plugin_cancel;
2067   api->address_pretty_printer = &tcp_plugin_address_pretty_printer;
2068   api->set_receive_quota = &tcp_plugin_set_receive_quota;
2069   api->address_suggested = &tcp_plugin_address_suggested;
2070   api->cost_estimate = 42;      /* TODO: ATS */
2071   plugin->service = service;
2072   plugin->server = GNUNET_SERVICE_get_server (service);
2073   create_tcp_handlers (plugin);
2074   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2075                    "tcp", _("TCP transport listening on port %llu\n"), bport);
2076   if (aport != bport)
2077     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
2078                      "tcp",
2079                      _
2080                      ("TCP transport advertises itself as being on port %llu\n"),
2081                      aport);
2082   GNUNET_SERVER_disconnect_notify (plugin->server, &disconnect_notify,
2083                                    plugin);
2084   GNUNET_OS_network_interfaces_list (&process_interfaces, plugin);
2085   plugin->hostname_dns = GNUNET_RESOLVER_hostname_resolve (env->sched,
2086                                                            env->cfg,
2087                                                            AF_UNSPEC,
2088                                                            HOSTNAME_RESOLVE_TIMEOUT,
2089                                                            &process_hostname_ips, plugin);
2090   return api;
2091 }
2092
2093
2094 /**
2095  * Exit point from the plugin.
2096  */
2097 void *
2098 libgnunet_plugin_transport_tcp_done (void *cls)
2099 {
2100   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
2101   struct Plugin *plugin = api->cls;
2102   struct Session *session;
2103
2104   while (NULL != (session = plugin->sessions))
2105     disconnect_session (session);    
2106   if (NULL != plugin->hostname_dns)
2107     {
2108       GNUNET_RESOLVER_request_cancel (plugin->hostname_dns);
2109       plugin->hostname_dns = NULL;
2110     }
2111   GNUNET_SERVICE_stop (plugin->service);
2112   GNUNET_free (plugin->handlers);
2113   GNUNET_free (plugin);
2114   GNUNET_free (api);
2115   return NULL;
2116 }
2117
2118 /* end of plugin_transport_tcp.c */