first draft of UDP communicator
[oweals/gnunet.git] / src / transport / gnunet-communicator-tcp.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2010-2014, 2018, 2019 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
19 */
20
21 /**
22  * @file transport/gnunet-communicator-tcp.c
23  * @brief Transport plugin using TCP.
24  * @author Christian Grothoff
25  *
26  * TODO:
27  * - support DNS names in BINDTO option (#5528)
28  * - support NAT connection reversal method (#5529)
29  * - support other TCP-specific NAT traversal methods (#5531)
30  * - add replay protection support to the protocol by
31  *   adding a nonce in the KX and requiring (!) a
32  *   nounce ACK to be send within the first X bytes of
33  *   data (#5530)
34  */
35 #include "platform.h"
36 #include "gnunet_util_lib.h"
37 #include "gnunet_protocols.h"
38 #include "gnunet_signatures.h"
39 #include "gnunet_constants.h"
40 #include "gnunet_nt_lib.h"
41 #include "gnunet_nat_service.h"
42 #include "gnunet_statistics_service.h"
43 #include "gnunet_transport_communication_service.h"
44
45 /**
46  * How many messages do we keep at most in the queue to the
47  * transport service before we start to drop (default,
48  * can be changed via the configuration file).
49  * Should be _below_ the level of the communicator API, as
50  * otherwise we may read messages just to have them dropped
51  * by the communicator API.
52  */
53 #define DEFAULT_MAX_QUEUE_LENGTH 8
54
55 /**
56  * Size of our IO buffers for ciphertext data. Must be at
57  * least UINT_MAX + sizeof (struct TCPBox).
58  */
59 #define BUF_SIZE (2 * 64 * 1024 + sizeof (struct TCPBox))
60
61 /**
62  * How often do we rekey based on time (at least)
63  */ 
64 #define REKEY_TIME_INTERVAL GNUNET_TIME_UNIT_DAYS
65
66 /**
67  * How long do we wait until we must have received the initial KX?
68  */ 
69 #define PROTO_QUEUE_TIMEOUT GNUNET_TIME_UNIT_MINUTES
70
71 /**
72  * How often do we rekey based on number of bytes transmitted?
73  * (additionally randomized).
74  */ 
75 #define REKEY_MAX_BYTES (1024LLU * 1024 * 1024 * 4LLU)
76
77 /**
78  * Size of the initial key exchange message sent first in both
79  * directions.
80  */
81 #define INITIAL_KX_SIZE (sizeof (struct GNUNET_CRYPTO_EcdhePublicKey)+sizeof (struct TCPConfirmation))
82
83
84 /**
85  * Address prefix used by the communicator.
86  */
87 #define COMMUNICATOR_ADDRESS_PREFIX "tcp"
88
89 /**
90  * Configuration section used by the communicator.
91  */
92 #define COMMUNICATOR_CONFIG_SECTION "communicator-tcp"
93
94 GNUNET_NETWORK_STRUCT_BEGIN
95
96
97 /**
98  * Signature we use to verify that the ephemeral key was really chosen by
99  * the specified sender.
100  */
101 struct TcpHandshakeSignature
102 {
103   /**
104    * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE
105    */
106   struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
107
108   /**
109    * Identity of the inititor of the TCP connection (TCP client).
110    */ 
111   struct GNUNET_PeerIdentity sender;
112
113   /**
114    * Presumed identity of the target of the TCP connection (TCP server)
115    */ 
116   struct GNUNET_PeerIdentity receiver;
117
118   /**
119    * Ephemeral key used by the @e sender.
120    */ 
121   struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
122
123   /**
124    * Monotonic time of @e sender, to possibly help detect replay attacks
125    * (if receiver persists times by sender).
126    */ 
127   struct GNUNET_TIME_AbsoluteNBO monotonic_time;
128 };
129
130
131 /**
132  * Encrypted continuation of TCP initial handshake.
133  */
134 struct TCPConfirmation
135 {
136   /**
137    * Sender's identity
138    */
139   struct GNUNET_PeerIdentity sender;
140
141   /**
142    * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE
143    */
144   struct GNUNET_CRYPTO_EddsaSignature sender_sig;
145
146   /**
147    * Monotonic time of @e sender, to possibly help detect replay attacks
148    * (if receiver persists times by sender).
149    */ 
150   struct GNUNET_TIME_AbsoluteNBO monotonic_time;
151
152 };
153
154
155 /**
156  * TCP message box.  Always sent encrypted!
157  */ 
158 struct TCPBox
159 {
160   
161   /**
162    * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX.  Warning: the
163    * header size EXCLUDES the size of the `struct TCPBox`. We usually
164    * never do this, but here the payload may truly be 64k *after* the
165    * TCPBox (as we have no MTU)!!
166    */ 
167   struct GNUNET_MessageHeader header;
168
169   /**
170    * HMAC for the following encrypted message.  Yes, we MUST use
171    * mac-then-encrypt here, as we want to hide the message sizes on
172    * the wire (zero plaintext design!).  Using CTR mode padding oracle
173    * attacks do not apply.  Besides, due to the use of ephemeral keys
174    * (hopefully with effective replay protection from monotonic time!)
175    * the attacker is limited in using the oracle.
176    */ 
177   struct GNUNET_ShortHashCode hmac;
178
179   /* followed by as may bytes of payload as indicated in @e header,
180      excluding the TCPBox itself! */
181   
182 };
183
184
185 /**
186  * TCP rekey message box.  Always sent encrypted!  Data after
187  * this message will use the new key.
188  */ 
189 struct TCPRekey
190 {
191
192   /**
193    * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY.
194    */ 
195   struct GNUNET_MessageHeader header;
196
197   /**
198    * HMAC for the following encrypted message.  Yes, we MUST use
199    * mac-then-encrypt here, as we want to hide the message sizes on
200    * the wire (zero plaintext design!).  Using CTR mode padding oracle
201    * attacks do not apply.  Besides, due to the use of ephemeral keys
202    * (hopefully with effective replay protection from monotonic time!)
203    * the attacker is limited in using the oracle.
204    */ 
205   struct GNUNET_ShortHashCode hmac;
206
207   /**
208    * New ephemeral key.
209    */ 
210   struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
211   
212   /**
213    * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY
214    */
215   struct GNUNET_CRYPTO_EddsaSignature sender_sig;
216
217   /**
218    * Monotonic time of @e sender, to possibly help detect replay attacks
219    * (if receiver persists times by sender).
220    */ 
221   struct GNUNET_TIME_AbsoluteNBO monotonic_time;
222
223 };
224
225
226 /**
227  * TCP finish. Sender asks for the connection to be closed.
228  * Needed/useful in case we drop RST/FIN packets on the GNUnet
229  * port due to the possibility of malicious RST/FIN injection.
230  */ 
231 struct TCPFinish
232 {
233
234   /**
235    * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH.
236    */ 
237   struct GNUNET_MessageHeader header;
238
239   /**
240    * HMAC for the following encrypted message.  Yes, we MUST use
241    * mac-then-encrypt here, as we want to hide the message sizes on
242    * the wire (zero plaintext design!).  Using CTR mode padding oracle
243    * attacks do not apply.  Besides, due to the use of ephemeral keys
244    * (hopefully with effective replay protection from monotonic time!)
245    * the attacker is limited in using the oracle.
246    */ 
247   struct GNUNET_ShortHashCode hmac;
248
249 };
250
251
252 GNUNET_NETWORK_STRUCT_END
253
254
255 /**
256  * Handle for a queue.
257  */
258 struct Queue
259 {
260
261   /**
262    * To whom are we talking to.
263    */
264   struct GNUNET_PeerIdentity target;
265
266   /**
267    * socket that we transmit all data with on this queue
268    */
269   struct GNUNET_NETWORK_Handle *sock;
270
271   /**
272    * cipher for decryption of incoming data.
273    */ 
274   gcry_cipher_hd_t in_cipher;
275
276   /**
277    * cipher for encryption of outgoing data.
278    */
279   gcry_cipher_hd_t out_cipher;
280
281   /**
282    * Shared secret for HMAC verification on incoming data.
283    */ 
284   struct GNUNET_HashCode in_hmac;
285
286   /**
287    * Shared secret for HMAC generation on outgoing data, ratcheted after
288    * each operation.
289    */ 
290   struct GNUNET_HashCode out_hmac;
291
292   /**
293    * Our ephemeral key. Stored here temporarily during rekeying / key generation.
294    */
295   struct GNUNET_CRYPTO_EcdhePrivateKey ephemeral;
296   
297   /**
298    * ID of read task for this connection.
299    */
300   struct GNUNET_SCHEDULER_Task *read_task;
301
302   /**
303    * ID of write task for this connection.
304    */
305   struct GNUNET_SCHEDULER_Task *write_task;
306
307   /**
308    * Address of the other peer.
309    */
310   struct sockaddr *address;
311   
312   /**
313    * How many more bytes may we sent with the current @e out_cipher
314    * before we should rekey?
315    */
316   uint64_t rekey_left_bytes;
317
318   /**
319    * Until what time may we sent with the current @e out_cipher
320    * before we should rekey?
321    */
322   struct GNUNET_TIME_Absolute rekey_time;
323   
324   /**
325    * Length of the address.
326    */
327   socklen_t address_len;
328
329   /**
330    * Message queue we are providing for the #ch.
331    */
332   struct GNUNET_MQ_Handle *mq;
333
334   /**
335    * handle for this queue with the #ch.
336    */
337   struct GNUNET_TRANSPORT_QueueHandle *qh;
338
339   /**
340    * Number of bytes we currently have in our write queue.
341    */
342   unsigned long long bytes_in_queue;
343
344   /**
345    * Buffer for reading ciphertext from network into.
346    */
347   char cread_buf[BUF_SIZE];
348
349   /**
350    * buffer for writing ciphertext to network.
351    */
352   char cwrite_buf[BUF_SIZE];
353
354   /**
355    * Plaintext buffer for decrypted plaintext.
356    */
357   char pread_buf[UINT16_MAX + 1 + sizeof (struct TCPBox)];
358
359   /**
360    * Plaintext buffer for messages to be encrypted.
361    */
362   char pwrite_buf[UINT16_MAX + 1 + sizeof (struct TCPBox)];
363   
364   /**
365    * At which offset in the ciphertext read buffer should we
366    * append more ciphertext for transmission next?
367    */
368   size_t cread_off;
369
370   /**
371    * At which offset in the ciphertext write buffer should we
372    * append more ciphertext from reading next?
373    */
374   size_t cwrite_off;
375   
376   /**
377    * At which offset in the plaintext input buffer should we
378    * append more plaintext from decryption next?
379    */
380   size_t pread_off;
381   
382   /**
383    * At which offset in the plaintext output buffer should we
384    * append more plaintext for encryption next?
385    */
386   size_t pwrite_off;
387
388   /**
389    * Timeout for this queue.
390    */
391   struct GNUNET_TIME_Absolute timeout;
392
393   /**
394    * How may messages did we pass from this queue to CORE for which we
395    * have yet to receive an acknoweldgement that CORE is done with
396    * them? If "large" (or even just non-zero), we should throttle
397    * reading to provide flow control.  See also #DEFAULT_MAX_QUEUE_LENGTH
398    * and #max_queue_length.
399    */ 
400   unsigned int backpressure;
401   
402   /**
403    * Which network type does this queue use?
404    */
405   enum GNUNET_NetworkType nt;
406   
407   /**
408    * Is MQ awaiting a #GNUNET_MQ_impl_send_continue() call?
409    */
410   int mq_awaits_continue;
411   
412   /**
413    * Did we enqueue a finish message and are closing down the queue?
414    */
415   int finishing;
416
417   /**
418    * Did we technically destroy this queue, but kept the allocation
419    * around because of @e backpressure not being zero yet? Used
420    * simply to delay the final #GNUNET_free() operation until
421    * #core_read_finished_cb() has been called.
422    */
423   int destroyed;
424
425   /**
426    * #GNUNET_YES after #inject_key() placed the rekey message into the
427    * plaintext buffer. Once the plaintext buffer is drained, this
428    * means we must switch to the new key material.
429    */
430   int rekey_state;
431
432   /**
433    * #GNUNET_YES if we just rekeyed and must thus possibly
434    * re-decrypt ciphertext.
435    */
436   int rekeyed;
437 };
438
439
440 /**
441  * Handle for an incoming connection where we do not yet have enough
442  * information to setup a full queue.
443  */
444 struct ProtoQueue
445 {
446
447   /**
448    * Kept in a DLL.
449    */ 
450   struct ProtoQueue *next;
451
452   /**
453    * Kept in a DLL.
454    */ 
455   struct ProtoQueue *prev;
456   
457   /**
458    * socket that we transmit all data with on this queue
459    */
460   struct GNUNET_NETWORK_Handle *sock;
461
462   /**
463    * ID of read task for this connection.
464    */
465   struct GNUNET_SCHEDULER_Task *read_task;
466
467   /**
468    * Address of the other peer.
469    */
470   struct sockaddr *address;
471
472   /**
473    * Length of the address.
474    */
475   socklen_t address_len;
476
477   /**
478    * Timeout for this protoqueue.
479    */
480   struct GNUNET_TIME_Absolute timeout;
481
482   /** 
483    * Buffer for reading all the information we need to upgrade from 
484    * protoqueue to queue.
485    */
486   char ibuf[INITIAL_KX_SIZE];
487
488   /**
489    * Current offset for reading into @e ibuf.
490    */ 
491   size_t ibuf_off;
492 };
493
494
495 /**
496  * ID of listen task
497  */
498 static struct GNUNET_SCHEDULER_Task *listen_task;
499
500 /**
501  * Maximum queue length before we stop reading towards the transport service.
502  */
503 static unsigned long long max_queue_length;
504
505 /**
506  * For logging statistics.
507  */
508 static struct GNUNET_STATISTICS_Handle *stats;
509
510 /**
511  * Our environment.
512  */
513 static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
514
515 /**
516  * Queues (map from peer identity to `struct Queue`)
517  */
518 static struct GNUNET_CONTAINER_MultiPeerMap *queue_map;
519
520 /**
521  * Listen socket.
522  */
523 static struct GNUNET_NETWORK_Handle *listen_sock;
524
525 /**
526  * Our public key.
527  */
528 static struct GNUNET_PeerIdentity my_identity;
529
530 /**
531  * Our private key.
532  */
533 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
534
535 /**
536  * Our configuration.
537  */
538 static const struct GNUNET_CONFIGURATION_Handle *cfg;
539
540 /**
541  * Network scanner to determine network types.
542  */
543 static struct GNUNET_NT_InterfaceScanner *is;
544
545 /**
546  * Connection to NAT service.
547  */
548 static struct GNUNET_NAT_Handle *nat;
549
550 /**
551  * Protoqueues DLL head.
552  */ 
553 static struct ProtoQueue *proto_head;
554
555 /**
556  * Protoqueues DLL tail.
557  */ 
558 static struct ProtoQueue *proto_tail;
559
560
561 /**
562  * We have been notified that our listen socket has something to
563  * read. Do the read and reschedule this function to be called again
564  * once more is available.
565  *
566  * @param cls NULL
567  */
568 static void
569 listen_cb (void *cls);
570
571
572 /**
573  * Functions with this signature are called whenever we need
574  * to close a queue due to a disconnect or failure to
575  * establish a connection.
576  *
577  * @param queue queue to close down
578  */
579 static void
580 queue_destroy (struct Queue *queue)
581 {
582   struct GNUNET_MQ_Handle *mq;
583
584   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
585               "Disconnecting queue for peer `%s'\n",
586               GNUNET_i2s (&queue->target));
587   if (NULL != (mq = queue->mq))
588   {
589     queue->mq = NULL;
590     GNUNET_MQ_destroy (mq);
591   }
592   GNUNET_assert (GNUNET_YES ==
593                  GNUNET_CONTAINER_multipeermap_remove (queue_map,
594                                                        &queue->target,
595                                                        queue));
596   GNUNET_STATISTICS_set (stats,
597                          "# queues active",
598                          GNUNET_CONTAINER_multipeermap_size (queue_map),
599                          GNUNET_NO);
600   if (NULL != queue->read_task)
601   {
602     GNUNET_SCHEDULER_cancel (queue->read_task);
603     queue->read_task = NULL;
604   }
605   if (NULL != queue->write_task)
606   {
607     GNUNET_SCHEDULER_cancel (queue->write_task);
608     queue->write_task = NULL;
609   }
610   GNUNET_NETWORK_socket_close (queue->sock);
611   gcry_cipher_close (queue->in_cipher);
612   gcry_cipher_close (queue->out_cipher);
613   GNUNET_free (queue->address);
614   if (0 != queue->backpressure)
615     queue->destroyed = GNUNET_YES;
616   else
617     GNUNET_free (queue);
618   if (NULL == listen_task)
619     listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
620                                                  listen_sock,
621                                                  &listen_cb,
622                                                  NULL);
623 }
624
625
626 /**
627  * Compute @a mac over @a buf, and ratched the @a hmac_secret.
628  *
629  * @param[in,out] hmac_secret secret for HMAC calculation
630  * @param buf buffer to MAC
631  * @param buf_size number of bytes in @a buf
632  * @param smac[out] where to write the HMAC
633  */
634 static void
635 hmac (struct GNUNET_HashCode *hmac_secret,
636       const void *buf,
637       size_t buf_size,
638       struct GNUNET_ShortHashCode *smac)
639 {
640   struct GNUNET_HashCode mac;
641
642   GNUNET_CRYPTO_hmac_raw (hmac_secret,
643                           sizeof (struct GNUNET_HashCode),
644                           buf,
645                           buf_size,
646                           &mac);
647   /* truncate to `struct GNUNET_ShortHashCode` */
648   memcpy (smac,
649           &mac,
650           sizeof (struct GNUNET_ShortHashCode));
651   /* ratchet hmac key */
652   GNUNET_CRYPTO_hash (hmac_secret,
653                       sizeof (struct GNUNET_HashCode),
654                       hmac_secret);
655 }
656
657
658 /**
659  * Append a 'finish' message to the outgoing transmission. Once the
660  * finish has been transmitted, destroy the queue.
661  *
662  * @param queue queue to shut down nicely
663  */
664 static void
665 queue_finish (struct Queue *queue)
666 {
667   struct TCPFinish fin;
668
669   memset (&fin,
670           0,
671           sizeof (fin));
672   fin.header.size = htons (sizeof (fin));
673   fin.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH);
674   hmac (&queue->out_hmac,
675         &fin,
676         sizeof (fin),
677         &fin.hmac);
678   /* if there is any message left in pwrite_buf, we 
679      overwrite it (possibly dropping the last message
680      from CORE hard here) */
681   memcpy (queue->pwrite_buf,
682           &fin,
683           sizeof (fin));
684   queue->pwrite_off = sizeof (fin);
685   /* This flag will ensure that #queue_write() no longer
686      notifies CORE about the possibility of sending
687      more data, and that #queue_write() will call
688      #queue_destroy() once the @c fin was fully written. */
689   queue->finishing = GNUNET_YES;
690 }
691
692
693 /**
694  * Increment queue timeout due to activity.  We do not immediately
695  * notify the monitor here as that might generate excessive
696  * signalling.
697  *
698  * @param queue queue for which the timeout should be rescheduled
699  */
700 static void
701 reschedule_queue_timeout (struct Queue *queue)
702 {
703   queue->timeout
704     = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
705 }
706
707
708 /**
709  * Queue read task. If we hit the timeout, disconnect it
710  *
711  * @param cls the `struct Queue *` to disconnect
712  */
713 static void
714 queue_read (void *cls);
715
716
717 /**
718  * Core tells us it is done processing a message that transport
719  * received on a queue with status @a success.
720  *
721  * @param cls a `struct Queue *` where the message originally came from
722  * @param success #GNUNET_OK on success
723  */
724 static void
725 core_read_finished_cb (void *cls,
726                        int success)
727 {
728   struct Queue *queue = cls;
729
730   if (GNUNET_OK != success)
731     GNUNET_STATISTICS_update (stats,
732                               "# messages lost in communicator API towards CORE",
733                               1,
734                               GNUNET_NO);
735   queue->backpressure--;
736   /* handle deferred queue destruction */
737   if ( (queue->destroyed) &&
738        (0 == queue->backpressure) )
739   {
740     GNUNET_free (queue);
741     return;
742   }
743   reschedule_queue_timeout (queue);
744   /* possibly unchoke reading, now that CORE made progress */
745   if (NULL == queue->read_task)
746     queue->read_task
747       = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining (queue->timeout),
748                                        queue->sock,
749                                        &queue_read,
750                                        queue);
751 }
752
753
754 /**
755  * We received @a plaintext_len bytes of @a plaintext on @a queue.
756  * Pass it on to CORE.  If transmission is actually happening,
757  * increase backpressure counter.
758  *
759  * @param queue the queue that received the plaintext
760  * @param plaintext the plaintext that was received
761  * @param plaintext_len number of bytes of plaintext received
762  */ 
763 static void
764 pass_plaintext_to_core (struct Queue *queue,
765                         const void *plaintext,
766                         size_t plaintext_len)
767 {
768   const struct GNUNET_MessageHeader *hdr = plaintext;
769   int ret;
770
771   if (ntohs (hdr->size) != plaintext_len)
772   {
773     /* NOTE: If we ever allow multiple CORE messages in one
774        BOX, this will have to change! */
775     GNUNET_break (0);
776     return;
777   }
778   ret = GNUNET_TRANSPORT_communicator_receive (ch,
779                                                &queue->target,
780                                                hdr,
781                                                &core_read_finished_cb,
782                                                queue);
783   if (GNUNET_OK == ret)
784     queue->backpressure++;
785   GNUNET_break (GNUNET_NO != ret); /* backpressure not working!? */
786   if (GNUNET_SYSERR == ret)
787     GNUNET_STATISTICS_update (stats,
788                               "# bytes lost due to CORE not running",
789                               plaintext_len,
790                               GNUNET_NO);
791 }
792
793
794 /**
795  * Setup @a cipher based on shared secret @a dh and decrypting
796  * peer @a pid.
797  *
798  * @param dh shared secret
799  * @param pid decrypting peer's identity
800  * @param cipher[out] cipher to initialize
801  * @param hmac_key[out] HMAC key to initialize
802  */
803 static void
804 setup_cipher (const struct GNUNET_HashCode *dh,
805               const struct GNUNET_PeerIdentity *pid,
806               gcry_cipher_hd_t *cipher,
807               struct GNUNET_HashCode *hmac_key)
808 {
809   char key[256/8];
810   char ctr[128/8];
811
812   gcry_cipher_open (cipher,
813                     GCRY_CIPHER_AES256 /* low level: go for speed */,
814                     GCRY_CIPHER_MODE_CTR,
815                     0 /* flags */);
816   GNUNET_assert (GNUNET_YES ==
817                  GNUNET_CRYPTO_kdf (key,
818                                     sizeof (key),
819                                     "TCP-key",
820                                     strlen ("TCP-key"),
821                                     dh,
822                                     sizeof (*dh),
823                                     pid,
824                                     sizeof (*pid),
825                                     NULL, 0));
826   gcry_cipher_setkey (*cipher,
827                       key,
828                       sizeof (key));
829   GNUNET_assert (GNUNET_YES ==
830                  GNUNET_CRYPTO_kdf (ctr,
831                                     sizeof (ctr),
832                                     "TCP-ctr",
833                                     strlen ("TCP-ctr"),
834                                     dh,
835                                     sizeof (*dh),
836                                     pid,
837                                     sizeof (*pid),
838                                     NULL, 0));
839   gcry_cipher_setctr (*cipher,
840                       ctr,
841                       sizeof (ctr));
842   GNUNET_assert (GNUNET_YES ==
843                  GNUNET_CRYPTO_kdf (hmac_key,
844                                     sizeof (struct GNUNET_HashCode),
845                                     "TCP-hmac",
846                                     strlen ("TCP-hmac"),
847                                     dh,
848                                     sizeof (*dh),
849                                     pid,
850                                     sizeof (*pid),
851                                     NULL, 0));
852 }
853
854
855 /**
856  * Setup cipher of @a queue for decryption.
857  *
858  * @param ephemeral ephemeral key we received from the other peer
859  * @param queue[in,out] queue to initialize decryption cipher for
860  */
861 static void
862 setup_in_cipher (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
863                  struct Queue *queue)
864 {
865   struct GNUNET_HashCode dh;
866   
867   GNUNET_CRYPTO_eddsa_ecdh (my_private_key,
868                             ephemeral,
869                             &dh);
870   setup_cipher (&dh,
871                 &my_identity,
872                 &queue->in_cipher,
873                 &queue->in_hmac);
874 }
875                 
876
877 /**
878  * Handle @a rekey message on @a queue. The message was already
879  * HMAC'ed, but we should additionally still check the signature.
880  * Then we need to stop the old cipher and start afresh.
881  *
882  * @param queue the queue @a rekey was received on
883  * @param rekey the rekey message
884  */ 
885 static void
886 do_rekey (struct Queue *queue,
887           const struct TCPRekey *rekey)
888 {
889   struct TcpHandshakeSignature thp;
890
891   thp.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY);
892   thp.purpose.size = htonl (sizeof (thp));
893   thp.sender = queue->target;
894   thp.receiver = my_identity;
895   thp.ephemeral = rekey->ephemeral;
896   thp.monotonic_time = rekey->monotonic_time;
897   if (GNUNET_OK !=
898       GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY,
899                                   &thp.purpose,
900                                   &rekey->sender_sig,
901                                   &queue->target.public_key))
902   {
903     GNUNET_break (0);
904     queue_finish (queue);
905     return;
906   }
907   gcry_cipher_close (queue->in_cipher);
908   queue->rekeyed = GNUNET_YES;
909   setup_in_cipher (&rekey->ephemeral,
910                    queue);
911 }
912
913
914 /**
915  * Test if we have received a full message in plaintext.
916  * If so, handle it.
917  *
918  * @param queue queue to process inbound plaintext for
919  * @return number of bytes of plaintext handled, 0 for none
920  */ 
921 static size_t
922 try_handle_plaintext (struct Queue *queue)
923 {
924   const struct GNUNET_MessageHeader *hdr
925     = (const struct GNUNET_MessageHeader *) queue->pread_buf;
926   const struct TCPBox *box
927     = (const struct TCPBox *) queue->pread_buf;
928   const struct TCPRekey *rekey
929     = (const struct TCPRekey *) queue->pread_buf;
930   const struct TCPFinish *fin
931     = (const struct TCPFinish *) queue->pread_buf;
932   struct TCPRekey rekeyz;
933   struct TCPFinish finz;
934   struct GNUNET_ShortHashCode tmac;
935   uint16_t type;
936   size_t size = 0; /* make compiler happy */
937
938   if (sizeof (*hdr) > queue->pread_off)
939     return 0; /* not even a header */
940   type = ntohs (hdr->type);
941   switch (type)
942   {
943   case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX:
944     /* Special case: header size excludes box itself! */
945     if (ntohs (hdr->size) + sizeof (struct TCPBox) > queue->pread_off)
946       return 0;
947     hmac (&queue->in_hmac,
948           &box[1],
949           ntohs (hdr->size),
950           &tmac);
951     if (0 != memcmp (&tmac,
952                      &box->hmac,
953                      sizeof (tmac)))
954     {
955       GNUNET_break_op (0);
956       queue_finish (queue);
957       return 0;
958     }
959     pass_plaintext_to_core (queue,
960                             (const void *) &box[1],
961                             ntohs (hdr->size));
962     size = ntohs (hdr->size) + sizeof (*box);
963     break;
964   case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY:
965     if (sizeof (*rekey) > queue->pread_off)
966       return 0;
967     if (ntohs (hdr->size) != sizeof (*rekey))
968     {
969       GNUNET_break_op (0);
970       queue_finish (queue);
971       return 0;
972     }
973     rekeyz = *rekey;
974     memset (&rekeyz.hmac,
975             0,
976             sizeof (rekeyz.hmac));
977     hmac (&queue->in_hmac,
978           &rekeyz,
979           sizeof (rekeyz),
980           &tmac);
981     if (0 != memcmp (&tmac,
982                      &box->hmac,
983                      sizeof (tmac)))
984     {
985       GNUNET_break_op (0);
986       queue_finish (queue);
987       return 0;
988     }
989     do_rekey (queue,
990               rekey);
991     size = ntohs (hdr->size);
992     break;
993   case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH:
994     if (sizeof (*fin) > queue->pread_off)
995       return 0;
996     if (ntohs (hdr->size) != sizeof (*fin))
997     {
998       GNUNET_break_op (0);
999       queue_finish (queue);
1000       return 0;
1001     }
1002     finz = *fin;
1003     memset (&finz.hmac,
1004             0,
1005             sizeof (finz.hmac));
1006     hmac (&queue->in_hmac,
1007           &rekeyz,
1008           sizeof (rekeyz),
1009           &tmac);
1010     if (0 != memcmp (&tmac,
1011                      &fin->hmac,
1012                      sizeof (tmac)))
1013     {
1014       GNUNET_break_op (0);
1015       queue_finish (queue);
1016       return 0;
1017     }
1018     /* handle FINISH by destroying queue */
1019     queue_destroy (queue);
1020     break;
1021   default:
1022     GNUNET_break_op (0);
1023     queue_finish (queue);
1024     return 0;
1025   }
1026   GNUNET_assert (0 != size);
1027   return size;
1028 }
1029
1030
1031 /**
1032  * Queue read task. If we hit the timeout, disconnect it
1033  *
1034  * @param cls the `struct Queue *` to disconnect
1035  */
1036 static void
1037 queue_read (void *cls)
1038 {
1039   struct Queue *queue = cls;
1040   struct GNUNET_TIME_Relative left;
1041   ssize_t rcvd;
1042
1043   queue->read_task = NULL;
1044   rcvd = GNUNET_NETWORK_socket_recv (queue->sock,
1045                                      &queue->cread_buf[queue->cread_off],
1046                                      BUF_SIZE - queue->cread_off);
1047   if (-1 == rcvd)
1048   {
1049     if ( (EAGAIN != errno) &&
1050          (EINTR != errno) )
1051     {
1052       GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1053                            "recv");
1054       queue_finish (queue);
1055       return;
1056     }
1057     /* try again */
1058     queue->read_task
1059       = GNUNET_SCHEDULER_add_read_net (left,
1060                                        queue->sock,
1061                                        &queue_read,
1062                                        queue);
1063     return;
1064   }
1065   if (0 != rcvd)
1066     reschedule_queue_timeout (queue);
1067   queue->cread_off += rcvd;
1068   while ( (queue->pread_off < sizeof (queue->pread_buf)) &&
1069           (queue->cread_off > 0) )
1070   {
1071     size_t max = GNUNET_MIN (sizeof (queue->pread_buf) - queue->pread_off,
1072                              queue->cread_off);
1073     size_t done;
1074     size_t total;
1075     
1076     GNUNET_assert (0 ==
1077                    gcry_cipher_decrypt (queue->in_cipher,
1078                                         &queue->pread_buf[queue->pread_off],
1079                                         max,
1080                                         queue->cread_buf,
1081                                         max));
1082     queue->pread_off += max;
1083     total = 0;
1084     while ( (GNUNET_NO == queue->rekeyed) &&
1085             (0 != (done = try_handle_plaintext (queue))) )          
1086     {
1087       /* 'done' bytes of plaintext were used, shift buffer */
1088       GNUNET_assert (done <= queue->pread_off);
1089       /* NOTE: this memmove() could possibly sometimes be
1090          avoided if we pass 'total' into try_handle_plaintext()
1091          and use it at an offset into the buffer there! */
1092       memmove (queue->pread_buf,
1093                &queue->pread_buf[done],
1094                queue->pread_off - done);
1095       queue->pread_off -= done;
1096       total += done;
1097     }
1098     /* when we encounter a rekey message, the decryption above uses the
1099        wrong key for everything after the rekey; in that case, we have
1100        to re-do the decryption at 'total' instead of at 'max'. If there
1101        is no rekey and the last message is incomplete (max > total),
1102        it is safe to keep the decryption so we shift by 'max' */
1103     if (GNUNET_YES == queue->rekeyed)
1104     {
1105       max = total;
1106       queue->rekeyed = GNUNET_NO;
1107     }
1108     memmove (queue->cread_buf,
1109              &queue->cread_buf[max],
1110              queue->cread_off - max);
1111     queue->cread_off -= max; 
1112   }
1113   
1114   if (BUF_SIZE == queue->cread_off)
1115     return; /* buffer full, suspend reading */
1116   left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
1117   if (0 != left.rel_value_us) 
1118   {
1119     if (max_queue_length < queue->backpressure)
1120     {
1121       /* continue reading */
1122       queue->read_task
1123         = GNUNET_SCHEDULER_add_read_net (left,
1124                                          queue->sock,
1125                                          &queue_read,
1126                                          queue);
1127     }
1128     return;
1129   }
1130   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1131               "Queue %p was idle for %s, disconnecting\n",
1132               queue,
1133               GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1134                                                       GNUNET_YES));
1135   queue_finish (queue);
1136 }
1137
1138
1139 /**
1140  * Convert TCP bind specification to a `struct sockaddr *`
1141  *
1142  * @param bindto bind specification to convert
1143  * @param[out] sock_len set to the length of the address
1144  * @return converted bindto specification
1145  */
1146 static struct sockaddr *
1147 tcp_address_to_sockaddr (const char *bindto,
1148                          socklen_t *sock_len)
1149 {
1150   struct sockaddr *in;
1151   unsigned int port;
1152   char dummy[2];
1153   char *colon;
1154   char *cp;
1155   
1156   if (1 == SSCANF (bindto,
1157                    "%u%1s",
1158                    &port,
1159                    dummy))
1160   {
1161     /* interpreting value as just a PORT number */
1162     if (port > UINT16_MAX)
1163     {
1164       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1165                   "BINDTO specification `%s' invalid: value too large for port\n",
1166                   bindto);
1167       return NULL;
1168     }
1169     if (GNUNET_YES ==
1170         GNUNET_CONFIGURATION_get_value_yesno (cfg,
1171                                               COMMUNICATOR_CONFIG_SECTION,
1172                                               "DISABLE_V6"))
1173     {
1174       struct sockaddr_in *i4;
1175       
1176       i4 = GNUNET_malloc (sizeof (struct sockaddr_in));
1177       i4->sin_family = AF_INET;
1178       i4->sin_port = htons ((uint16_t) port);
1179       *sock_len = sizeof (struct sockaddr_in);
1180       in = (struct sockaddr *) i4;
1181     }
1182     else
1183     {
1184       struct sockaddr_in6 *i6;
1185       
1186       i6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
1187       i6->sin6_family = AF_INET6;
1188       i6->sin6_port = htons ((uint16_t) port);
1189       *sock_len = sizeof (struct sockaddr_in6);
1190       in = (struct sockaddr *) i6;
1191     }
1192     return in;
1193   }
1194   cp = GNUNET_strdup (bindto);
1195   colon = strrchr (cp, ':');
1196   if (NULL != colon)
1197   {
1198     /* interpet value after colon as port */
1199     *colon = '\0';
1200     colon++;
1201     if (1 == SSCANF (colon,
1202                      "%u%1s",
1203                      &port,
1204                      dummy))
1205     {
1206       /* interpreting value as just a PORT number */
1207       if (port > UINT16_MAX)
1208       {
1209         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1210                     "BINDTO specification `%s' invalid: value too large for port\n",
1211                     bindto);
1212         GNUNET_free (cp);
1213         return NULL;
1214       }
1215     }
1216     else
1217     {
1218       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1219                   "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1220                   bindto);
1221       GNUNET_free (cp);
1222       return NULL;
1223     }
1224   }
1225   else
1226   {
1227     /* interpret missing port as 0, aka pick any free one */
1228     port = 0;
1229   }
1230   {
1231     /* try IPv4 */
1232     struct sockaddr_in v4;
1233
1234     if (1 == inet_pton (AF_INET,
1235                         cp,
1236                         &v4))
1237     {
1238       v4.sin_port = htons ((uint16_t) port);
1239       in = GNUNET_memdup (&v4,
1240                           sizeof (v4));
1241       *sock_len = sizeof (v4);
1242       GNUNET_free (cp);
1243       return in;
1244     }
1245   }
1246   {
1247     /* try IPv6 */
1248     struct sockaddr_in6 v6;
1249     const char *start;
1250
1251     start = cp;
1252     if ( ('[' == *cp) &&
1253          (']' == cp[strlen (cp)-1]) )
1254     {
1255       start++; /* skip over '[' */
1256       cp[strlen (cp) -1] = '\0'; /* eat ']' */
1257     }
1258     if (1 == inet_pton (AF_INET6,
1259                         start,
1260                         &v6))
1261     {
1262       v6.sin6_port = htons ((uint16_t) port);
1263       in = GNUNET_memdup (&v6,
1264                           sizeof (v6));
1265       *sock_len = sizeof (v6);
1266       GNUNET_free (cp);
1267       return in;
1268     }
1269   }
1270   /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1271   GNUNET_free (cp);
1272   return NULL;
1273 }
1274
1275
1276 /**
1277  * Setup cipher for outgoing data stream based on target and
1278  * our ephemeral private key.
1279  *
1280  * @param queue queue to setup outgoing (encryption) cipher for
1281  */
1282 static void
1283 setup_out_cipher (struct Queue *queue)
1284 {
1285   struct GNUNET_HashCode dh;
1286   
1287   GNUNET_CRYPTO_ecdh_eddsa (&queue->ephemeral,
1288                             &queue->target.public_key,
1289                             &dh);
1290   /* we don't need the private key anymore, drop it! */
1291   memset (&queue->ephemeral,
1292           0,
1293           sizeof (queue->ephemeral));
1294   setup_cipher (&dh,
1295                 &queue->target,
1296                 &queue->out_cipher,
1297                 &queue->out_hmac);
1298   
1299   queue->rekey_time = GNUNET_TIME_relative_to_absolute (REKEY_TIME_INTERVAL);
1300   queue->rekey_left_bytes = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
1301                                                       REKEY_MAX_BYTES);
1302 }
1303
1304
1305 /**
1306  * Inject a `struct TCPRekey` message into the queue's plaintext
1307  * buffer.
1308  *
1309  * @param queue queue to perform rekeying on
1310  */ 
1311 static void
1312 inject_rekey (struct Queue *queue)
1313 {
1314   struct TCPRekey rekey;
1315   struct TcpHandshakeSignature thp;
1316   
1317   GNUNET_assert (0 == queue->pwrite_off);
1318   memset (&rekey,
1319           0,
1320           sizeof (rekey));
1321   GNUNET_assert (GNUNET_OK ==
1322                  GNUNET_CRYPTO_ecdhe_key_create2 (&queue->ephemeral));
1323   rekey.header.type = ntohs (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY);
1324   rekey.header.size = ntohs (sizeof (rekey));
1325   GNUNET_CRYPTO_ecdhe_key_get_public (&queue->ephemeral,
1326                                       &rekey.ephemeral);
1327   rekey.monotonic_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1328   thp.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY);
1329   thp.purpose.size = htonl (sizeof (thp));
1330   thp.sender = my_identity;
1331   thp.receiver = queue->target;
1332   thp.ephemeral = rekey.ephemeral;
1333   thp.monotonic_time = rekey.monotonic_time;
1334   GNUNET_assert (GNUNET_OK ==
1335                  GNUNET_CRYPTO_eddsa_sign (my_private_key,
1336                                            &thp.purpose,
1337                                            &rekey.sender_sig));
1338   hmac (&queue->out_hmac,
1339         &rekey,
1340         sizeof (rekey),
1341         &rekey.hmac);
1342   memcpy (queue->pwrite_buf,
1343           &rekey,
1344           sizeof (rekey));
1345   queue->rekey_state = GNUNET_YES;
1346 }
1347
1348
1349 /**
1350  * We encrypted the rekey message, now update actually swap the key
1351  * material and update the key freshness parameters of @a queue.
1352  */ 
1353 static void
1354 switch_key (struct Queue *queue)
1355 {
1356   queue->rekey_state = GNUNET_NO; 
1357   gcry_cipher_close (queue->out_cipher);
1358   setup_out_cipher (queue);
1359 }
1360
1361
1362 /**
1363  * We have been notified that our socket is ready to write.
1364  * Then reschedule this function to be called again once more is available.
1365  *
1366  * @param cls a `struct Queue`
1367  */
1368 static void
1369 queue_write (void *cls)
1370 {
1371   struct Queue *queue = cls;
1372   ssize_t sent;
1373
1374   queue->write_task = NULL;
1375   sent = GNUNET_NETWORK_socket_send (queue->sock,
1376                                      queue->cwrite_buf,
1377                                      queue->cwrite_off);
1378   if ( (-1 == sent) &&
1379        (EAGAIN != errno) &&
1380        (EINTR != errno) )
1381   {
1382     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1383                          "send");
1384     queue_destroy (queue);
1385     return;                      
1386   }
1387   if (sent > 0)
1388   {
1389     size_t usent = (size_t) sent;
1390
1391     memmove (queue->cwrite_buf,
1392              &queue->cwrite_buf[usent],
1393              queue->cwrite_off - usent);
1394     reschedule_queue_timeout (queue);
1395  }
1396   /* can we encrypt more? (always encrypt full messages, needed
1397      such that #mq_cancel() can work!) */
1398   if (queue->cwrite_off + queue->pwrite_off <= BUF_SIZE)
1399   {
1400     GNUNET_assert (0 ==
1401                    gcry_cipher_encrypt (queue->out_cipher,
1402                                         &queue->cwrite_buf[queue->cwrite_off],
1403                                         queue->pwrite_off,
1404                                         queue->pwrite_buf,
1405                                         queue->pwrite_off));
1406     if (queue->rekey_left_bytes > queue->pwrite_off)
1407       queue->rekey_left_bytes -= queue->pwrite_off;
1408     else
1409       queue->rekey_left_bytes = 0;
1410     queue->cwrite_off += queue->pwrite_off;
1411     queue->pwrite_off = 0;
1412   }
1413   if ( (GNUNET_YES == queue->rekey_state) &&
1414        (0 == queue->pwrite_off) )
1415     switch_key (queue);
1416   if ( (0 == queue->pwrite_off) &&
1417        ( (0 == queue->rekey_left_bytes) ||
1418          (0 == GNUNET_TIME_absolute_get_remaining (queue->rekey_time).rel_value_us) ) )
1419     inject_rekey (queue);
1420   if ( (0 == queue->pwrite_off) &&
1421        (! queue->finishing) &&
1422        (queue->mq_awaits_continue) )
1423   {
1424     queue->mq_awaits_continue = GNUNET_NO;
1425     GNUNET_MQ_impl_send_continue (queue->mq);
1426   }
1427   /* did we just finish writing 'finish'? */
1428   if ( (0 == queue->cwrite_off) &&
1429        (GNUNET_YES == queue->finishing) )
1430   {
1431     queue_destroy (queue);
1432     return;
1433   }
1434   /* do we care to write more? */
1435   if (0 < queue->cwrite_off)
1436     queue->write_task 
1437       = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1438                                         queue->sock,
1439                                         &queue_write,
1440                                         queue);
1441 }
1442
1443
1444 /**
1445  * Signature of functions implementing the sending functionality of a
1446  * message queue.
1447  *
1448  * @param mq the message queue
1449  * @param msg the message to send
1450  * @param impl_state our `struct Queue`
1451  */
1452 static void
1453 mq_send (struct GNUNET_MQ_Handle *mq,
1454          const struct GNUNET_MessageHeader *msg,
1455          void *impl_state)
1456 {
1457   struct Queue *queue = impl_state;
1458   uint16_t msize = ntohs (msg->size);
1459   struct TCPBox box;
1460
1461   GNUNET_assert (mq == queue->mq);
1462   if (GNUNET_YES == queue->finishing)
1463     return; /* this queue is dying, drop msg */
1464   GNUNET_assert (0 == queue->pread_off);
1465   box.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX);
1466   box.header.size = htons (msize);
1467   hmac (&queue->out_hmac,
1468         msg,
1469         msize,
1470         &box.hmac);
1471   memcpy (&queue->pread_buf[queue->pread_off],
1472           &box,
1473           sizeof (box));
1474   queue->pread_off += sizeof (box);
1475   memcpy (&queue->pread_buf[queue->pread_off],
1476           msg,
1477           msize);
1478   queue->pread_off += msize;
1479   GNUNET_assert (NULL != queue->sock);
1480   if (NULL == queue->write_task)
1481     queue->write_task =
1482       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1483                                       queue->sock,
1484                                       &queue_write,
1485                                       queue);
1486 }
1487
1488
1489 /**
1490  * Signature of functions implementing the destruction of a message
1491  * queue.  Implementations must not free @a mq, but should take care
1492  * of @a impl_state.
1493  *
1494  * @param mq the message queue to destroy
1495  * @param impl_state our `struct Queue`
1496  */
1497 static void
1498 mq_destroy (struct GNUNET_MQ_Handle *mq,
1499             void *impl_state)
1500 {
1501   struct Queue *queue = impl_state;
1502
1503   if (mq == queue->mq)
1504   {
1505     queue->mq = NULL;
1506     queue_finish (queue);
1507   }
1508 }
1509
1510
1511 /**
1512  * Implementation function that cancels the currently sent message.
1513  *
1514  * @param mq message queue
1515  * @param impl_state our `struct Queue`
1516  */
1517 static void
1518 mq_cancel (struct GNUNET_MQ_Handle *mq,
1519            void *impl_state)
1520 {
1521   struct Queue *queue = impl_state;
1522
1523   GNUNET_assert (0 != queue->pwrite_off);
1524   queue->pwrite_off = 0;
1525 }
1526
1527
1528 /**
1529  * Generic error handler, called with the appropriate
1530  * error code and the same closure specified at the creation of
1531  * the message queue.
1532  * Not every message queue implementation supports an error handler.
1533  *
1534  * @param cls our `struct Queue`
1535  * @param error error code
1536  */
1537 static void
1538 mq_error (void *cls,
1539           enum GNUNET_MQ_Error error)
1540 {
1541   struct Queue *queue = cls;
1542
1543   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1544               "MQ error in queue to %s: %d\n",
1545               GNUNET_i2s (&queue->target),
1546               (int) error);
1547   queue_finish (queue);
1548 }
1549
1550
1551 /**
1552  * Add the given @a queue to our internal data structure.  Setup the
1553  * MQ processing and inform transport that the queue is ready.  Must
1554  * be called after the KX for outgoing messages has been bootstrapped.
1555  *
1556  * @param queue queue to boot
1557  */ 
1558 static void
1559 boot_queue (struct Queue *queue,
1560             enum GNUNET_TRANSPORT_ConnectionStatus cs)
1561 {
1562   queue->nt = GNUNET_NT_scanner_get_type (is,
1563                                           queue->address,
1564                                           queue->address_len);
1565   (void) GNUNET_CONTAINER_multipeermap_put (queue_map,
1566                                             &queue->target,
1567                                             queue,
1568                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1569   GNUNET_STATISTICS_set (stats,
1570                          "# queues active",
1571                          GNUNET_CONTAINER_multipeermap_size (queue_map),
1572                          GNUNET_NO);
1573   queue->timeout
1574     = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1575   queue->mq
1576     = GNUNET_MQ_queue_for_callbacks (&mq_send,
1577                                      &mq_destroy,
1578                                      &mq_cancel,
1579                                      queue,
1580                                      NULL,
1581                                      &mq_error,
1582                                      queue);
1583   {
1584     char *foreign_addr;
1585
1586     switch (queue->address->sa_family)
1587     {
1588     case AF_INET:
1589       GNUNET_asprintf (&foreign_addr,
1590                        "%s-%s",
1591                        COMMUNICATOR_ADDRESS_PREFIX,
1592                        GNUNET_a2s(queue->address,
1593                                   queue->address_len));
1594       break;
1595     case AF_INET6:
1596       GNUNET_asprintf (&foreign_addr,
1597                        "%s-%s",
1598                        COMMUNICATOR_ADDRESS_PREFIX,
1599                        GNUNET_a2s(queue->address,
1600                                   queue->address_len));
1601       break;
1602     default:
1603       GNUNET_assert (0);
1604     }
1605     queue->qh
1606       = GNUNET_TRANSPORT_communicator_mq_add (ch,
1607                                               &queue->target,
1608                                               foreign_addr,
1609                                               0 /* no MTU */,
1610                                               queue->nt,
1611                                               cs,
1612                                               queue->mq);
1613     GNUNET_free (foreign_addr);
1614   }
1615 }
1616
1617
1618 /**
1619  * Generate and transmit our ephemeral key and the signature for
1620  * the initial KX with the other peer.  Must be called first, before
1621  * any other bytes are ever written to the output buffer.  Note that
1622  * our cipher must already be initialized when calling this function.
1623  * Helper function for #start_initial_kx_out().
1624  *
1625  * @param queue queue to do KX for
1626  * @param epub our public key for the KX
1627  */
1628 static void
1629 transmit_kx (struct Queue *queue,
1630              const struct GNUNET_CRYPTO_EcdhePublicKey *epub)
1631 {
1632   struct TcpHandshakeSignature ths;
1633   struct TCPConfirmation tc;
1634
1635   memcpy (queue->cwrite_buf,
1636           epub,
1637           sizeof (*epub));
1638   queue->cwrite_off = sizeof (epub);
1639   /* compute 'tc' and append in encrypted format to cwrite_buf */
1640   tc.sender = my_identity;
1641   tc.monotonic_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1642   ths.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE);
1643   ths.purpose.size = htonl (sizeof (ths));
1644   ths.sender = my_identity;
1645   ths.receiver = queue->target;
1646   ths.ephemeral = *epub;
1647   ths.monotonic_time = tc.monotonic_time;
1648   GNUNET_assert (GNUNET_OK ==
1649                  GNUNET_CRYPTO_eddsa_sign (my_private_key,
1650                                            &ths.purpose,
1651                                            &tc.sender_sig));
1652   GNUNET_assert (0 ==
1653                  gcry_cipher_encrypt (queue->out_cipher,
1654                                       &queue->cwrite_buf[queue->cwrite_off],
1655                                       sizeof (tc),
1656                                       &tc,
1657                                       sizeof (tc)));
1658   queue->cwrite_off += sizeof (tc);
1659 }
1660
1661
1662 /**
1663  * Initialize our key material for outgoing transmissions and 
1664  * inform the other peer about it. Must be called first before
1665  * any data is sent.
1666  *
1667  * @param queue the queue to setup
1668  */
1669 static void
1670 start_initial_kx_out (struct Queue *queue)
1671 {
1672   struct GNUNET_CRYPTO_EcdhePublicKey epub;
1673
1674   GNUNET_assert (GNUNET_OK ==
1675                  GNUNET_CRYPTO_ecdhe_key_create2 (&queue->ephemeral)); 
1676   GNUNET_CRYPTO_ecdhe_key_get_public (&queue->ephemeral,
1677                                       &epub);
1678   setup_out_cipher (queue);
1679   transmit_kx (queue,
1680                &epub);
1681 }
1682
1683
1684 /**
1685  * We have received the first bytes from the other side on a @a queue.
1686  * Decrypt the @a tc contained in @a ibuf and check the signature.
1687  * Note that #setup_in_cipher() must have already been called.
1688  *
1689  * @param queue queue to decrypt initial bytes from other peer for
1690  * @param tc[out] where to store the result
1691  * @param ibuf incoming data, of size 
1692  *        `INITIAL_KX_SIZE`
1693  * @return #GNUNET_OK if the signature was OK, #GNUNET_SYSERR if not
1694  */
1695 static int
1696 decrypt_and_check_tc (struct Queue *queue,
1697                       struct TCPConfirmation *tc,
1698                       char *ibuf)
1699 {
1700   struct TcpHandshakeSignature ths;
1701                         
1702   GNUNET_assert (0 ==
1703                  gcry_cipher_decrypt (queue->in_cipher,
1704                                       tc,
1705                                       sizeof (*tc),
1706                                       &ibuf[sizeof (struct GNUNET_CRYPTO_EcdhePublicKey)],
1707                                       sizeof (tc)));
1708   ths.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE);
1709   ths.purpose.size = htonl (sizeof (ths));
1710   ths.sender = tc->sender;
1711   ths.receiver = my_identity;
1712   memcpy (&ths.ephemeral,
1713           ibuf,
1714           sizeof (struct GNUNET_CRYPTO_EcdhePublicKey));
1715   ths.monotonic_time = tc->monotonic_time;
1716   return GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE,
1717                                      &ths.purpose,
1718                                      &tc->sender_sig,
1719                                      &tc->sender.public_key);
1720 }
1721
1722
1723 /**
1724  * Closes socket and frees memory associated with @a pq.
1725  *
1726  * @param pq proto queue to free
1727  */ 
1728 static void
1729 free_proto_queue (struct ProtoQueue *pq)
1730 {
1731   GNUNET_NETWORK_socket_close (pq->sock);
1732   GNUNET_free (pq->address);
1733   GNUNET_CONTAINER_DLL_remove (proto_head,
1734                                proto_tail,
1735                                pq);
1736   GNUNET_free (pq);
1737 }
1738  
1739
1740 /**
1741  * Read from the socket of the proto queue until we have enough data
1742  * to upgrade to full queue.
1743  *
1744  * @param cls a `struct ProtoQueue`
1745  */
1746 static void
1747 proto_read_kx (void *cls)
1748 {
1749   struct ProtoQueue *pq = cls;
1750   ssize_t rcvd;
1751   struct GNUNET_TIME_Relative left;
1752   struct Queue *queue;
1753   struct TCPConfirmation tc;
1754   
1755   pq->read_task = NULL;
1756   left = GNUNET_TIME_absolute_get_remaining (pq->timeout);
1757   if (0 == left.rel_value_us)
1758   {
1759     free_proto_queue (pq);
1760     return;
1761   }
1762   rcvd = GNUNET_NETWORK_socket_recv (pq->sock,
1763                                      &pq->ibuf[pq->ibuf_off],
1764                                      sizeof (pq->ibuf) - pq->ibuf_off);
1765   if (-1 == rcvd)
1766   {
1767     if ( (EAGAIN != errno) &&
1768          (EINTR != errno) )
1769     {
1770       GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1771                            "recv");
1772       free_proto_queue (pq);
1773       return;
1774     }
1775     /* try again */
1776     pq->read_task = GNUNET_SCHEDULER_add_read_net (left,
1777                                                    pq->sock,
1778                                                    &proto_read_kx,
1779                                                    pq);
1780     return;    
1781   }
1782   pq->ibuf_off += rcvd;
1783   if (pq->ibuf_off > sizeof (pq->ibuf))
1784   {
1785     /* read more */
1786     pq->read_task = GNUNET_SCHEDULER_add_read_net (left,
1787                                                    pq->sock,
1788                                                    &proto_read_kx,
1789                                                    pq);
1790     return;
1791   }
1792   /* we got all the data, let's find out who we are talking to! */
1793   queue = GNUNET_new (struct Queue);
1794   setup_in_cipher ((const struct GNUNET_CRYPTO_EcdhePublicKey *) pq->ibuf,
1795                    queue);
1796   if (GNUNET_OK !=
1797       decrypt_and_check_tc (queue,
1798                             &tc,
1799                             pq->ibuf))
1800   {
1801     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1802                 "Invalid TCP KX received from %s\n",
1803                 GNUNET_a2s (queue->address,
1804                             queue->address_len));
1805     gcry_cipher_close (queue->in_cipher);
1806     GNUNET_free (queue);
1807     free_proto_queue (pq);
1808     return;    
1809   }
1810   queue->address = pq->address; /* steals reference */
1811   queue->address_len = pq->address_len;
1812   queue->target = tc.sender;
1813   start_initial_kx_out (queue);
1814   boot_queue (queue,
1815               GNUNET_TRANSPORT_CS_INBOUND);
1816   queue->read_task
1817     = GNUNET_SCHEDULER_add_read_net (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1818                                      queue->sock,
1819                                      &queue_read,
1820                                      queue);
1821   GNUNET_CONTAINER_DLL_remove (proto_head,
1822                                proto_tail,
1823                                pq);
1824   GNUNET_free (pq);
1825 }
1826
1827
1828 /**
1829  * We have been notified that our listen socket has something to
1830  * read. Do the read and reschedule this function to be called again
1831  * once more is available.
1832  *
1833  * @param cls NULL
1834  */
1835 static void
1836 listen_cb (void *cls)
1837 {
1838   struct sockaddr_storage in;
1839   socklen_t addrlen;
1840   struct GNUNET_NETWORK_Handle *sock;
1841   struct ProtoQueue *pq;
1842
1843   listen_task = NULL;
1844   GNUNET_assert (NULL != listen_sock);
1845   addrlen = sizeof (in);
1846   memset (&in,
1847           0,
1848           sizeof (in));
1849   sock = GNUNET_NETWORK_socket_accept (listen_sock,
1850                                        (struct sockaddr *) &in,
1851                                        &addrlen);
1852   if ( (NULL == sock) &&
1853        ( (EMFILE == errno) ||
1854          (ENFILE == errno) ) )
1855     return; /* system limit reached, wait until connection goes down */
1856   listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1857                                                listen_sock,
1858                                                &listen_cb,
1859                                                NULL);
1860   if ( (NULL == sock) &&
1861        ( (EAGAIN == errno) ||
1862          (ENOBUFS == errno) ) )
1863     return;
1864   if (NULL == sock)
1865   {
1866     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1867                          "accept");
1868     return;
1869   }
1870   pq = GNUNET_new (struct ProtoQueue);
1871   pq->address_len = addrlen;
1872   pq->address = GNUNET_memdup (&in,
1873                                addrlen);
1874   pq->timeout = GNUNET_TIME_relative_to_absolute (PROTO_QUEUE_TIMEOUT);
1875   pq->sock = sock;
1876   pq->read_task = GNUNET_SCHEDULER_add_read_net (PROTO_QUEUE_TIMEOUT,
1877                                                  pq->sock,
1878                                                  &proto_read_kx,
1879                                                  pq);
1880   GNUNET_CONTAINER_DLL_insert (proto_head,
1881                                proto_tail,
1882                                pq);
1883 }
1884
1885
1886 /**
1887  * Read from the socket of the queue until we have enough data
1888  * to initialize the decryption logic and can switch to regular
1889  * reading.
1890  *
1891  * @param cls a `struct Queue`
1892  */
1893 static void
1894 queue_read_kx (void *cls)
1895 {
1896   struct Queue *queue = cls;
1897   ssize_t rcvd;
1898   struct GNUNET_TIME_Relative left;
1899   struct TCPConfirmation tc;
1900   
1901   queue->read_task = NULL;
1902   left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
1903   if (0 == left.rel_value_us)
1904   {
1905     queue_destroy (queue);
1906     return;
1907   }
1908   rcvd = GNUNET_NETWORK_socket_recv (queue->sock,
1909                                      &queue->cread_buf[queue->cread_off],
1910                                      BUF_SIZE - queue->cread_off);
1911   if (-1 == rcvd)
1912   {
1913     if ( (EAGAIN != errno) &&
1914          (EINTR != errno) )
1915     {
1916       GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1917                            "recv");
1918       queue_destroy (queue);
1919       return;
1920     }
1921     queue->read_task = GNUNET_SCHEDULER_add_read_net (left,
1922                                                       queue->sock,
1923                                                       &queue_read_kx,
1924                                                       queue);
1925     return;
1926   }
1927   queue->cread_off += rcvd;
1928   if (queue->cread_off <
1929       INITIAL_KX_SIZE)
1930   {
1931     /* read more */
1932     queue->read_task = GNUNET_SCHEDULER_add_read_net (left,
1933                                                       queue->sock,
1934                                                       &queue_read_kx,
1935                                                       queue);
1936     return;
1937   }
1938   /* we got all the data, let's find out who we are talking to! */
1939   setup_in_cipher ((const struct GNUNET_CRYPTO_EcdhePublicKey *) queue->cread_buf,
1940                    queue);
1941   if (GNUNET_OK !=
1942       decrypt_and_check_tc (queue,
1943                             &tc,
1944                             queue->cread_buf))
1945   {
1946     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1947                 "Invalid TCP KX received from %s\n",
1948                 GNUNET_a2s (queue->address,
1949                             queue->address_len));
1950     queue_destroy (queue);
1951     return;
1952   }
1953   if (0 != memcmp (&tc.sender,
1954                    &queue->target,
1955                    sizeof (struct GNUNET_PeerIdentity)))
1956   {
1957     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1958                 "Invalid sender in TCP KX received from %s\n",
1959                 GNUNET_a2s (queue->address,
1960                             queue->address_len));
1961     queue_destroy (queue);
1962     return;
1963   }
1964
1965   /* update queue timeout */
1966   reschedule_queue_timeout (queue);
1967   /* prepare to continue with regular read task immediately */
1968   memmove (queue->cread_buf,
1969            &queue->cread_buf[INITIAL_KX_SIZE],
1970            queue->cread_off - (INITIAL_KX_SIZE));
1971   queue->cread_off -= INITIAL_KX_SIZE;
1972   queue->read_task = GNUNET_SCHEDULER_add_now (&queue_read,
1973                                                queue);
1974 }
1975                                       
1976
1977 /**
1978  * Function called by the transport service to initialize a
1979  * message queue given address information about another peer.
1980  * If and when the communication channel is established, the
1981  * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
1982  * to notify the service that the channel is now up.  It is
1983  * the responsibility of the communicator to manage sane
1984  * retries and timeouts for any @a peer/@a address combination
1985  * provided by the transport service.  Timeouts and retries
1986  * do not need to be signalled to the transport service.
1987  *
1988  * @param cls closure
1989  * @param peer identity of the other peer
1990  * @param address where to send the message, human-readable
1991  *        communicator-specific format, 0-terminated, UTF-8
1992  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is invalid
1993  */
1994 static int
1995 mq_init (void *cls,
1996          const struct GNUNET_PeerIdentity *peer,
1997          const char *address)
1998 {
1999   struct Queue *queue;
2000   const char *path;
2001   struct sockaddr *in;
2002   socklen_t in_len;
2003   struct GNUNET_NETWORK_Handle *sock;
2004   
2005   if (0 != strncmp (address,
2006                     COMMUNICATOR_ADDRESS_PREFIX "-",
2007                     strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
2008   {
2009     GNUNET_break_op (0);
2010     return GNUNET_SYSERR;
2011   }
2012   path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
2013   in = tcp_address_to_sockaddr (path,
2014                                 &in_len);
2015   
2016   sock = GNUNET_NETWORK_socket_create (in->sa_family,
2017                                        SOCK_STREAM,
2018                                        IPPROTO_TCP);
2019   if (NULL == sock)
2020   {
2021     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2022                 "socket(%d) failed: %s",
2023                 in->sa_family,
2024                 STRERROR (errno));
2025     GNUNET_free (in);
2026     return GNUNET_SYSERR;
2027   }
2028   if (GNUNET_OK !=
2029       GNUNET_NETWORK_socket_connect (sock,
2030                                      in,
2031                                      in_len))
2032   {
2033     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2034                 "connect to `%s' failed: %s",
2035                 address,
2036                 STRERROR (errno));
2037     GNUNET_NETWORK_socket_close (sock);
2038     GNUNET_free (in);
2039     return GNUNET_SYSERR;
2040   }
2041
2042   queue = GNUNET_new (struct Queue);
2043   queue->target = *peer; 
2044   queue->address = in;
2045   queue->address_len = in_len;
2046   queue->sock = sock;
2047   boot_queue (queue,
2048               GNUNET_TRANSPORT_CS_OUTBOUND);
2049   queue->read_task
2050     = GNUNET_SCHEDULER_add_read_net (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2051                                      queue->sock,
2052                                      &queue_read_kx,
2053                                      queue);
2054   if (NULL == queue)
2055   {
2056     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2057                 "Failed to setup queue to %s at `%s'\n",
2058                 GNUNET_i2s (peer),
2059                 path);
2060     GNUNET_NETWORK_socket_close (sock);
2061     return GNUNET_NO;
2062   }
2063   start_initial_kx_out (queue);
2064   return GNUNET_OK;  
2065 }
2066
2067
2068 /**
2069  * Iterator over all message queues to clean up.
2070  *
2071  * @param cls NULL
2072  * @param target unused
2073  * @param value the queue to destroy
2074  * @return #GNUNET_OK to continue to iterate
2075  */
2076 static int
2077 get_queue_delete_it (void *cls,
2078                      const struct GNUNET_PeerIdentity *target,
2079                      void *value)
2080 {
2081   struct Queue *queue = value;
2082
2083   (void) cls;
2084   (void) target;
2085   queue_destroy (queue);
2086   return GNUNET_OK;
2087 }
2088
2089
2090 /**
2091  * Shutdown the UNIX communicator.
2092  *
2093  * @param cls NULL (always)
2094  */
2095 static void
2096 do_shutdown (void *cls)
2097 {
2098   if (NULL != nat)
2099   {
2100      GNUNET_NAT_unregister (nat);
2101      nat = NULL;
2102   }
2103   if (NULL != listen_task)
2104   {
2105     GNUNET_SCHEDULER_cancel (listen_task);
2106     listen_task = NULL;
2107   }
2108   if (NULL != listen_sock)
2109   {
2110     GNUNET_break (GNUNET_OK ==
2111                   GNUNET_NETWORK_socket_close (listen_sock));
2112     listen_sock = NULL;
2113   }
2114   GNUNET_CONTAINER_multipeermap_iterate (queue_map,
2115                                          &get_queue_delete_it,
2116                                          NULL);
2117   GNUNET_CONTAINER_multipeermap_destroy (queue_map);
2118   if (NULL != ch)
2119   {
2120     GNUNET_TRANSPORT_communicator_disconnect (ch);
2121     ch = NULL;
2122   }
2123   if (NULL != stats)
2124   {
2125     GNUNET_STATISTICS_destroy (stats,
2126                                GNUNET_NO);
2127     stats = NULL;
2128   }
2129   if (NULL != my_private_key)
2130   {
2131     GNUNET_free (my_private_key);
2132     my_private_key = NULL;
2133   }
2134   if (NULL != is)
2135   {
2136      GNUNET_NT_scanner_done (is);
2137      is = NULL;
2138   }
2139 }
2140
2141
2142 /**
2143  * Function called when the transport service has received an
2144  * acknowledgement for this communicator (!) via a different return
2145  * path.
2146  *
2147  * Not applicable for TCP.
2148  *
2149  * @param cls closure
2150  * @param sender which peer sent the notification
2151  * @param msg payload
2152  */
2153 static void
2154 enc_notify_cb (void *cls,
2155                const struct GNUNET_PeerIdentity *sender,
2156                const struct GNUNET_MessageHeader *msg)
2157 {
2158   (void) cls;
2159   (void) sender;
2160   (void) msg;
2161   GNUNET_break_op (0);
2162 }
2163
2164
2165 /**
2166  * Signature of the callback passed to #GNUNET_NAT_register() for
2167  * a function to call whenever our set of 'valid' addresses changes.
2168  *
2169  * @param cls closure
2170  * @param app_ctx[in,out] location where the app can store stuff
2171  *                  on add and retrieve it on remove
2172  * @param add_remove #GNUNET_YES to add a new public IP address, 
2173  *                   #GNUNET_NO to remove a previous (now invalid) one
2174  * @param ac address class the address belongs to
2175  * @param addr either the previous or the new public IP address
2176  * @param addrlen actual length of the @a addr
2177  */
2178 static void
2179 nat_address_cb (void *cls,
2180                 void **app_ctx,
2181                 int add_remove,
2182                 enum GNUNET_NAT_AddressClass ac,
2183                 const struct sockaddr *addr,
2184                 socklen_t addrlen)
2185 {
2186   char *my_addr;
2187   struct GNUNET_TRANSPORT_AddressIdentifier *ai;
2188
2189   if (GNUNET_YES == add_remove)
2190   {
2191     enum GNUNET_NetworkType nt;
2192
2193     GNUNET_asprintf (&my_addr,
2194                      "%s-%s",
2195                      COMMUNICATOR_ADDRESS_PREFIX,
2196                      GNUNET_a2s (addr,
2197                                  addrlen));
2198     nt = GNUNET_NT_scanner_get_type (is,
2199                                      addr,
2200                                      addrlen); 
2201     ai = GNUNET_TRANSPORT_communicator_address_add (ch,
2202                                                     my_addr,
2203                                                     nt,
2204                                                     GNUNET_TIME_UNIT_FOREVER_REL);
2205     GNUNET_free (my_addr);
2206     *app_ctx = ai;
2207   }
2208   else
2209   {
2210     ai = *app_ctx;
2211     GNUNET_TRANSPORT_communicator_address_remove (ai);
2212     *app_ctx = NULL;
2213   }
2214 }
2215
2216
2217 /**
2218  * Setup communicator and launch network interactions.
2219  *
2220  * @param cls NULL (always)
2221  * @param args remaining command-line arguments
2222  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2223  * @param c configuration
2224  */
2225 static void
2226 run (void *cls,
2227      char *const *args,
2228      const char *cfgfile,
2229      const struct GNUNET_CONFIGURATION_Handle *c)
2230 {
2231   char *bindto;
2232   struct sockaddr *in;
2233   socklen_t in_len;
2234   struct sockaddr_storage in_sto;
2235   socklen_t sto_len;
2236   
2237   (void) cls;
2238   cfg = c;
2239   if (GNUNET_OK !=
2240       GNUNET_CONFIGURATION_get_value_filename (cfg,
2241                                                COMMUNICATOR_CONFIG_SECTION,
2242                                                "BINDTO",
2243                                                &bindto))
2244   {
2245     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2246                                COMMUNICATOR_CONFIG_SECTION,
2247                                "BINDTO");
2248     return;
2249   }
2250   if (GNUNET_OK !=
2251       GNUNET_CONFIGURATION_get_value_number (cfg,
2252                                              COMMUNICATOR_CONFIG_SECTION,
2253                                              "MAX_QUEUE_LENGTH",
2254                                              &max_queue_length))
2255     max_queue_length = DEFAULT_MAX_QUEUE_LENGTH;
2256
2257   in = tcp_address_to_sockaddr (bindto,
2258                                 &in_len);
2259   if (NULL == in)
2260   {
2261     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2262                 "Failed to setup TCP socket address with path `%s'\n",
2263                 bindto);
2264     GNUNET_free (bindto);
2265     return;
2266   }
2267   listen_sock = GNUNET_NETWORK_socket_create (in->sa_family,
2268                                               SOCK_STREAM,
2269                                               IPPROTO_TCP);
2270   if (NULL == listen_sock)
2271   {
2272     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
2273                          "socket");
2274     GNUNET_free (in);
2275     GNUNET_free (bindto);
2276     return;
2277   }
2278   if (GNUNET_OK !=
2279       GNUNET_NETWORK_socket_bind (listen_sock,
2280                                   in,
2281                                   in_len))
2282   {
2283     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
2284                               "bind",
2285                               bindto);
2286     GNUNET_NETWORK_socket_close (listen_sock);
2287     listen_sock = NULL;
2288     GNUNET_free (in);
2289     GNUNET_free (bindto);
2290     return;
2291   }
2292   /* We might have bound to port 0, allowing the OS to figure it out;
2293      thus, get the real IN-address from the socket */
2294   sto_len = sizeof (in_sto);
2295   if (0 != getsockname (GNUNET_NETWORK_get_fd (listen_sock),
2296                         (struct sockaddr *) &in_sto,
2297                         &sto_len))
2298   {
2299     memcpy (&in_sto,
2300             in,
2301             in_len);
2302     sto_len = in_len;
2303   }
2304   GNUNET_free (in);
2305   GNUNET_free (bindto);
2306   in = (struct sockaddr *) &in_sto;
2307   in_len = sto_len;
2308   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2309               "Bound to `%s'\n",
2310               GNUNET_a2s ((const struct sockaddr *) &in_sto,
2311                           sto_len));
2312   stats = GNUNET_STATISTICS_create ("C-TCP",
2313                                     cfg);
2314   GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
2315                                  NULL);
2316   is = GNUNET_NT_scanner_init ();
2317   my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
2318   if (NULL == my_private_key)
2319   {
2320     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2321                 _("Transport service is lacking key configuration settings. Exiting.\n"));
2322     GNUNET_SCHEDULER_shutdown ();
2323     return;
2324   }
2325   GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
2326                                       &my_identity.public_key);
2327   /* start listening */
2328   listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2329                                                listen_sock,
2330                                                &listen_cb,
2331                                                NULL);
2332   queue_map = GNUNET_CONTAINER_multipeermap_create (10,
2333                                                     GNUNET_NO);
2334   ch = GNUNET_TRANSPORT_communicator_connect (cfg,
2335                                               COMMUNICATOR_CONFIG_SECTION,
2336                                               COMMUNICATOR_ADDRESS_PREFIX,
2337                                               GNUNET_TRANSPORT_CC_RELIABLE,
2338                                               &mq_init,
2339                                               NULL,
2340                                               &enc_notify_cb,
2341                                               NULL);
2342   if (NULL == ch)
2343   {
2344     GNUNET_break (0);
2345     GNUNET_SCHEDULER_shutdown ();
2346     return;
2347   }
2348   nat = GNUNET_NAT_register (cfg,
2349                              COMMUNICATOR_CONFIG_SECTION,
2350                              IPPROTO_TCP,
2351                              1 /* one address */,
2352                              (const struct sockaddr **) &in,
2353                              &in_len,
2354                              &nat_address_cb,
2355                              NULL /* FIXME: support reversal: #5529 */,
2356                              NULL /* closure */);
2357 }
2358
2359
2360 /**
2361  * The main function for the UNIX communicator.
2362  *
2363  * @param argc number of arguments from the command line
2364  * @param argv command line arguments
2365  * @return 0 ok, 1 on error
2366  */
2367 int
2368 main (int argc,
2369       char *const *argv)
2370 {
2371   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2372     GNUNET_GETOPT_OPTION_END
2373   };
2374   int ret;
2375
2376   if (GNUNET_OK !=
2377       GNUNET_STRINGS_get_utf8_args (argc, argv,
2378                                     &argc, &argv))
2379     return 2;
2380
2381   ret =
2382       (GNUNET_OK ==
2383        GNUNET_PROGRAM_run (argc, argv,
2384                            "gnunet-communicator-tcp",
2385                            _("GNUnet TCP communicator"),
2386                            options,
2387                            &run,
2388                            NULL)) ? 0 : 1;
2389   GNUNET_free ((void*) argv);
2390   return ret;
2391 }
2392
2393
2394 /* end of gnunet-communicator-tcp.c */