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