tolerate additional IPv4 address now available for gnunet.org
[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 after #inject_key() placed the rekey message into the
433    * plaintext buffer. Once the plaintext buffer is drained, this
434    * means we must switch to the new key material.
435    */
436   int rekey_state;
437
438   /**
439    * #GNUNET_YES if we just rekeyed and must thus possibly
440    * re-decrypt ciphertext.
441    */
442   int rekeyed;
443 };
444
445
446 /**
447  * Handle for an incoming connection where we do not yet have enough
448  * information to setup a full queue.
449  */
450 struct ProtoQueue
451 {
452
453   /**
454    * Kept in a DLL.
455    */
456   struct ProtoQueue *next;
457
458   /**
459    * Kept in a DLL.
460    */
461   struct ProtoQueue *prev;
462
463   /**
464    * socket that we transmit all data with on this queue
465    */
466   struct GNUNET_NETWORK_Handle *sock;
467
468   /**
469    * ID of read task for this connection.
470    */
471   struct GNUNET_SCHEDULER_Task *read_task;
472
473   /**
474    * Address of the other peer.
475    */
476   struct sockaddr *address;
477
478   /**
479    * Length of the address.
480    */
481   socklen_t address_len;
482
483   /**
484    * Timeout for this protoqueue.
485    */
486   struct GNUNET_TIME_Absolute timeout;
487
488   /**
489    * Buffer for reading all the information we need to upgrade from
490    * protoqueue to queue.
491    */
492   char ibuf[INITIAL_KX_SIZE];
493
494   /**
495    * Current offset for reading into @e ibuf.
496    */
497   size_t ibuf_off;
498 };
499
500
501 /**
502  * ID of listen task
503  */
504 static struct GNUNET_SCHEDULER_Task *listen_task;
505
506 /**
507  * Maximum queue length before we stop reading towards the transport service.
508  */
509 static unsigned long long max_queue_length;
510
511 /**
512  * For logging statistics.
513  */
514 static struct GNUNET_STATISTICS_Handle *stats;
515
516 /**
517  * Our environment.
518  */
519 static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
520
521 /**
522  * Queues (map from peer identity to `struct Queue`)
523  */
524 static struct GNUNET_CONTAINER_MultiPeerMap *queue_map;
525
526 /**
527  * Listen socket.
528  */
529 static struct GNUNET_NETWORK_Handle *listen_sock;
530
531 /**
532  * Our public key.
533  */
534 static struct GNUNET_PeerIdentity my_identity;
535
536 /**
537  * Our private key.
538  */
539 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
540
541 /**
542  * Our configuration.
543  */
544 static const struct GNUNET_CONFIGURATION_Handle *cfg;
545
546 /**
547  * Network scanner to determine network types.
548  */
549 static struct GNUNET_NT_InterfaceScanner *is;
550
551 /**
552  * Connection to NAT service.
553  */
554 static struct GNUNET_NAT_Handle *nat;
555
556 /**
557  * Protoqueues DLL head.
558  */
559 static struct ProtoQueue *proto_head;
560
561 /**
562  * Protoqueues DLL tail.
563  */
564 static struct ProtoQueue *proto_tail;
565
566
567 /**
568  * We have been notified that our listen socket has something to
569  * read. Do the read and reschedule this function to be called again
570  * once more is available.
571  *
572  * @param cls NULL
573  */
574 static void
575 listen_cb (void *cls);
576
577
578 /**
579  * Functions with this signature are called whenever we need
580  * to close a queue due to a disconnect or failure to
581  * establish a connection.
582  *
583  * @param queue queue to close down
584  */
585 static void
586 queue_destroy (struct Queue *queue)
587 {
588   struct GNUNET_MQ_Handle *mq;
589
590   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
591               "Disconnecting queue for peer `%s'\n",
592               GNUNET_i2s (&queue->target));
593   if (NULL != (mq = queue->mq))
594   {
595     queue->mq = NULL;
596     GNUNET_MQ_destroy (mq);
597   }
598   if (NULL != queue->qh)
599   {
600     GNUNET_TRANSPORT_communicator_mq_del (queue->qh);
601     queue->qh = NULL;
602   }
603   GNUNET_assert (
604     GNUNET_YES ==
605     GNUNET_CONTAINER_multipeermap_remove (queue_map, &queue->target, queue));
606   GNUNET_STATISTICS_set (stats,
607                          "# queues active",
608                          GNUNET_CONTAINER_multipeermap_size (queue_map),
609                          GNUNET_NO);
610   if (NULL != queue->read_task)
611   {
612     GNUNET_SCHEDULER_cancel (queue->read_task);
613     queue->read_task = NULL;
614   }
615   if (NULL != queue->write_task)
616   {
617     GNUNET_SCHEDULER_cancel (queue->write_task);
618     queue->write_task = NULL;
619   }
620   GNUNET_NETWORK_socket_close (queue->sock);
621   gcry_cipher_close (queue->in_cipher);
622   gcry_cipher_close (queue->out_cipher);
623   GNUNET_free (queue->address);
624   if (0 != queue->backpressure)
625     queue->destroyed = GNUNET_YES;
626   else
627     GNUNET_free (queue);
628   if (NULL == listen_task)
629     listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
630                                                  listen_sock,
631                                                  &listen_cb,
632                                                  NULL);
633 }
634
635
636 /**
637  * Compute @a mac over @a buf, and ratched the @a hmac_secret.
638  *
639  * @param[in,out] hmac_secret secret for HMAC calculation
640  * @param buf buffer to MAC
641  * @param buf_size number of bytes in @a buf
642  * @param smac[out] where to write the HMAC
643  */
644 static void
645 calculate_hmac (struct GNUNET_HashCode *hmac_secret,
646                 const void *buf,
647                 size_t buf_size,
648                 struct GNUNET_ShortHashCode *smac)
649 {
650   struct GNUNET_HashCode mac;
651
652   GNUNET_CRYPTO_hmac_raw (hmac_secret,
653                           sizeof (struct GNUNET_HashCode),
654                           buf,
655                           buf_size,
656                           &mac);
657   /* truncate to `struct GNUNET_ShortHashCode` */
658   memcpy (smac, &mac, sizeof (struct GNUNET_ShortHashCode));
659   /* ratchet hmac key */
660   GNUNET_CRYPTO_hash (hmac_secret,
661                       sizeof (struct GNUNET_HashCode),
662                       hmac_secret);
663 }
664
665
666 /**
667  * Append a 'finish' message to the outgoing transmission. Once the
668  * finish has been transmitted, destroy the queue.
669  *
670  * @param queue queue to shut down nicely
671  */
672 static void
673 queue_finish (struct Queue *queue)
674 {
675   struct TCPFinish fin;
676
677   memset (&fin, 0, sizeof (fin));
678   fin.header.size = htons (sizeof (fin));
679   fin.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH);
680   calculate_hmac (&queue->out_hmac, &fin, sizeof (fin), &fin.hmac);
681   /* if there is any message left in pwrite_buf, we
682      overwrite it (possibly dropping the last message
683      from CORE hard here) */
684   memcpy (queue->pwrite_buf, &fin, sizeof (fin));
685   queue->pwrite_off = sizeof (fin);
686   /* This flag will ensure that #queue_write() no longer
687      notifies CORE about the possibility of sending
688      more data, and that #queue_write() will call
689      #queue_destroy() once the @c fin was fully written. */
690   queue->finishing = GNUNET_YES;
691 }
692
693
694 /**
695  * Increment queue timeout due to activity.  We do not immediately
696  * notify the monitor here as that might generate excessive
697  * signalling.
698  *
699  * @param queue queue for which the timeout should be rescheduled
700  */
701 static void
702 reschedule_queue_timeout (struct Queue *queue)
703 {
704   queue->timeout =
705     GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
706 }
707
708
709 /**
710  * Queue read task. If we hit the timeout, disconnect it
711  *
712  * @param cls the `struct Queue *` to disconnect
713  */
714 static void
715 queue_read (void *cls);
716
717
718 /**
719  * Core tells us it is done processing a message that transport
720  * received on a queue with status @a success.
721  *
722  * @param cls a `struct Queue *` where the message originally came from
723  * @param success #GNUNET_OK on success
724  */
725 static void
726 core_read_finished_cb (void *cls, int success)
727 {
728   struct Queue *queue = cls;
729
730   if (GNUNET_OK != success)
731     GNUNET_STATISTICS_update (stats,
732                               "# messages lost in communicator API towards CORE",
733                               1,
734                               GNUNET_NO);
735   queue->backpressure--;
736   /* handle deferred queue destruction */
737   if ((queue->destroyed) && (0 == queue->backpressure))
738   {
739     GNUNET_free (queue);
740     return;
741   }
742   reschedule_queue_timeout (queue);
743   /* possibly unchoke reading, now that CORE made progress */
744   if (NULL == queue->read_task)
745     queue->read_task =
746       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining (
747                                        queue->timeout),
748                                      queue->sock,
749                                      &queue_read,
750                                      queue);
751 }
752
753
754 /**
755  * We received @a plaintext_len bytes of @a plaintext on @a queue.
756  * Pass it on to CORE.  If transmission is actually happening,
757  * increase backpressure counter.
758  *
759  * @param queue the queue that received the plaintext
760  * @param plaintext the plaintext that was received
761  * @param plaintext_len number of bytes of plaintext received
762  */
763 static void
764 pass_plaintext_to_core (struct Queue *queue,
765                         const void *plaintext,
766                         size_t plaintext_len)
767 {
768   const struct GNUNET_MessageHeader *hdr = plaintext;
769   int ret;
770
771   if (ntohs (hdr->size) != plaintext_len)
772   {
773     /* NOTE: If we ever allow multiple CORE messages in one
774        BOX, this will have to change! */
775     GNUNET_break (0);
776     return;
777   }
778   ret = GNUNET_TRANSPORT_communicator_receive (ch,
779                                                &queue->target,
780                                                hdr,
781                                                ADDRESS_VALIDITY_PERIOD,
782                                                &core_read_finished_cb,
783                                                queue);
784   if (GNUNET_OK == ret)
785     queue->backpressure++;
786   GNUNET_break (GNUNET_NO != ret); /* backpressure not working!? */
787   if (GNUNET_SYSERR == ret)
788     GNUNET_STATISTICS_update (stats,
789                               "# bytes lost due to CORE not running",
790                               plaintext_len,
791                               GNUNET_NO);
792 }
793
794
795 /**
796  * Setup @a cipher based on shared secret @a dh and decrypting
797  * peer @a pid.
798  *
799  * @param dh shared secret
800  * @param pid decrypting peer's identity
801  * @param cipher[out] cipher to initialize
802  * @param hmac_key[out] HMAC key to initialize
803  */
804 static void
805 setup_cipher (const struct GNUNET_HashCode *dh,
806               const struct GNUNET_PeerIdentity *pid,
807               gcry_cipher_hd_t *cipher,
808               struct GNUNET_HashCode *hmac_key)
809 {
810   char key[256 / 8];
811   char ctr[128 / 8];
812
813   gcry_cipher_open (cipher,
814                     GCRY_CIPHER_AES256 /* low level: go for speed */,
815                     GCRY_CIPHER_MODE_CTR,
816                     0 /* flags */);
817   GNUNET_assert (GNUNET_YES == GNUNET_CRYPTO_kdf (key,
818                                                   sizeof (key),
819                                                   "TCP-key",
820                                                   strlen ("TCP-key"),
821                                                   dh,
822                                                   sizeof (*dh),
823                                                   pid,
824                                                   sizeof (*pid),
825                                                   NULL,
826                                                   0));
827   gcry_cipher_setkey (*cipher, key, sizeof (key));
828   GNUNET_assert (GNUNET_YES == GNUNET_CRYPTO_kdf (ctr,
829                                                   sizeof (ctr),
830                                                   "TCP-ctr",
831                                                   strlen ("TCP-ctr"),
832                                                   dh,
833                                                   sizeof (*dh),
834                                                   pid,
835                                                   sizeof (*pid),
836                                                   NULL,
837                                                   0));
838   gcry_cipher_setctr (*cipher, ctr, sizeof (ctr));
839   GNUNET_assert (GNUNET_YES ==
840                  GNUNET_CRYPTO_kdf (hmac_key,
841                                     sizeof (struct GNUNET_HashCode),
842                                     "TCP-hmac",
843                                     strlen ("TCP-hmac"),
844                                     dh,
845                                     sizeof (*dh),
846                                     pid,
847                                     sizeof (*pid),
848                                     NULL,
849                                     0));
850 }
851
852
853 /**
854  * Setup cipher of @a queue for decryption.
855  *
856  * @param ephemeral ephemeral key we received from the other peer
857  * @param queue[in,out] queue to initialize decryption cipher for
858  */
859 static void
860 setup_in_cipher (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
861                  struct Queue *queue)
862 {
863   struct GNUNET_HashCode dh;
864
865   GNUNET_CRYPTO_eddsa_ecdh (my_private_key, ephemeral, &dh);
866   setup_cipher (&dh, &my_identity, &queue->in_cipher, &queue->in_hmac);
867 }
868
869
870 /**
871  * Handle @a rekey message on @a queue. The message was already
872  * HMAC'ed, but we should additionally still check the signature.
873  * Then we need to stop the old cipher and start afresh.
874  *
875  * @param queue the queue @a rekey was received on
876  * @param rekey the rekey message
877  */
878 static void
879 do_rekey (struct Queue *queue, const struct TCPRekey *rekey)
880 {
881   struct TcpHandshakeSignature thp;
882
883   thp.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY);
884   thp.purpose.size = htonl (sizeof (thp));
885   thp.sender = queue->target;
886   thp.receiver = my_identity;
887   thp.ephemeral = rekey->ephemeral;
888   thp.monotonic_time = rekey->monotonic_time;
889   if (GNUNET_OK !=
890       GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY,
891                                   &thp.purpose,
892                                   &rekey->sender_sig,
893                                   &queue->target.public_key))
894   {
895     GNUNET_break (0);
896     queue_finish (queue);
897     return;
898   }
899   gcry_cipher_close (queue->in_cipher);
900   queue->rekeyed = GNUNET_YES;
901   setup_in_cipher (&rekey->ephemeral, queue);
902 }
903
904
905 /**
906  * Test if we have received a full message in plaintext.
907  * If so, handle it.
908  *
909  * @param queue queue to process inbound plaintext for
910  * @return number of bytes of plaintext handled, 0 for none
911  */
912 static size_t
913 try_handle_plaintext (struct Queue *queue)
914 {
915   const struct GNUNET_MessageHeader *hdr =
916     (const struct GNUNET_MessageHeader *) queue->pread_buf;
917   const struct TCPBox *box = (const struct TCPBox *) queue->pread_buf;
918   const struct TCPRekey *rekey = (const struct TCPRekey *) queue->pread_buf;
919   const struct TCPFinish *fin = (const struct TCPFinish *) queue->pread_buf;
920   struct TCPRekey rekeyz;
921   struct TCPFinish finz;
922   struct GNUNET_ShortHashCode tmac;
923   uint16_t type;
924   size_t size = 0; /* make compiler happy */
925
926   if (sizeof (*hdr) > queue->pread_off)
927     return 0; /* not even a header */
928   type = ntohs (hdr->type);
929   switch (type)
930   {
931   case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX:
932     /* Special case: header size excludes box itself! */
933     if (ntohs (hdr->size) + sizeof (struct TCPBox) > queue->pread_off)
934       return 0;
935     calculate_hmac (&queue->in_hmac, &box[1], ntohs (hdr->size), &tmac);
936     if (0 != memcmp (&tmac, &box->hmac, sizeof (tmac)))
937     {
938       GNUNET_break_op (0);
939       queue_finish (queue);
940       return 0;
941     }
942     pass_plaintext_to_core (queue, (const void *) &box[1], ntohs (hdr->size));
943     size = ntohs (hdr->size) + sizeof (*box);
944     break;
945   case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY:
946     if (sizeof (*rekey) > queue->pread_off)
947       return 0;
948     if (ntohs (hdr->size) != sizeof (*rekey))
949     {
950       GNUNET_break_op (0);
951       queue_finish (queue);
952       return 0;
953     }
954     rekeyz = *rekey;
955     memset (&rekeyz.hmac, 0, sizeof (rekeyz.hmac));
956     calculate_hmac (&queue->in_hmac, &rekeyz, sizeof (rekeyz), &tmac);
957     if (0 != memcmp (&tmac, &box->hmac, sizeof (tmac)))
958     {
959       GNUNET_break_op (0);
960       queue_finish (queue);
961       return 0;
962     }
963     do_rekey (queue, rekey);
964     size = ntohs (hdr->size);
965     break;
966   case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH:
967     if (sizeof (*fin) > queue->pread_off)
968       return 0;
969     if (ntohs (hdr->size) != sizeof (*fin))
970     {
971       GNUNET_break_op (0);
972       queue_finish (queue);
973       return 0;
974     }
975     finz = *fin;
976     memset (&finz.hmac, 0, sizeof (finz.hmac));
977     calculate_hmac (&queue->in_hmac, &rekeyz, sizeof (rekeyz), &tmac);
978     if (0 != memcmp (&tmac, &fin->hmac, sizeof (tmac)))
979     {
980       GNUNET_break_op (0);
981       queue_finish (queue);
982       return 0;
983     }
984     /* handle FINISH by destroying queue */
985     queue_destroy (queue);
986     break;
987   default:
988     GNUNET_break_op (0);
989     queue_finish (queue);
990     return 0;
991   }
992   GNUNET_assert (0 != size);
993   return size;
994 }
995
996
997 /**
998  * Queue read task. If we hit the timeout, disconnect it
999  *
1000  * @param cls the `struct Queue *` to disconnect
1001  */
1002 static void
1003 queue_read (void *cls)
1004 {
1005   struct Queue *queue = cls;
1006   struct GNUNET_TIME_Relative left;
1007   ssize_t rcvd;
1008
1009   queue->read_task = NULL;
1010   rcvd = GNUNET_NETWORK_socket_recv (queue->sock,
1011                                      &queue->cread_buf[queue->cread_off],
1012                                      BUF_SIZE - queue->cread_off);
1013   if (-1 == rcvd)
1014   {
1015     if ((EAGAIN != errno) && (EINTR != errno))
1016     {
1017       GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "recv");
1018       queue_finish (queue);
1019       return;
1020     }
1021     /* try again */
1022     queue->read_task =
1023       GNUNET_SCHEDULER_add_read_net (left, queue->sock, &queue_read, queue);
1024     return;
1025   }
1026   if (0 != rcvd)
1027     reschedule_queue_timeout (queue);
1028   queue->cread_off += rcvd;
1029   while ((queue->pread_off < sizeof (queue->pread_buf)) &&
1030          (queue->cread_off > 0))
1031   {
1032     size_t max = GNUNET_MIN (sizeof (queue->pread_buf) - queue->pread_off,
1033                              queue->cread_off);
1034     size_t done;
1035     size_t total;
1036
1037     GNUNET_assert (0 ==
1038                    gcry_cipher_decrypt (queue->in_cipher,
1039                                         &queue->pread_buf[queue->pread_off],
1040                                         max,
1041                                         queue->cread_buf,
1042                                         max));
1043     queue->pread_off += max;
1044     total = 0;
1045     while ((GNUNET_NO == queue->rekeyed) &&
1046            (0 != (done = try_handle_plaintext (queue))))
1047     {
1048       /* 'done' bytes of plaintext were used, shift buffer */
1049       GNUNET_assert (done <= queue->pread_off);
1050       /* NOTE: this memmove() could possibly sometimes be
1051    avoided if we pass 'total' into try_handle_plaintext()
1052    and use it at an offset into the buffer there! */
1053       memmove (queue->pread_buf,
1054                &queue->pread_buf[done],
1055                queue->pread_off - done);
1056       queue->pread_off -= done;
1057       total += done;
1058     }
1059     /* when we encounter a rekey message, the decryption above uses the
1060        wrong key for everything after the rekey; in that case, we have
1061        to re-do the decryption at 'total' instead of at 'max'. If there
1062        is no rekey and the last message is incomplete (max > total),
1063        it is safe to keep the decryption so we shift by 'max' */
1064     if (GNUNET_YES == queue->rekeyed)
1065     {
1066       max = total;
1067       queue->rekeyed = GNUNET_NO;
1068     }
1069     memmove (queue->cread_buf, &queue->cread_buf[max], queue->cread_off - max);
1070     queue->cread_off -= max;
1071   }
1072
1073   if (BUF_SIZE == queue->cread_off)
1074     return; /* buffer full, suspend reading */
1075   left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
1076   if (0 != left.rel_value_us)
1077   {
1078     if (max_queue_length < queue->backpressure)
1079     {
1080       /* continue reading */
1081       queue->read_task =
1082         GNUNET_SCHEDULER_add_read_net (left, queue->sock, &queue_read, queue);
1083     }
1084     return;
1085   }
1086   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1087               "Queue %p was idle for %s, disconnecting\n",
1088               queue,
1089               GNUNET_STRINGS_relative_time_to_string (
1090                 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1091                 GNUNET_YES));
1092   queue_finish (queue);
1093 }
1094
1095
1096 /**
1097  * Convert TCP bind specification to a `struct sockaddr *`
1098  *
1099  * @param bindto bind specification to convert
1100  * @param[out] sock_len set to the length of the address
1101  * @return converted bindto specification
1102  */
1103 static struct sockaddr *
1104 tcp_address_to_sockaddr (const char *bindto, socklen_t *sock_len)
1105 {
1106   struct sockaddr *in;
1107   unsigned int port;
1108   char dummy[2];
1109   char *colon;
1110   char *cp;
1111
1112   if (1 == SSCANF (bindto, "%u%1s", &port, dummy))
1113   {
1114     /* interpreting value as just a PORT number */
1115     if (port > UINT16_MAX)
1116     {
1117       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1118                   "BINDTO specification `%s' invalid: value too large for port\n",
1119                   bindto);
1120       return NULL;
1121     }
1122     if ((GNUNET_NO == GNUNET_NETWORK_test_pf (PF_INET6)) ||
1123         (GNUNET_YES ==
1124          GNUNET_CONFIGURATION_get_value_yesno (cfg,
1125                                                COMMUNICATOR_CONFIG_SECTION,
1126                                                "DISABLE_V6")))
1127     {
1128       struct sockaddr_in *i4;
1129
1130       i4 = GNUNET_malloc (sizeof (struct sockaddr_in));
1131       i4->sin_family = AF_INET;
1132       i4->sin_port = htons ((uint16_t) port);
1133       *sock_len = sizeof (struct sockaddr_in);
1134       in = (struct sockaddr *) i4;
1135     }
1136     else
1137     {
1138       struct sockaddr_in6 *i6;
1139
1140       i6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
1141       i6->sin6_family = AF_INET6;
1142       i6->sin6_port = htons ((uint16_t) port);
1143       *sock_len = sizeof (struct sockaddr_in6);
1144       in = (struct sockaddr *) i6;
1145     }
1146     return in;
1147   }
1148   cp = GNUNET_strdup (bindto);
1149   colon = strrchr (cp, ':');
1150   if (NULL != colon)
1151   {
1152     /* interpet value after colon as port */
1153     *colon = '\0';
1154     colon++;
1155     if (1 == SSCANF (colon, "%u%1s", &port, dummy))
1156     {
1157       /* interpreting value as just a PORT number */
1158       if (port > UINT16_MAX)
1159       {
1160         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1161                     "BINDTO specification `%s' invalid: value too large for port\n",
1162                     bindto);
1163         GNUNET_free (cp);
1164         return NULL;
1165       }
1166     }
1167     else
1168     {
1169       GNUNET_log (
1170         GNUNET_ERROR_TYPE_ERROR,
1171         "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1172         bindto);
1173       GNUNET_free (cp);
1174       return NULL;
1175     }
1176   }
1177   else
1178   {
1179     /* interpret missing port as 0, aka pick any free one */
1180     port = 0;
1181   }
1182   {
1183     /* try IPv4 */
1184     struct sockaddr_in v4;
1185
1186     if (1 == inet_pton (AF_INET, cp, &v4))
1187     {
1188       v4.sin_port = htons ((uint16_t) port);
1189       in = GNUNET_memdup (&v4, sizeof (v4));
1190       *sock_len = sizeof (v4);
1191       GNUNET_free (cp);
1192       return in;
1193     }
1194   }
1195   {
1196     /* try IPv6 */
1197     struct sockaddr_in6 v6;
1198     const char *start;
1199
1200     start = cp;
1201     if (('[' == *cp) && (']' == cp[strlen (cp) - 1]))
1202     {
1203       start++; /* skip over '[' */
1204       cp[strlen (cp) - 1] = '\0'; /* eat ']' */
1205     }
1206     if (1 == inet_pton (AF_INET6, start, &v6))
1207     {
1208       v6.sin6_port = htons ((uint16_t) port);
1209       in = GNUNET_memdup (&v6, sizeof (v6));
1210       *sock_len = sizeof (v6);
1211       GNUNET_free (cp);
1212       return in;
1213     }
1214   }
1215   /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1216   GNUNET_free (cp);
1217   return NULL;
1218 }
1219
1220
1221 /**
1222  * Setup cipher for outgoing data stream based on target and
1223  * our ephemeral private key.
1224  *
1225  * @param queue queue to setup outgoing (encryption) cipher for
1226  */
1227 static void
1228 setup_out_cipher (struct Queue *queue)
1229 {
1230   struct GNUNET_HashCode dh;
1231
1232   GNUNET_CRYPTO_ecdh_eddsa (&queue->ephemeral, &queue->target.public_key, &dh);
1233   /* we don't need the private key anymore, drop it! */
1234   memset (&queue->ephemeral, 0, sizeof (queue->ephemeral));
1235   setup_cipher (&dh, &queue->target, &queue->out_cipher, &queue->out_hmac);
1236   queue->rekey_time = GNUNET_TIME_relative_to_absolute (REKEY_TIME_INTERVAL);
1237   queue->rekey_left_bytes =
1238     GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, REKEY_MAX_BYTES);
1239 }
1240
1241
1242 /**
1243  * Inject a `struct TCPRekey` message into the queue's plaintext
1244  * buffer.
1245  *
1246  * @param queue queue to perform rekeying on
1247  */
1248 static void
1249 inject_rekey (struct Queue *queue)
1250 {
1251   struct TCPRekey rekey;
1252   struct TcpHandshakeSignature thp;
1253
1254   GNUNET_assert (0 == queue->pwrite_off);
1255   memset (&rekey, 0, sizeof (rekey));
1256   GNUNET_assert (GNUNET_OK ==
1257                  GNUNET_CRYPTO_ecdhe_key_create2 (&queue->ephemeral));
1258   rekey.header.type = ntohs (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY);
1259   rekey.header.size = ntohs (sizeof (rekey));
1260   GNUNET_CRYPTO_ecdhe_key_get_public (&queue->ephemeral, &rekey.ephemeral);
1261   rekey.monotonic_time =
1262     GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1263   thp.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY);
1264   thp.purpose.size = htonl (sizeof (thp));
1265   thp.sender = my_identity;
1266   thp.receiver = queue->target;
1267   thp.ephemeral = rekey.ephemeral;
1268   thp.monotonic_time = rekey.monotonic_time;
1269   GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_private_key,
1270                                                         &thp.purpose,
1271                                                         &rekey.sender_sig));
1272   calculate_hmac (&queue->out_hmac, &rekey, sizeof (rekey), &rekey.hmac);
1273   memcpy (queue->pwrite_buf, &rekey, sizeof (rekey));
1274   queue->rekey_state = GNUNET_YES;
1275 }
1276
1277
1278 /**
1279  * We encrypted the rekey message, now update actually swap the key
1280  * material and update the key freshness parameters of @a queue.
1281  */
1282 static void
1283 switch_key (struct Queue *queue)
1284 {
1285   queue->rekey_state = GNUNET_NO;
1286   gcry_cipher_close (queue->out_cipher);
1287   setup_out_cipher (queue);
1288 }
1289
1290
1291 /**
1292  * We have been notified that our socket is ready to write.
1293  * Then reschedule this function to be called again once more is available.
1294  *
1295  * @param cls a `struct Queue`
1296  */
1297 static void
1298 queue_write (void *cls)
1299 {
1300   struct Queue *queue = cls;
1301   ssize_t sent;
1302
1303   queue->write_task = NULL;
1304   sent = GNUNET_NETWORK_socket_send (queue->sock,
1305                                      queue->cwrite_buf,
1306                                      queue->cwrite_off);
1307   if ((-1 == sent) && (EAGAIN != errno) && (EINTR != errno))
1308   {
1309     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "send");
1310     queue_destroy (queue);
1311     return;
1312   }
1313   if (sent > 0)
1314   {
1315     size_t usent = (size_t) sent;
1316
1317     memmove (queue->cwrite_buf,
1318              &queue->cwrite_buf[usent],
1319              queue->cwrite_off - usent);
1320     reschedule_queue_timeout (queue);
1321   }
1322   /* can we encrypt more? (always encrypt full messages, needed
1323      such that #mq_cancel() can work!) */
1324   if (queue->cwrite_off + queue->pwrite_off <= BUF_SIZE)
1325   {
1326     GNUNET_assert (0 ==
1327                    gcry_cipher_encrypt (queue->out_cipher,
1328                                         &queue->cwrite_buf[queue->cwrite_off],
1329                                         queue->pwrite_off,
1330                                         queue->pwrite_buf,
1331                                         queue->pwrite_off));
1332     if (queue->rekey_left_bytes > queue->pwrite_off)
1333       queue->rekey_left_bytes -= queue->pwrite_off;
1334     else
1335       queue->rekey_left_bytes = 0;
1336     queue->cwrite_off += queue->pwrite_off;
1337     queue->pwrite_off = 0;
1338   }
1339   if ((GNUNET_YES == queue->rekey_state) && (0 == queue->pwrite_off))
1340     switch_key (queue);
1341   if ((0 == queue->pwrite_off) &&
1342       ((0 == queue->rekey_left_bytes) ||
1343        (0 ==
1344         GNUNET_TIME_absolute_get_remaining (queue->rekey_time).rel_value_us)))
1345     inject_rekey (queue);
1346   if ((0 == queue->pwrite_off) && (! queue->finishing) &&
1347       (queue->mq_awaits_continue))
1348   {
1349     queue->mq_awaits_continue = GNUNET_NO;
1350     GNUNET_MQ_impl_send_continue (queue->mq);
1351   }
1352   /* did we just finish writing 'finish'? */
1353   if ((0 == queue->cwrite_off) && (GNUNET_YES == queue->finishing))
1354   {
1355     queue_destroy (queue);
1356     return;
1357   }
1358   /* do we care to write more? */
1359   if (0 < queue->cwrite_off)
1360     queue->write_task =
1361       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1362                                       queue->sock,
1363                                       &queue_write,
1364                                       queue);
1365 }
1366
1367
1368 /**
1369  * Signature of functions implementing the sending functionality of a
1370  * message queue.
1371  *
1372  * @param mq the message queue
1373  * @param msg the message to send
1374  * @param impl_state our `struct Queue`
1375  */
1376 static void
1377 mq_send (struct GNUNET_MQ_Handle *mq,
1378          const struct GNUNET_MessageHeader *msg,
1379          void *impl_state)
1380 {
1381   struct Queue *queue = impl_state;
1382   uint16_t msize = ntohs (msg->size);
1383   struct TCPBox box;
1384
1385   GNUNET_assert (mq == queue->mq);
1386   if (GNUNET_YES == queue->finishing)
1387     return; /* this queue is dying, drop msg */
1388   GNUNET_assert (0 == queue->pread_off);
1389   box.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX);
1390   box.header.size = htons (msize);
1391   calculate_hmac (&queue->out_hmac, msg, msize, &box.hmac);
1392   memcpy (&queue->pread_buf[queue->pread_off], &box, sizeof (box));
1393   queue->pread_off += sizeof (box);
1394   memcpy (&queue->pread_buf[queue->pread_off], msg, msize);
1395   queue->pread_off += msize;
1396   GNUNET_assert (NULL != queue->sock);
1397   if (NULL == queue->write_task)
1398     queue->write_task =
1399       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1400                                       queue->sock,
1401                                       &queue_write,
1402                                       queue);
1403 }
1404
1405
1406 /**
1407  * Signature of functions implementing the destruction of a message
1408  * queue.  Implementations must not free @a mq, but should take care
1409  * of @a impl_state.
1410  *
1411  * @param mq the message queue to destroy
1412  * @param impl_state our `struct Queue`
1413  */
1414 static void
1415 mq_destroy (struct GNUNET_MQ_Handle *mq, void *impl_state)
1416 {
1417   struct Queue *queue = impl_state;
1418
1419   if (mq == queue->mq)
1420   {
1421     queue->mq = NULL;
1422     queue_finish (queue);
1423   }
1424 }
1425
1426
1427 /**
1428  * Implementation function that cancels the currently sent message.
1429  *
1430  * @param mq message queue
1431  * @param impl_state our `struct Queue`
1432  */
1433 static void
1434 mq_cancel (struct GNUNET_MQ_Handle *mq, void *impl_state)
1435 {
1436   struct Queue *queue = impl_state;
1437
1438   GNUNET_assert (0 != queue->pwrite_off);
1439   queue->pwrite_off = 0;
1440 }
1441
1442
1443 /**
1444  * Generic error handler, called with the appropriate
1445  * error code and the same closure specified at the creation of
1446  * the message queue.
1447  * Not every message queue implementation supports an error handler.
1448  *
1449  * @param cls our `struct Queue`
1450  * @param error error code
1451  */
1452 static void
1453 mq_error (void *cls, enum GNUNET_MQ_Error error)
1454 {
1455   struct Queue *queue = cls;
1456
1457   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1458               "MQ error in queue to %s: %d\n",
1459               GNUNET_i2s (&queue->target),
1460               (int) error);
1461   queue_finish (queue);
1462 }
1463
1464
1465 /**
1466  * Add the given @a queue to our internal data structure.  Setup the
1467  * MQ processing and inform transport that the queue is ready.  Must
1468  * be called after the KX for outgoing messages has been bootstrapped.
1469  *
1470  * @param queue queue to boot
1471  */
1472 static void
1473 boot_queue (struct Queue *queue, enum GNUNET_TRANSPORT_ConnectionStatus cs)
1474 {
1475   queue->nt =
1476     GNUNET_NT_scanner_get_type (is, queue->address, queue->address_len);
1477   (void) GNUNET_CONTAINER_multipeermap_put (
1478     queue_map,
1479     &queue->target,
1480     queue,
1481     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1482   GNUNET_STATISTICS_set (stats,
1483                          "# queues active",
1484                          GNUNET_CONTAINER_multipeermap_size (queue_map),
1485                          GNUNET_NO);
1486   queue->timeout =
1487     GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1488   queue->mq = GNUNET_MQ_queue_for_callbacks (&mq_send,
1489                                              &mq_destroy,
1490                                              &mq_cancel,
1491                                              queue,
1492                                              NULL,
1493                                              &mq_error,
1494                                              queue);
1495   {
1496     char *foreign_addr;
1497
1498     switch (queue->address->sa_family)
1499     {
1500     case AF_INET:
1501       GNUNET_asprintf (&foreign_addr,
1502                        "%s-%s",
1503                        COMMUNICATOR_ADDRESS_PREFIX,
1504                        GNUNET_a2s (queue->address, queue->address_len));
1505       break;
1506     case AF_INET6:
1507       GNUNET_asprintf (&foreign_addr,
1508                        "%s-%s",
1509                        COMMUNICATOR_ADDRESS_PREFIX,
1510                        GNUNET_a2s (queue->address, queue->address_len));
1511       break;
1512     default:
1513       GNUNET_assert (0);
1514     }
1515     queue->qh = GNUNET_TRANSPORT_communicator_mq_add (ch,
1516                                                       &queue->target,
1517                                                       foreign_addr,
1518                                                       0 /* no MTU */,
1519                                                       queue->nt,
1520                                                       cs,
1521                                                       queue->mq);
1522     GNUNET_free (foreign_addr);
1523   }
1524 }
1525
1526
1527 /**
1528  * Generate and transmit our ephemeral key and the signature for
1529  * the initial KX with the other peer.  Must be called first, before
1530  * any other bytes are ever written to the output buffer.  Note that
1531  * our cipher must already be initialized when calling this function.
1532  * Helper function for #start_initial_kx_out().
1533  *
1534  * @param queue queue to do KX for
1535  * @param epub our public key for the KX
1536  */
1537 static void
1538 transmit_kx (struct Queue *queue,
1539              const struct GNUNET_CRYPTO_EcdhePublicKey *epub)
1540 {
1541   struct TcpHandshakeSignature ths;
1542   struct TCPConfirmation tc;
1543
1544   memcpy (queue->cwrite_buf, epub, sizeof (*epub));
1545   queue->cwrite_off = sizeof (epub);
1546   /* compute 'tc' and append in encrypted format to cwrite_buf */
1547   tc.sender = my_identity;
1548   tc.monotonic_time =
1549     GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1550   ths.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE);
1551   ths.purpose.size = htonl (sizeof (ths));
1552   ths.sender = my_identity;
1553   ths.receiver = queue->target;
1554   ths.ephemeral = *epub;
1555   ths.monotonic_time = tc.monotonic_time;
1556   GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_private_key,
1557                                                         &ths.purpose,
1558                                                         &tc.sender_sig));
1559   GNUNET_assert (0 ==
1560                  gcry_cipher_encrypt (queue->out_cipher,
1561                                       &queue->cwrite_buf[queue->cwrite_off],
1562                                       sizeof (tc),
1563                                       &tc,
1564                                       sizeof (tc)));
1565   queue->cwrite_off += sizeof (tc);
1566 }
1567
1568
1569 /**
1570  * Initialize our key material for outgoing transmissions and
1571  * inform the other peer about it. Must be called first before
1572  * any data is sent.
1573  *
1574  * @param queue the queue to setup
1575  */
1576 static void
1577 start_initial_kx_out (struct Queue *queue)
1578 {
1579   struct GNUNET_CRYPTO_EcdhePublicKey epub;
1580
1581   GNUNET_assert (GNUNET_OK ==
1582                  GNUNET_CRYPTO_ecdhe_key_create2 (&queue->ephemeral));
1583   GNUNET_CRYPTO_ecdhe_key_get_public (&queue->ephemeral, &epub);
1584   setup_out_cipher (queue);
1585   transmit_kx (queue, &epub);
1586 }
1587
1588
1589 /**
1590  * We have received the first bytes from the other side on a @a queue.
1591  * Decrypt the @a tc contained in @a ibuf and check the signature.
1592  * Note that #setup_in_cipher() must have already been called.
1593  *
1594  * @param queue queue to decrypt initial bytes from other peer for
1595  * @param tc[out] where to store the result
1596  * @param ibuf incoming data, of size
1597  *        `INITIAL_KX_SIZE`
1598  * @return #GNUNET_OK if the signature was OK, #GNUNET_SYSERR if not
1599  */
1600 static int
1601 decrypt_and_check_tc (struct Queue *queue,
1602                       struct TCPConfirmation *tc,
1603                       char *ibuf)
1604 {
1605   struct TcpHandshakeSignature ths;
1606
1607   GNUNET_assert (
1608     0 ==
1609     gcry_cipher_decrypt (queue->in_cipher,
1610                          tc,
1611                          sizeof (*tc),
1612                          &ibuf[sizeof (struct GNUNET_CRYPTO_EcdhePublicKey)],
1613                          sizeof (tc)));
1614   ths.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE);
1615   ths.purpose.size = htonl (sizeof (ths));
1616   ths.sender = tc->sender;
1617   ths.receiver = my_identity;
1618   memcpy (&ths.ephemeral, ibuf, sizeof (struct GNUNET_CRYPTO_EcdhePublicKey));
1619   ths.monotonic_time = tc->monotonic_time;
1620   return GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE,
1621                                      &ths.purpose,
1622                                      &tc->sender_sig,
1623                                      &tc->sender.public_key);
1624 }
1625
1626
1627 /**
1628  * Closes socket and frees memory associated with @a pq.
1629  *
1630  * @param pq proto queue to free
1631  */
1632 static void
1633 free_proto_queue (struct ProtoQueue *pq)
1634 {
1635   GNUNET_NETWORK_socket_close (pq->sock);
1636   GNUNET_free (pq->address);
1637   GNUNET_CONTAINER_DLL_remove (proto_head, proto_tail, pq);
1638   GNUNET_free (pq);
1639 }
1640
1641
1642 /**
1643  * Read from the socket of the proto queue until we have enough data
1644  * to upgrade to full queue.
1645  *
1646  * @param cls a `struct ProtoQueue`
1647  */
1648 static void
1649 proto_read_kx (void *cls)
1650 {
1651   struct ProtoQueue *pq = cls;
1652   ssize_t rcvd;
1653   struct GNUNET_TIME_Relative left;
1654   struct Queue *queue;
1655   struct TCPConfirmation tc;
1656
1657   pq->read_task = NULL;
1658   left = GNUNET_TIME_absolute_get_remaining (pq->timeout);
1659   if (0 == left.rel_value_us)
1660   {
1661     free_proto_queue (pq);
1662     return;
1663   }
1664   rcvd = GNUNET_NETWORK_socket_recv (pq->sock,
1665                                      &pq->ibuf[pq->ibuf_off],
1666                                      sizeof (pq->ibuf) - pq->ibuf_off);
1667   if (-1 == rcvd)
1668   {
1669     if ((EAGAIN != errno) && (EINTR != errno))
1670     {
1671       GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "recv");
1672       free_proto_queue (pq);
1673       return;
1674     }
1675     /* try again */
1676     pq->read_task =
1677       GNUNET_SCHEDULER_add_read_net (left, pq->sock, &proto_read_kx, pq);
1678     return;
1679   }
1680   pq->ibuf_off += rcvd;
1681   if (pq->ibuf_off > sizeof (pq->ibuf))
1682   {
1683     /* read more */
1684     pq->read_task =
1685       GNUNET_SCHEDULER_add_read_net (left, pq->sock, &proto_read_kx, pq);
1686     return;
1687   }
1688   /* we got all the data, let's find out who we are talking to! */
1689   queue = GNUNET_new (struct Queue);
1690   setup_in_cipher ((const struct GNUNET_CRYPTO_EcdhePublicKey *) pq->ibuf,
1691                    queue);
1692   if (GNUNET_OK != decrypt_and_check_tc (queue, &tc, pq->ibuf))
1693   {
1694     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1695                 "Invalid TCP KX received from %s\n",
1696                 GNUNET_a2s (queue->address, queue->address_len));
1697     gcry_cipher_close (queue->in_cipher);
1698     GNUNET_free (queue);
1699     free_proto_queue (pq);
1700     return;
1701   }
1702   queue->address = pq->address; /* steals reference */
1703   queue->address_len = pq->address_len;
1704   queue->target = tc.sender;
1705   start_initial_kx_out (queue);
1706   boot_queue (queue, GNUNET_TRANSPORT_CS_INBOUND);
1707   queue->read_task =
1708     GNUNET_SCHEDULER_add_read_net (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1709                                    queue->sock,
1710                                    &queue_read,
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   if (NULL == queue)
1913   {
1914     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1915                 "Failed to setup queue to %s at `%s'\n",
1916                 GNUNET_i2s (peer),
1917                 path);
1918     GNUNET_NETWORK_socket_close (sock);
1919     return GNUNET_NO;
1920   }
1921   start_initial_kx_out (queue);
1922   return GNUNET_OK;
1923 }
1924
1925
1926 /**
1927  * Iterator over all message queues to clean up.
1928  *
1929  * @param cls NULL
1930  * @param target unused
1931  * @param value the queue to destroy
1932  * @return #GNUNET_OK to continue to iterate
1933  */
1934 static int
1935 get_queue_delete_it (void *cls,
1936                      const struct GNUNET_PeerIdentity *target,
1937                      void *value)
1938 {
1939   struct Queue *queue = value;
1940
1941   (void) cls;
1942   (void) target;
1943   queue_destroy (queue);
1944   return GNUNET_OK;
1945 }
1946
1947
1948 /**
1949  * Shutdown the UNIX communicator.
1950  *
1951  * @param cls NULL (always)
1952  */
1953 static void
1954 do_shutdown (void *cls)
1955 {
1956   if (NULL != nat)
1957   {
1958     GNUNET_NAT_unregister (nat);
1959     nat = NULL;
1960   }
1961   if (NULL != listen_task)
1962   {
1963     GNUNET_SCHEDULER_cancel (listen_task);
1964     listen_task = NULL;
1965   }
1966   if (NULL != listen_sock)
1967   {
1968     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (listen_sock));
1969     listen_sock = NULL;
1970   }
1971   GNUNET_CONTAINER_multipeermap_iterate (queue_map, &get_queue_delete_it, NULL);
1972   GNUNET_CONTAINER_multipeermap_destroy (queue_map);
1973   if (NULL != ch)
1974   {
1975     GNUNET_TRANSPORT_communicator_disconnect (ch);
1976     ch = NULL;
1977   }
1978   if (NULL != stats)
1979   {
1980     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1981     stats = NULL;
1982   }
1983   if (NULL != my_private_key)
1984   {
1985     GNUNET_free (my_private_key);
1986     my_private_key = NULL;
1987   }
1988   if (NULL != is)
1989   {
1990     GNUNET_NT_scanner_done (is);
1991     is = NULL;
1992   }
1993 }
1994
1995
1996 /**
1997  * Function called when the transport service has received an
1998  * acknowledgement for this communicator (!) via a different return
1999  * path.
2000  *
2001  * Not applicable for TCP.
2002  *
2003  * @param cls closure
2004  * @param sender which peer sent the notification
2005  * @param msg payload
2006  */
2007 static void
2008 enc_notify_cb (void *cls,
2009                const struct GNUNET_PeerIdentity *sender,
2010                const struct GNUNET_MessageHeader *msg)
2011 {
2012   (void) cls;
2013   (void) sender;
2014   (void) msg;
2015   GNUNET_break_op (0);
2016 }
2017
2018
2019 /**
2020  * Signature of the callback passed to #GNUNET_NAT_register() for
2021  * a function to call whenever our set of 'valid' addresses changes.
2022  *
2023  * @param cls closure
2024  * @param app_ctx[in,out] location where the app can store stuff
2025  *                  on add and retrieve it on remove
2026  * @param add_remove #GNUNET_YES to add a new public IP address,
2027  *                   #GNUNET_NO to remove a previous (now invalid) one
2028  * @param ac address class the address belongs to
2029  * @param addr either the previous or the new public IP address
2030  * @param addrlen actual length of the @a addr
2031  */
2032 static void
2033 nat_address_cb (void *cls,
2034                 void **app_ctx,
2035                 int add_remove,
2036                 enum GNUNET_NAT_AddressClass ac,
2037                 const struct sockaddr *addr,
2038                 socklen_t addrlen)
2039 {
2040   char *my_addr;
2041   struct GNUNET_TRANSPORT_AddressIdentifier *ai;
2042
2043   if (GNUNET_YES == add_remove)
2044   {
2045     enum GNUNET_NetworkType nt;
2046
2047     GNUNET_asprintf (&my_addr,
2048                      "%s-%s",
2049                      COMMUNICATOR_ADDRESS_PREFIX,
2050                      GNUNET_a2s (addr, addrlen));
2051     nt = GNUNET_NT_scanner_get_type (is, addr, addrlen);
2052     ai =
2053       GNUNET_TRANSPORT_communicator_address_add (ch,
2054                                                  my_addr,
2055                                                  nt,
2056                                                  GNUNET_TIME_UNIT_FOREVER_REL);
2057     GNUNET_free (my_addr);
2058     *app_ctx = ai;
2059   }
2060   else
2061   {
2062     ai = *app_ctx;
2063     GNUNET_TRANSPORT_communicator_address_remove (ai);
2064     *app_ctx = NULL;
2065   }
2066 }
2067
2068
2069 /**
2070  * Setup communicator and launch network interactions.
2071  *
2072  * @param cls NULL (always)
2073  * @param args remaining command-line arguments
2074  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2075  * @param c configuration
2076  */
2077 static void
2078 run (void *cls,
2079      char *const *args,
2080      const char *cfgfile,
2081      const struct GNUNET_CONFIGURATION_Handle *c)
2082 {
2083   char *bindto;
2084   struct sockaddr *in;
2085   socklen_t in_len;
2086   struct sockaddr_storage in_sto;
2087   socklen_t sto_len;
2088
2089   (void) cls;
2090   cfg = c;
2091   if (GNUNET_OK !=
2092       GNUNET_CONFIGURATION_get_value_filename (cfg,
2093                                                COMMUNICATOR_CONFIG_SECTION,
2094                                                "BINDTO",
2095                                                &bindto))
2096   {
2097     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2098                                COMMUNICATOR_CONFIG_SECTION,
2099                                "BINDTO");
2100     return;
2101   }
2102   if (GNUNET_OK !=
2103       GNUNET_CONFIGURATION_get_value_number (cfg,
2104                                              COMMUNICATOR_CONFIG_SECTION,
2105                                              "MAX_QUEUE_LENGTH",
2106                                              &max_queue_length))
2107     max_queue_length = DEFAULT_MAX_QUEUE_LENGTH;
2108
2109   in = tcp_address_to_sockaddr (bindto, &in_len);
2110   if (NULL == in)
2111   {
2112     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2113                 "Failed to setup TCP socket address with path `%s'\n",
2114                 bindto);
2115     GNUNET_free (bindto);
2116     return;
2117   }
2118   listen_sock =
2119     GNUNET_NETWORK_socket_create (in->sa_family, SOCK_STREAM, IPPROTO_TCP);
2120   if (NULL == listen_sock)
2121   {
2122     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
2123     GNUNET_free (in);
2124     GNUNET_free (bindto);
2125     return;
2126   }
2127   if (GNUNET_OK != GNUNET_NETWORK_socket_bind (listen_sock, in, in_len))
2128   {
2129     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "bind", bindto);
2130     GNUNET_NETWORK_socket_close (listen_sock);
2131     listen_sock = NULL;
2132     GNUNET_free (in);
2133     GNUNET_free (bindto);
2134     return;
2135   }
2136   /* We might have bound to port 0, allowing the OS to figure it out;
2137      thus, get the real IN-address from the socket */
2138   sto_len = sizeof (in_sto);
2139   if (0 != getsockname (GNUNET_NETWORK_get_fd (listen_sock),
2140                         (struct sockaddr *) &in_sto,
2141                         &sto_len))
2142   {
2143     memcpy (&in_sto, in, in_len);
2144     sto_len = in_len;
2145   }
2146   GNUNET_free (in);
2147   GNUNET_free (bindto);
2148   in = (struct sockaddr *) &in_sto;
2149   in_len = sto_len;
2150   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2151               "Bound to `%s'\n",
2152               GNUNET_a2s ((const struct sockaddr *) &in_sto, sto_len));
2153   stats = GNUNET_STATISTICS_create ("C-TCP", cfg);
2154   GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
2155   is = GNUNET_NT_scanner_init ();
2156   my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
2157   if (NULL == my_private_key)
2158   {
2159     GNUNET_log (
2160       GNUNET_ERROR_TYPE_ERROR,
2161       _ (
2162         "Transport service is lacking key configuration settings. Exiting.\n"));
2163     GNUNET_SCHEDULER_shutdown ();
2164     return;
2165   }
2166   GNUNET_CRYPTO_eddsa_key_get_public (my_private_key, &my_identity.public_key);
2167   /* start listening */
2168   listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2169                                                listen_sock,
2170                                                &listen_cb,
2171                                                NULL);
2172   queue_map = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
2173   ch = GNUNET_TRANSPORT_communicator_connect (cfg,
2174                                               COMMUNICATOR_CONFIG_SECTION,
2175                                               COMMUNICATOR_ADDRESS_PREFIX,
2176                                               GNUNET_TRANSPORT_CC_RELIABLE,
2177                                               &mq_init,
2178                                               NULL,
2179                                               &enc_notify_cb,
2180                                               NULL);
2181   if (NULL == ch)
2182   {
2183     GNUNET_break (0);
2184     GNUNET_SCHEDULER_shutdown ();
2185     return;
2186   }
2187   nat = GNUNET_NAT_register (cfg,
2188                              COMMUNICATOR_CONFIG_SECTION,
2189                              IPPROTO_TCP,
2190                              1 /* one address */,
2191                              (const struct sockaddr **) &in,
2192                              &in_len,
2193                              &nat_address_cb,
2194                              NULL /* FIXME: support reversal: #5529 */,
2195                              NULL /* closure */);
2196 }
2197
2198
2199 /**
2200  * The main function for the UNIX communicator.
2201  *
2202  * @param argc number of arguments from the command line
2203  * @param argv command line arguments
2204  * @return 0 ok, 1 on error
2205  */
2206 int
2207 main (int argc, char *const *argv)
2208 {
2209   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2210     GNUNET_GETOPT_OPTION_END};
2211   int ret;
2212
2213   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
2214     return 2;
2215
2216   ret = (GNUNET_OK == GNUNET_PROGRAM_run (argc,
2217                                           argv,
2218                                           "gnunet-communicator-tcp",
2219                                           _ ("GNUnet TCP communicator"),
2220                                           options,
2221                                           &run,
2222                                           NULL))
2223           ? 0
2224           : 1;
2225   GNUNET_free ((void *) argv);
2226   return ret;
2227 }
2228
2229
2230 /* end of gnunet-communicator-tcp.c */