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