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