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