2 This file is part of GNUnet
3 Copyright (C) 2010-2014, 2018, 2019 GNUnet e.V.
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.
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.
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/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file transport/gnunet-communicator-tcp.c
23 * @brief Transport plugin using TCP.
24 * @author Christian Grothoff
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
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"
46 * How long do we believe our addresses to remain up (before
47 * the other peer should revalidate).
49 #define ADDRESS_VALIDITY_PERIOD \
50 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 4)
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.
60 #define DEFAULT_MAX_QUEUE_LENGTH 8
63 * Size of our IO buffers for ciphertext data. Must be at
64 * least UINT_MAX + sizeof (struct TCPBox).
66 #define BUF_SIZE (2 * 64 * 1024 + sizeof(struct TCPBox))
69 * How often do we rekey based on time (at least)
71 #define REKEY_TIME_INTERVAL GNUNET_TIME_UNIT_DAYS
74 * How long do we wait until we must have received the initial KX?
76 #define PROTO_QUEUE_TIMEOUT GNUNET_TIME_UNIT_MINUTES
79 * How often do we rekey based on number of bytes transmitted?
80 * (additionally randomized).
82 #define REKEY_MAX_BYTES (1024LLU * 1024 * 1024 * 4LLU)
85 * Size of the initial key exchange message sent first in both
88 #define INITIAL_KX_SIZE \
89 (sizeof(struct GNUNET_CRYPTO_EcdhePublicKey) \
90 + sizeof(struct TCPConfirmation))
94 * Address prefix used by the communicator.
96 #define COMMUNICATOR_ADDRESS_PREFIX "tcp"
99 * Configuration section used by the communicator.
101 #define COMMUNICATOR_CONFIG_SECTION "communicator-tcp"
103 GNUNET_NETWORK_STRUCT_BEGIN
107 * Signature we use to verify that the ephemeral key was really chosen by
108 * the specified sender.
110 struct TcpHandshakeSignature
113 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE
115 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
118 * Identity of the inititor of the TCP connection (TCP client).
120 struct GNUNET_PeerIdentity sender;
123 * Presumed identity of the target of the TCP connection (TCP server)
125 struct GNUNET_PeerIdentity receiver;
128 * Ephemeral key used by the @e sender.
130 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
133 * Monotonic time of @e sender, to possibly help detect replay attacks
134 * (if receiver persists times by sender).
136 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
141 * Encrypted continuation of TCP initial handshake.
143 struct TCPConfirmation
148 struct GNUNET_PeerIdentity sender;
151 * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE
153 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
156 * Monotonic time of @e sender, to possibly help detect replay attacks
157 * (if receiver persists times by sender).
159 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
164 * TCP message box. Always sent encrypted!
169 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX. Warning: the
170 * header size EXCLUDES the size of the `struct TCPBox`. We usually
171 * never do this, but here the payload may truly be 64k *after* the
172 * TCPBox (as we have no MTU)!!
174 struct GNUNET_MessageHeader header;
177 * HMAC for the following encrypted message. Yes, we MUST use
178 * mac-then-encrypt here, as we want to hide the message sizes on
179 * the wire (zero plaintext design!). Using CTR mode, padding oracle
180 * attacks do not apply. Besides, due to the use of ephemeral keys
181 * (hopefully with effective replay protection from monotonic time!)
182 * the attacker is limited in using the oracle.
184 struct GNUNET_ShortHashCode hmac;
186 /* followed by as may bytes of payload as indicated in @e header,
187 excluding the TCPBox itself! */
192 * TCP rekey message box. Always sent encrypted! Data after
193 * this message will use the new key.
198 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY.
200 struct GNUNET_MessageHeader header;
203 * HMAC for the following encrypted message. Yes, we MUST use
204 * mac-then-encrypt here, as we want to hide the message sizes on
205 * the wire (zero plaintext design!). Using CTR mode padding oracle
206 * attacks do not apply. Besides, due to the use of ephemeral keys
207 * (hopefully with effective replay protection from monotonic time!)
208 * the attacker is limited in using the oracle.
210 struct GNUNET_ShortHashCode hmac;
215 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
218 * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY
220 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
223 * Monotonic time of @e sender, to possibly help detect replay attacks
224 * (if receiver persists times by sender).
226 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
231 * TCP finish. Sender asks for the connection to be closed.
232 * Needed/useful in case we drop RST/FIN packets on the GNUnet
233 * port due to the possibility of malicious RST/FIN injection.
238 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH.
240 struct GNUNET_MessageHeader header;
243 * HMAC for the following encrypted message. Yes, we MUST use
244 * mac-then-encrypt here, as we want to hide the message sizes on
245 * the wire (zero plaintext design!). Using CTR mode padding oracle
246 * attacks do not apply. Besides, due to the use of ephemeral keys
247 * (hopefully with effective replay protection from monotonic time!)
248 * the attacker is limited in using the oracle.
250 struct GNUNET_ShortHashCode hmac;
254 GNUNET_NETWORK_STRUCT_END
258 * Handle for a queue.
263 * To whom are we talking to.
265 struct GNUNET_PeerIdentity target;
268 * socket that we transmit all data with on this queue
270 struct GNUNET_NETWORK_Handle *sock;
273 * cipher for decryption of incoming data.
275 gcry_cipher_hd_t in_cipher;
278 * cipher for encryption of outgoing data.
280 gcry_cipher_hd_t out_cipher;
283 * Shared secret for HMAC verification on incoming data.
285 struct GNUNET_HashCode in_hmac;
288 * Shared secret for HMAC generation on outgoing data, ratcheted after
291 struct GNUNET_HashCode out_hmac;
294 * Our ephemeral key. Stored here temporarily during rekeying / key
297 struct GNUNET_CRYPTO_EcdhePrivateKey ephemeral;
300 * ID of read task for this connection.
302 struct GNUNET_SCHEDULER_Task *read_task;
305 * ID of write task for this connection.
307 struct GNUNET_SCHEDULER_Task *write_task;
310 * Address of the other peer.
312 struct sockaddr *address;
315 * How many more bytes may we sent with the current @e out_cipher
316 * before we should rekey?
318 uint64_t rekey_left_bytes;
321 * Until what time may we sent with the current @e out_cipher
322 * before we should rekey?
324 struct GNUNET_TIME_Absolute rekey_time;
327 * Length of the address.
329 socklen_t address_len;
332 * Message queue we are providing for the #ch.
334 struct GNUNET_MQ_Handle *mq;
337 * handle for this queue with the #ch.
339 struct GNUNET_TRANSPORT_QueueHandle *qh;
342 * Number of bytes we currently have in our write queue.
344 unsigned long long bytes_in_queue;
347 * Buffer for reading ciphertext from network into.
349 char cread_buf[BUF_SIZE];
352 * buffer for writing ciphertext to network.
354 char cwrite_buf[BUF_SIZE];
357 * Plaintext buffer for decrypted plaintext.
359 char pread_buf[UINT16_MAX + 1 + sizeof(struct TCPBox)];
362 * Plaintext buffer for messages to be encrypted.
364 char pwrite_buf[UINT16_MAX + 1 + sizeof(struct TCPBox)];
367 * At which offset in the ciphertext read buffer should we
368 * append more ciphertext for transmission next?
373 * At which offset in the ciphertext write buffer should we
374 * append more ciphertext from reading next?
379 * At which offset in the plaintext input buffer should we
380 * append more plaintext from decryption next?
385 * At which offset in the plaintext output buffer should we
386 * append more plaintext for encryption next?
391 * Timeout for this queue.
393 struct GNUNET_TIME_Absolute timeout;
396 * How may messages did we pass from this queue to CORE for which we
397 * have yet to receive an acknoweldgement that CORE is done with
398 * them? If "large" (or even just non-zero), we should throttle
399 * reading to provide flow control. See also #DEFAULT_MAX_QUEUE_LENGTH
400 * and #max_queue_length.
402 unsigned int backpressure;
405 * Which network type does this queue use?
407 enum GNUNET_NetworkType nt;
410 * Is MQ awaiting a #GNUNET_MQ_impl_send_continue() call?
412 int mq_awaits_continue;
415 * Did we enqueue a finish message and are closing down the queue?
420 * Did we technically destroy this queue, but kept the allocation
421 * around because of @e backpressure not being zero yet? Used
422 * simply to delay the final #GNUNET_free() operation until
423 * #core_read_finished_cb() has been called.
428 * #GNUNET_YES if we just rekeyed and must thus possibly
429 * re-decrypt ciphertext.
436 * Handle for an incoming connection where we do not yet have enough
437 * information to setup a full queue.
444 struct ProtoQueue *next;
449 struct ProtoQueue *prev;
452 * socket that we transmit all data with on this queue
454 struct GNUNET_NETWORK_Handle *sock;
457 * ID of read task for this connection.
459 struct GNUNET_SCHEDULER_Task *read_task;
462 * Address of the other peer.
464 struct sockaddr *address;
467 * Length of the address.
469 socklen_t address_len;
472 * Timeout for this protoqueue.
474 struct GNUNET_TIME_Absolute timeout;
477 * Buffer for reading all the information we need to upgrade from
478 * protoqueue to queue.
480 char ibuf[INITIAL_KX_SIZE];
483 * Current offset for reading into @e ibuf.
492 static struct GNUNET_SCHEDULER_Task *listen_task;
495 * Maximum queue length before we stop reading towards the transport service.
497 static unsigned long long max_queue_length;
500 * For logging statistics.
502 static struct GNUNET_STATISTICS_Handle *stats;
507 static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
510 * Queues (map from peer identity to `struct Queue`)
512 static struct GNUNET_CONTAINER_MultiPeerMap *queue_map;
517 static struct GNUNET_NETWORK_Handle *listen_sock;
522 static struct GNUNET_PeerIdentity my_identity;
527 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
532 static const struct GNUNET_CONFIGURATION_Handle *cfg;
535 * Network scanner to determine network types.
537 static struct GNUNET_NT_InterfaceScanner *is;
540 * Connection to NAT service.
542 static struct GNUNET_NAT_Handle *nat;
545 * Protoqueues DLL head.
547 static struct ProtoQueue *proto_head;
550 * Protoqueues DLL tail.
552 static struct ProtoQueue *proto_tail;
556 * We have been notified that our listen socket has something to
557 * read. Do the read and reschedule this function to be called again
558 * once more is available.
563 listen_cb (void *cls);
567 * Functions with this signature are called whenever we need
568 * to close a queue due to a disconnect or failure to
569 * establish a connection.
571 * @param queue queue to close down
574 queue_destroy (struct Queue *queue)
576 struct GNUNET_MQ_Handle *mq;
578 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
579 "Disconnecting queue for peer `%s'\n",
580 GNUNET_i2s (&queue->target));
581 if (NULL != (mq = queue->mq))
584 GNUNET_MQ_destroy (mq);
586 if (NULL != queue->qh)
588 GNUNET_TRANSPORT_communicator_mq_del (queue->qh);
593 GNUNET_CONTAINER_multipeermap_remove (queue_map, &queue->target, queue));
594 GNUNET_STATISTICS_set (stats,
596 GNUNET_CONTAINER_multipeermap_size (queue_map),
598 if (NULL != queue->read_task)
600 GNUNET_SCHEDULER_cancel (queue->read_task);
601 queue->read_task = NULL;
603 if (NULL != queue->write_task)
605 GNUNET_SCHEDULER_cancel (queue->write_task);
606 queue->write_task = NULL;
608 GNUNET_NETWORK_socket_close (queue->sock);
609 gcry_cipher_close (queue->in_cipher);
610 gcry_cipher_close (queue->out_cipher);
611 GNUNET_free (queue->address);
612 if (0 != queue->backpressure)
613 queue->destroyed = GNUNET_YES;
616 if (NULL == listen_task)
617 listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
625 * Compute @a mac over @a buf, and ratched the @a hmac_secret.
627 * @param[in,out] hmac_secret secret for HMAC calculation
628 * @param buf buffer to MAC
629 * @param buf_size number of bytes in @a buf
630 * @param smac[out] where to write the HMAC
633 calculate_hmac (struct GNUNET_HashCode *hmac_secret,
636 struct GNUNET_ShortHashCode *smac)
638 struct GNUNET_HashCode mac;
640 GNUNET_CRYPTO_hmac_raw (hmac_secret,
641 sizeof(struct GNUNET_HashCode),
645 /* truncate to `struct GNUNET_ShortHashCode` */
646 memcpy (smac, &mac, sizeof(struct GNUNET_ShortHashCode));
647 /* ratchet hmac key */
648 GNUNET_CRYPTO_hash (hmac_secret,
649 sizeof(struct GNUNET_HashCode),
655 * Append a 'finish' message to the outgoing transmission. Once the
656 * finish has been transmitted, destroy the queue.
658 * @param queue queue to shut down nicely
661 queue_finish (struct Queue *queue)
663 struct TCPFinish fin;
665 memset (&fin, 0, sizeof(fin));
666 fin.header.size = htons (sizeof(fin));
667 fin.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH);
668 calculate_hmac (&queue->out_hmac, &fin, sizeof(fin), &fin.hmac);
669 /* if there is any message left in pwrite_buf, we
670 overwrite it (possibly dropping the last message
671 from CORE hard here) */
672 memcpy (queue->pwrite_buf, &fin, sizeof(fin));
673 queue->pwrite_off = sizeof(fin);
674 /* This flag will ensure that #queue_write() no longer
675 notifies CORE about the possibility of sending
676 more data, and that #queue_write() will call
677 #queue_destroy() once the @c fin was fully written. */
678 queue->finishing = GNUNET_YES;
683 * Increment queue timeout due to activity. We do not immediately
684 * notify the monitor here as that might generate excessive
687 * @param queue queue for which the timeout should be rescheduled
690 reschedule_queue_timeout (struct Queue *queue)
693 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
698 * Queue read task. If we hit the timeout, disconnect it
700 * @param cls the `struct Queue *` to disconnect
703 queue_read (void *cls);
707 * Core tells us it is done processing a message that transport
708 * received on a queue with status @a success.
710 * @param cls a `struct Queue *` where the message originally came from
711 * @param success #GNUNET_OK on success
714 core_read_finished_cb (void *cls, int success)
716 struct Queue *queue = cls;
718 if (GNUNET_OK != success)
719 GNUNET_STATISTICS_update (stats,
720 "# messages lost in communicator API towards CORE",
723 queue->backpressure--;
724 /* handle deferred queue destruction */
725 if ((queue->destroyed) && (0 == queue->backpressure))
730 reschedule_queue_timeout (queue);
731 /* possibly unchoke reading, now that CORE made progress */
732 if (NULL == queue->read_task)
734 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining (
743 * We received @a plaintext_len bytes of @a plaintext on @a queue.
744 * Pass it on to CORE. If transmission is actually happening,
745 * increase backpressure counter.
747 * @param queue the queue that received the plaintext
748 * @param plaintext the plaintext that was received
749 * @param plaintext_len number of bytes of plaintext received
752 pass_plaintext_to_core (struct Queue *queue,
753 const void *plaintext,
754 size_t plaintext_len)
756 const struct GNUNET_MessageHeader *hdr = plaintext;
759 if (ntohs (hdr->size) != plaintext_len)
761 /* NOTE: If we ever allow multiple CORE messages in one
762 BOX, this will have to change! */
766 ret = GNUNET_TRANSPORT_communicator_receive (ch,
769 ADDRESS_VALIDITY_PERIOD,
770 &core_read_finished_cb,
772 if (GNUNET_OK == ret)
773 queue->backpressure++;
774 GNUNET_break (GNUNET_NO != ret); /* backpressure not working!? */
775 if (GNUNET_SYSERR == ret)
776 GNUNET_STATISTICS_update (stats,
777 "# bytes lost due to CORE not running",
784 * Setup @a cipher based on shared secret @a dh and decrypting
787 * @param dh shared secret
788 * @param pid decrypting peer's identity
789 * @param cipher[out] cipher to initialize
790 * @param hmac_key[out] HMAC key to initialize
793 setup_cipher (const struct GNUNET_HashCode *dh,
794 const struct GNUNET_PeerIdentity *pid,
795 gcry_cipher_hd_t *cipher,
796 struct GNUNET_HashCode *hmac_key)
801 gcry_cipher_open (cipher,
802 GCRY_CIPHER_AES256 /* low level: go for speed */,
803 GCRY_CIPHER_MODE_CTR,
805 GNUNET_assert (GNUNET_YES == GNUNET_CRYPTO_kdf (key,
815 gcry_cipher_setkey (*cipher, key, sizeof(key));
816 GNUNET_assert (GNUNET_YES == GNUNET_CRYPTO_kdf (ctr,
826 gcry_cipher_setctr (*cipher, ctr, sizeof(ctr));
827 GNUNET_assert (GNUNET_YES ==
828 GNUNET_CRYPTO_kdf (hmac_key,
829 sizeof(struct GNUNET_HashCode),
842 * Setup cipher of @a queue for decryption.
844 * @param ephemeral ephemeral key we received from the other peer
845 * @param queue[in,out] queue to initialize decryption cipher for
848 setup_in_cipher (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
851 struct GNUNET_HashCode dh;
853 GNUNET_CRYPTO_eddsa_ecdh (my_private_key, ephemeral, &dh);
854 setup_cipher (&dh, &my_identity, &queue->in_cipher, &queue->in_hmac);
859 * Handle @a rekey message on @a queue. The message was already
860 * HMAC'ed, but we should additionally still check the signature.
861 * Then we need to stop the old cipher and start afresh.
863 * @param queue the queue @a rekey was received on
864 * @param rekey the rekey message
867 do_rekey (struct Queue *queue, const struct TCPRekey *rekey)
869 struct TcpHandshakeSignature thp;
871 thp.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY);
872 thp.purpose.size = htonl (sizeof(thp));
873 thp.sender = queue->target;
874 thp.receiver = my_identity;
875 thp.ephemeral = rekey->ephemeral;
876 thp.monotonic_time = rekey->monotonic_time;
877 /* FIXME: check monotonic time is monotonic... */
879 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY,
882 &queue->target.public_key))
885 queue_finish (queue);
888 gcry_cipher_close (queue->in_cipher);
889 queue->rekeyed = GNUNET_YES;
890 setup_in_cipher (&rekey->ephemeral, queue);
895 * Test if we have received a full message in plaintext.
898 * @param queue queue to process inbound plaintext for
899 * @return number of bytes of plaintext handled, 0 for none
902 try_handle_plaintext (struct Queue *queue)
904 const struct GNUNET_MessageHeader *hdr =
905 (const struct GNUNET_MessageHeader *) queue->pread_buf;
906 const struct TCPBox *box = (const struct TCPBox *) queue->pread_buf;
907 const struct TCPRekey *rekey = (const struct TCPRekey *) queue->pread_buf;
908 const struct TCPFinish *fin = (const struct TCPFinish *) queue->pread_buf;
909 struct TCPRekey rekeyz;
910 struct TCPFinish finz;
911 struct GNUNET_ShortHashCode tmac;
913 size_t size = 0; /* make compiler happy */
915 if (sizeof(*hdr) > queue->pread_off)
916 return 0; /* not even a header */
917 type = ntohs (hdr->type);
920 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX:
921 /* Special case: header size excludes box itself! */
922 if (ntohs (hdr->size) + sizeof(struct TCPBox) > queue->pread_off)
924 calculate_hmac (&queue->in_hmac, &box[1], ntohs (hdr->size), &tmac);
925 if (0 != memcmp (&tmac, &box->hmac, sizeof(tmac)))
928 queue_finish (queue);
931 pass_plaintext_to_core (queue, (const void *) &box[1], ntohs (hdr->size));
932 size = ntohs (hdr->size) + sizeof(*box);
935 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY:
936 if (sizeof(*rekey) > queue->pread_off)
938 if (ntohs (hdr->size) != sizeof(*rekey))
941 queue_finish (queue);
945 memset (&rekeyz.hmac, 0, sizeof(rekeyz.hmac));
946 calculate_hmac (&queue->in_hmac, &rekeyz, sizeof(rekeyz), &tmac);
947 if (0 != memcmp (&tmac, &box->hmac, sizeof(tmac)))
950 queue_finish (queue);
953 do_rekey (queue, rekey);
954 size = ntohs (hdr->size);
957 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH:
958 if (sizeof(*fin) > queue->pread_off)
960 if (ntohs (hdr->size) != sizeof(*fin))
963 queue_finish (queue);
967 memset (&finz.hmac, 0, sizeof(finz.hmac));
968 calculate_hmac (&queue->in_hmac, &rekeyz, sizeof(rekeyz), &tmac);
969 if (0 != memcmp (&tmac, &fin->hmac, sizeof(tmac)))
972 queue_finish (queue);
975 /* handle FINISH by destroying queue */
976 queue_destroy (queue);
981 queue_finish (queue);
984 GNUNET_assert (0 != size);
990 * Queue read task. If we hit the timeout, disconnect it
992 * @param cls the `struct Queue *` to disconnect
995 queue_read (void *cls)
997 struct Queue *queue = cls;
998 struct GNUNET_TIME_Relative left;
1001 queue->read_task = NULL;
1002 rcvd = GNUNET_NETWORK_socket_recv (queue->sock,
1003 &queue->cread_buf[queue->cread_off],
1004 BUF_SIZE - queue->cread_off);
1007 if ((EAGAIN != errno) && (EINTR != errno))
1009 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "recv");
1010 queue_finish (queue);
1015 GNUNET_SCHEDULER_add_read_net (left, queue->sock, &queue_read, queue);
1019 reschedule_queue_timeout (queue);
1020 queue->cread_off += rcvd;
1021 while ((queue->pread_off < sizeof(queue->pread_buf)) &&
1022 (queue->cread_off > 0))
1024 size_t max = GNUNET_MIN (sizeof(queue->pread_buf) - queue->pread_off,
1030 gcry_cipher_decrypt (queue->in_cipher,
1031 &queue->pread_buf[queue->pread_off],
1035 queue->pread_off += max;
1037 while ((GNUNET_NO == queue->rekeyed) &&
1038 (0 != (done = try_handle_plaintext (queue))))
1040 /* 'done' bytes of plaintext were used, shift buffer */
1041 GNUNET_assert (done <= queue->pread_off);
1042 /* NOTE: this memmove() could possibly sometimes be
1043 avoided if we pass 'total' into try_handle_plaintext()
1044 and use it at an offset into the buffer there! */
1045 memmove (queue->pread_buf,
1046 &queue->pread_buf[done],
1047 queue->pread_off - done);
1048 queue->pread_off -= done;
1051 /* when we encounter a rekey message, the decryption above uses the
1052 wrong key for everything after the rekey; in that case, we have
1053 to re-do the decryption at 'total' instead of at 'max'. If there
1054 is no rekey and the last message is incomplete (max > total),
1055 it is safe to keep the decryption so we shift by 'max' */if (GNUNET_YES == queue->rekeyed)
1058 queue->rekeyed = GNUNET_NO;
1060 memmove (queue->cread_buf, &queue->cread_buf[max], queue->cread_off - max);
1061 queue->cread_off -= max;
1064 if (BUF_SIZE == queue->cread_off)
1065 return; /* buffer full, suspend reading */
1066 left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
1067 if (0 != left.rel_value_us)
1069 if (max_queue_length < queue->backpressure)
1071 /* continue reading */
1073 GNUNET_SCHEDULER_add_read_net (left, queue->sock, &queue_read, queue);
1077 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1078 "Queue %p was idle for %s, disconnecting\n",
1080 GNUNET_STRINGS_relative_time_to_string (
1081 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1083 queue_finish (queue);
1088 * Convert TCP bind specification to a `struct sockaddr *`
1090 * @param bindto bind specification to convert
1091 * @param[out] sock_len set to the length of the address
1092 * @return converted bindto specification
1094 static struct sockaddr *
1095 tcp_address_to_sockaddr (const char *bindto, socklen_t *sock_len)
1097 struct sockaddr *in;
1103 if (1 == sscanf (bindto, "%u%1s", &port, dummy))
1105 /* interpreting value as just a PORT number */
1106 if (port > UINT16_MAX)
1108 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1109 "BINDTO specification `%s' invalid: value too large for port\n",
1113 if ((GNUNET_NO == GNUNET_NETWORK_test_pf (PF_INET6)) ||
1115 GNUNET_CONFIGURATION_get_value_yesno (cfg,
1116 COMMUNICATOR_CONFIG_SECTION,
1119 struct sockaddr_in *i4;
1121 i4 = GNUNET_malloc (sizeof(struct sockaddr_in));
1122 i4->sin_family = AF_INET;
1123 i4->sin_port = htons ((uint16_t) port);
1124 *sock_len = sizeof(struct sockaddr_in);
1125 in = (struct sockaddr *) i4;
1129 struct sockaddr_in6 *i6;
1131 i6 = GNUNET_malloc (sizeof(struct sockaddr_in6));
1132 i6->sin6_family = AF_INET6;
1133 i6->sin6_port = htons ((uint16_t) port);
1134 *sock_len = sizeof(struct sockaddr_in6);
1135 in = (struct sockaddr *) i6;
1139 cp = GNUNET_strdup (bindto);
1140 colon = strrchr (cp, ':');
1143 /* interpet value after colon as port */
1146 if (1 == sscanf (colon, "%u%1s", &port, dummy))
1148 /* interpreting value as just a PORT number */
1149 if (port > UINT16_MAX)
1151 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1152 "BINDTO specification `%s' invalid: value too large for port\n",
1161 GNUNET_ERROR_TYPE_ERROR,
1162 "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1170 /* interpret missing port as 0, aka pick any free one */
1175 struct sockaddr_in v4;
1177 if (1 == inet_pton (AF_INET, cp, &v4))
1179 v4.sin_port = htons ((uint16_t) port);
1180 in = GNUNET_memdup (&v4, sizeof(v4));
1181 *sock_len = sizeof(v4);
1188 struct sockaddr_in6 v6;
1192 if (('[' == *cp) && (']' == cp[strlen (cp) - 1]))
1194 start++; /* skip over '[' */
1195 cp[strlen (cp) - 1] = '\0'; /* eat ']' */
1197 if (1 == inet_pton (AF_INET6, start, &v6))
1199 v6.sin6_port = htons ((uint16_t) port);
1200 in = GNUNET_memdup (&v6, sizeof(v6));
1201 *sock_len = sizeof(v6);
1206 /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1213 * Setup cipher for outgoing data stream based on target and
1214 * our ephemeral private key.
1216 * @param queue queue to setup outgoing (encryption) cipher for
1219 setup_out_cipher (struct Queue *queue)
1221 struct GNUNET_HashCode dh;
1223 GNUNET_CRYPTO_ecdh_eddsa (&queue->ephemeral, &queue->target.public_key, &dh);
1224 /* we don't need the private key anymore, drop it! */
1225 memset (&queue->ephemeral, 0, sizeof(queue->ephemeral));
1226 setup_cipher (&dh, &queue->target, &queue->out_cipher, &queue->out_hmac);
1227 queue->rekey_time = GNUNET_TIME_relative_to_absolute (REKEY_TIME_INTERVAL);
1228 queue->rekey_left_bytes =
1229 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, REKEY_MAX_BYTES);
1234 * Inject a `struct TCPRekey` message into the queue's plaintext
1237 * @param queue queue to perform rekeying on
1240 inject_rekey (struct Queue *queue)
1242 struct TCPRekey rekey;
1243 struct TcpHandshakeSignature thp;
1245 GNUNET_assert (0 == queue->pwrite_off);
1246 memset (&rekey, 0, sizeof(rekey));
1247 GNUNET_assert (GNUNET_OK ==
1248 GNUNET_CRYPTO_ecdhe_key_create2 (&queue->ephemeral));
1249 rekey.header.type = ntohs (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY);
1250 rekey.header.size = ntohs (sizeof(rekey));
1251 GNUNET_CRYPTO_ecdhe_key_get_public (&queue->ephemeral, &rekey.ephemeral);
1252 rekey.monotonic_time =
1253 GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1254 thp.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY);
1255 thp.purpose.size = htonl (sizeof(thp));
1256 thp.sender = my_identity;
1257 thp.receiver = queue->target;
1258 thp.ephemeral = rekey.ephemeral;
1259 thp.monotonic_time = rekey.monotonic_time;
1260 GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_private_key,
1262 &rekey.sender_sig));
1263 calculate_hmac (&queue->out_hmac, &rekey, sizeof(rekey), &rekey.hmac);
1264 memcpy (queue->pwrite_buf, &rekey, sizeof(rekey));
1265 queue->pwrite_off = sizeof(rekey);
1270 * We have been notified that our socket is ready to write.
1271 * Then reschedule this function to be called again once more is available.
1273 * @param cls a `struct Queue`
1276 queue_write (void *cls)
1278 struct Queue *queue = cls;
1281 queue->write_task = NULL;
1282 if (0 != queue->cwrite_off)
1284 sent = GNUNET_NETWORK_socket_send (queue->sock,
1287 if ((-1 == sent) && (EAGAIN != errno) && (EINTR != errno))
1289 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "send");
1290 queue_destroy (queue);
1295 size_t usent = (size_t) sent;
1297 memmove (queue->cwrite_buf,
1298 &queue->cwrite_buf[usent],
1299 queue->cwrite_off - usent);
1300 reschedule_queue_timeout (queue);
1303 /* can we encrypt more? (always encrypt full messages, needed
1304 such that #mq_cancel() can work!) */
1305 if ((0 < queue->rekey_left_bytes) &&
1306 (queue->cwrite_off + queue->pwrite_off <= BUF_SIZE))
1309 gcry_cipher_encrypt (queue->out_cipher,
1310 &queue->cwrite_buf[queue->cwrite_off],
1313 queue->pwrite_off));
1314 if (queue->rekey_left_bytes > queue->pwrite_off)
1315 queue->rekey_left_bytes -= queue->pwrite_off;
1317 queue->rekey_left_bytes = 0;
1318 queue->cwrite_off += queue->pwrite_off;
1319 queue->pwrite_off = 0;
1321 if ((0 == queue->pwrite_off) &&
1322 ((0 == queue->rekey_left_bytes) ||
1324 GNUNET_TIME_absolute_get_remaining (queue->rekey_time).rel_value_us)))
1326 gcry_cipher_close (queue->out_cipher);
1327 setup_out_cipher (queue);
1328 inject_rekey (queue);
1330 if ((0 == queue->pwrite_off) && (! queue->finishing) &&
1331 (queue->mq_awaits_continue))
1333 queue->mq_awaits_continue = GNUNET_NO;
1334 GNUNET_MQ_impl_send_continue (queue->mq);
1336 /* did we just finish writing 'finish'? */
1337 if ((0 == queue->cwrite_off) && (GNUNET_YES == queue->finishing))
1339 queue_destroy (queue);
1342 /* do we care to write more? */
1343 if ((0 < queue->cwrite_off) || (0 < queue->pwrite_off))
1345 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1353 * Signature of functions implementing the sending functionality of a
1356 * @param mq the message queue
1357 * @param msg the message to send
1358 * @param impl_state our `struct Queue`
1361 mq_send (struct GNUNET_MQ_Handle *mq,
1362 const struct GNUNET_MessageHeader *msg,
1365 struct Queue *queue = impl_state;
1366 uint16_t msize = ntohs (msg->size);
1369 GNUNET_assert (mq == queue->mq);
1370 if (GNUNET_YES == queue->finishing)
1371 return; /* this queue is dying, drop msg */
1372 GNUNET_assert (0 == queue->pread_off);
1373 box.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX);
1374 box.header.size = htons (msize);
1375 calculate_hmac (&queue->out_hmac, msg, msize, &box.hmac);
1376 memcpy (&queue->pread_buf[queue->pread_off], &box, sizeof(box));
1377 queue->pread_off += sizeof(box);
1378 memcpy (&queue->pread_buf[queue->pread_off], msg, msize);
1379 queue->pread_off += msize;
1380 GNUNET_assert (NULL != queue->sock);
1381 if (NULL == queue->write_task)
1383 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1391 * Signature of functions implementing the destruction of a message
1392 * queue. Implementations must not free @a mq, but should take care
1395 * @param mq the message queue to destroy
1396 * @param impl_state our `struct Queue`
1399 mq_destroy (struct GNUNET_MQ_Handle *mq, void *impl_state)
1401 struct Queue *queue = impl_state;
1403 if (mq == queue->mq)
1406 queue_finish (queue);
1412 * Implementation function that cancels the currently sent message.
1414 * @param mq message queue
1415 * @param impl_state our `struct Queue`
1418 mq_cancel (struct GNUNET_MQ_Handle *mq, void *impl_state)
1420 struct Queue *queue = impl_state;
1422 GNUNET_assert (0 != queue->pwrite_off);
1423 queue->pwrite_off = 0;
1428 * Generic error handler, called with the appropriate
1429 * error code and the same closure specified at the creation of
1430 * the message queue.
1431 * Not every message queue implementation supports an error handler.
1433 * @param cls our `struct Queue`
1434 * @param error error code
1437 mq_error (void *cls, enum GNUNET_MQ_Error error)
1439 struct Queue *queue = cls;
1441 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1442 "MQ error in queue to %s: %d\n",
1443 GNUNET_i2s (&queue->target),
1445 queue_finish (queue);
1450 * Add the given @a queue to our internal data structure. Setup the
1451 * MQ processing and inform transport that the queue is ready. Must
1452 * be called after the KX for outgoing messages has been bootstrapped.
1454 * @param queue queue to boot
1457 boot_queue (struct Queue *queue, enum GNUNET_TRANSPORT_ConnectionStatus cs)
1460 GNUNET_NT_scanner_get_type (is, queue->address, queue->address_len);
1461 (void) GNUNET_CONTAINER_multipeermap_put (
1465 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1466 GNUNET_STATISTICS_set (stats,
1468 GNUNET_CONTAINER_multipeermap_size (queue_map),
1471 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1472 queue->mq = GNUNET_MQ_queue_for_callbacks (&mq_send,
1482 switch (queue->address->sa_family)
1485 GNUNET_asprintf (&foreign_addr,
1487 COMMUNICATOR_ADDRESS_PREFIX,
1488 GNUNET_a2s (queue->address, queue->address_len));
1492 GNUNET_asprintf (&foreign_addr,
1494 COMMUNICATOR_ADDRESS_PREFIX,
1495 GNUNET_a2s (queue->address, queue->address_len));
1501 queue->qh = GNUNET_TRANSPORT_communicator_mq_add (ch,
1508 GNUNET_free (foreign_addr);
1514 * Generate and transmit our ephemeral key and the signature for
1515 * the initial KX with the other peer. Must be called first, before
1516 * any other bytes are ever written to the output buffer. Note that
1517 * our cipher must already be initialized when calling this function.
1518 * Helper function for #start_initial_kx_out().
1520 * @param queue queue to do KX for
1521 * @param epub our public key for the KX
1524 transmit_kx (struct Queue *queue,
1525 const struct GNUNET_CRYPTO_EcdhePublicKey *epub)
1527 struct TcpHandshakeSignature ths;
1528 struct TCPConfirmation tc;
1530 memcpy (queue->cwrite_buf, epub, sizeof(*epub));
1531 queue->cwrite_off = sizeof(epub);
1532 /* compute 'tc' and append in encrypted format to cwrite_buf */
1533 tc.sender = my_identity;
1535 GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1536 ths.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE);
1537 ths.purpose.size = htonl (sizeof(ths));
1538 ths.sender = my_identity;
1539 ths.receiver = queue->target;
1540 ths.ephemeral = *epub;
1541 ths.monotonic_time = tc.monotonic_time;
1542 GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_private_key,
1546 gcry_cipher_encrypt (queue->out_cipher,
1547 &queue->cwrite_buf[queue->cwrite_off],
1551 queue->cwrite_off += sizeof(tc);
1556 * Initialize our key material for outgoing transmissions and
1557 * inform the other peer about it. Must be called first before
1560 * @param queue the queue to setup
1563 start_initial_kx_out (struct Queue *queue)
1565 struct GNUNET_CRYPTO_EcdhePublicKey epub;
1567 GNUNET_assert (GNUNET_OK ==
1568 GNUNET_CRYPTO_ecdhe_key_create2 (&queue->ephemeral));
1569 GNUNET_CRYPTO_ecdhe_key_get_public (&queue->ephemeral, &epub);
1570 setup_out_cipher (queue);
1571 transmit_kx (queue, &epub);
1576 * We have received the first bytes from the other side on a @a queue.
1577 * Decrypt the @a tc contained in @a ibuf and check the signature.
1578 * Note that #setup_in_cipher() must have already been called.
1580 * @param queue queue to decrypt initial bytes from other peer for
1581 * @param tc[out] where to store the result
1582 * @param ibuf incoming data, of size
1584 * @return #GNUNET_OK if the signature was OK, #GNUNET_SYSERR if not
1587 decrypt_and_check_tc (struct Queue *queue,
1588 struct TCPConfirmation *tc,
1591 struct TcpHandshakeSignature ths;
1595 gcry_cipher_decrypt (queue->in_cipher,
1598 &ibuf[sizeof(struct GNUNET_CRYPTO_EcdhePublicKey)],
1600 ths.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE);
1601 ths.purpose.size = htonl (sizeof(ths));
1602 ths.sender = tc->sender;
1603 ths.receiver = my_identity;
1604 memcpy (&ths.ephemeral, ibuf, sizeof(struct GNUNET_CRYPTO_EcdhePublicKey));
1605 ths.monotonic_time = tc->monotonic_time;
1606 /* FIXME: check monotonic time against previous mono times
1607 from this sender! */
1608 return GNUNET_CRYPTO_eddsa_verify (
1609 GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE,
1612 &tc->sender.public_key);
1617 * Closes socket and frees memory associated with @a pq.
1619 * @param pq proto queue to free
1622 free_proto_queue (struct ProtoQueue *pq)
1624 GNUNET_NETWORK_socket_close (pq->sock);
1625 GNUNET_free (pq->address);
1626 GNUNET_CONTAINER_DLL_remove (proto_head, proto_tail, pq);
1632 * Read from the socket of the proto queue until we have enough data
1633 * to upgrade to full queue.
1635 * @param cls a `struct ProtoQueue`
1638 proto_read_kx (void *cls)
1640 struct ProtoQueue *pq = cls;
1642 struct GNUNET_TIME_Relative left;
1643 struct Queue *queue;
1644 struct TCPConfirmation tc;
1646 pq->read_task = NULL;
1647 left = GNUNET_TIME_absolute_get_remaining (pq->timeout);
1648 if (0 == left.rel_value_us)
1650 free_proto_queue (pq);
1653 rcvd = GNUNET_NETWORK_socket_recv (pq->sock,
1654 &pq->ibuf[pq->ibuf_off],
1655 sizeof(pq->ibuf) - pq->ibuf_off);
1658 if ((EAGAIN != errno) && (EINTR != errno))
1660 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "recv");
1661 free_proto_queue (pq);
1666 GNUNET_SCHEDULER_add_read_net (left, pq->sock, &proto_read_kx, pq);
1669 pq->ibuf_off += rcvd;
1670 if (pq->ibuf_off > sizeof(pq->ibuf))
1674 GNUNET_SCHEDULER_add_read_net (left, pq->sock, &proto_read_kx, pq);
1677 /* we got all the data, let's find out who we are talking to! */
1678 queue = GNUNET_new (struct Queue);
1679 setup_in_cipher ((const struct GNUNET_CRYPTO_EcdhePublicKey *) pq->ibuf,
1681 if (GNUNET_OK != decrypt_and_check_tc (queue, &tc, pq->ibuf))
1683 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1684 "Invalid TCP KX received from %s\n",
1685 GNUNET_a2s (queue->address, queue->address_len));
1686 gcry_cipher_close (queue->in_cipher);
1687 GNUNET_free (queue);
1688 free_proto_queue (pq);
1691 queue->address = pq->address; /* steals reference */
1692 queue->address_len = pq->address_len;
1693 queue->target = tc.sender;
1694 start_initial_kx_out (queue);
1695 boot_queue (queue, GNUNET_TRANSPORT_CS_INBOUND);
1697 GNUNET_SCHEDULER_add_read_net (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1702 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1706 GNUNET_CONTAINER_DLL_remove (proto_head, proto_tail, pq);
1712 * We have been notified that our listen socket has something to
1713 * read. Do the read and reschedule this function to be called again
1714 * once more is available.
1719 listen_cb (void *cls)
1721 struct sockaddr_storage in;
1723 struct GNUNET_NETWORK_Handle *sock;
1724 struct ProtoQueue *pq;
1727 GNUNET_assert (NULL != listen_sock);
1728 addrlen = sizeof(in);
1729 memset (&in, 0, sizeof(in));
1730 sock = GNUNET_NETWORK_socket_accept (listen_sock,
1731 (struct sockaddr *) &in,
1733 if ((NULL == sock) && ((EMFILE == errno) || (ENFILE == errno)))
1734 return; /* system limit reached, wait until connection goes down */
1735 listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1739 if ((NULL == sock) && ((EAGAIN == errno) || (ENOBUFS == errno)))
1743 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "accept");
1746 pq = GNUNET_new (struct ProtoQueue);
1747 pq->address_len = addrlen;
1748 pq->address = GNUNET_memdup (&in, addrlen);
1749 pq->timeout = GNUNET_TIME_relative_to_absolute (PROTO_QUEUE_TIMEOUT);
1751 pq->read_task = GNUNET_SCHEDULER_add_read_net (PROTO_QUEUE_TIMEOUT,
1755 GNUNET_CONTAINER_DLL_insert (proto_head, proto_tail, pq);
1760 * Read from the socket of the queue until we have enough data
1761 * to initialize the decryption logic and can switch to regular
1764 * @param cls a `struct Queue`
1767 queue_read_kx (void *cls)
1769 struct Queue *queue = cls;
1771 struct GNUNET_TIME_Relative left;
1772 struct TCPConfirmation tc;
1774 queue->read_task = NULL;
1775 left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
1776 if (0 == left.rel_value_us)
1778 queue_destroy (queue);
1781 rcvd = GNUNET_NETWORK_socket_recv (queue->sock,
1782 &queue->cread_buf[queue->cread_off],
1783 BUF_SIZE - queue->cread_off);
1786 if ((EAGAIN != errno) && (EINTR != errno))
1788 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "recv");
1789 queue_destroy (queue);
1793 GNUNET_SCHEDULER_add_read_net (left, queue->sock, &queue_read_kx, queue);
1796 queue->cread_off += rcvd;
1797 if (queue->cread_off < INITIAL_KX_SIZE)
1801 GNUNET_SCHEDULER_add_read_net (left, queue->sock, &queue_read_kx, queue);
1804 /* we got all the data, let's find out who we are talking to! */
1805 setup_in_cipher ((const struct GNUNET_CRYPTO_EcdhePublicKey *)
1808 if (GNUNET_OK != decrypt_and_check_tc (queue, &tc, queue->cread_buf))
1810 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1811 "Invalid TCP KX received from %s\n",
1812 GNUNET_a2s (queue->address, queue->address_len));
1813 queue_destroy (queue);
1817 memcmp (&tc.sender, &queue->target, sizeof(struct GNUNET_PeerIdentity)))
1819 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1820 "Invalid sender in TCP KX received from %s\n",
1821 GNUNET_a2s (queue->address, queue->address_len));
1822 queue_destroy (queue);
1826 /* update queue timeout */
1827 reschedule_queue_timeout (queue);
1828 /* prepare to continue with regular read task immediately */
1829 memmove (queue->cread_buf,
1830 &queue->cread_buf[INITIAL_KX_SIZE],
1831 queue->cread_off - (INITIAL_KX_SIZE));
1832 queue->cread_off -= INITIAL_KX_SIZE;
1833 queue->read_task = GNUNET_SCHEDULER_add_now (&queue_read, queue);
1838 * Function called by the transport service to initialize a
1839 * message queue given address information about another peer.
1840 * If and when the communication channel is established, the
1841 * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
1842 * to notify the service that the channel is now up. It is
1843 * the responsibility of the communicator to manage sane
1844 * retries and timeouts for any @a peer/@a address combination
1845 * provided by the transport service. Timeouts and retries
1846 * do not need to be signalled to the transport service.
1848 * @param cls closure
1849 * @param peer identity of the other peer
1850 * @param address where to send the message, human-readable
1851 * communicator-specific format, 0-terminated, UTF-8
1852 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is
1856 mq_init (void *cls, const struct GNUNET_PeerIdentity *peer, const char *address)
1858 struct Queue *queue;
1860 struct sockaddr *in;
1862 struct GNUNET_NETWORK_Handle *sock;
1864 if (0 != strncmp (address,
1865 COMMUNICATOR_ADDRESS_PREFIX "-",
1866 strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
1868 GNUNET_break_op (0);
1869 return GNUNET_SYSERR;
1871 path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
1872 in = tcp_address_to_sockaddr (path, &in_len);
1874 sock = GNUNET_NETWORK_socket_create (in->sa_family, SOCK_STREAM, IPPROTO_TCP);
1877 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1878 "socket(%d) failed: %s",
1882 return GNUNET_SYSERR;
1884 if (GNUNET_OK != GNUNET_NETWORK_socket_connect (sock, in, in_len))
1886 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1887 "connect to `%s' failed: %s",
1890 GNUNET_NETWORK_socket_close (sock);
1892 return GNUNET_SYSERR;
1895 queue = GNUNET_new (struct Queue);
1896 queue->target = *peer;
1897 queue->address = in;
1898 queue->address_len = in_len;
1900 boot_queue (queue, GNUNET_TRANSPORT_CS_OUTBOUND);
1902 GNUNET_SCHEDULER_add_read_net (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1906 start_initial_kx_out (queue);
1908 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1917 * Iterator over all message queues to clean up.
1920 * @param target unused
1921 * @param value the queue to destroy
1922 * @return #GNUNET_OK to continue to iterate
1925 get_queue_delete_it (void *cls,
1926 const struct GNUNET_PeerIdentity *target,
1929 struct Queue *queue = value;
1933 queue_destroy (queue);
1939 * Shutdown the UNIX communicator.
1941 * @param cls NULL (always)
1944 do_shutdown (void *cls)
1946 while (NULL != proto_head)
1947 free_proto_queue (proto_head);
1950 GNUNET_NAT_unregister (nat);
1953 if (NULL != listen_task)
1955 GNUNET_SCHEDULER_cancel (listen_task);
1958 if (NULL != listen_sock)
1960 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (listen_sock));
1963 GNUNET_CONTAINER_multipeermap_iterate (queue_map, &get_queue_delete_it, NULL);
1964 GNUNET_CONTAINER_multipeermap_destroy (queue_map);
1967 GNUNET_TRANSPORT_communicator_disconnect (ch);
1972 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1975 if (NULL != my_private_key)
1977 GNUNET_free (my_private_key);
1978 my_private_key = NULL;
1982 GNUNET_NT_scanner_done (is);
1989 * Function called when the transport service has received an
1990 * acknowledgement for this communicator (!) via a different return
1993 * Not applicable for TCP.
1995 * @param cls closure
1996 * @param sender which peer sent the notification
1997 * @param msg payload
2000 enc_notify_cb (void *cls,
2001 const struct GNUNET_PeerIdentity *sender,
2002 const struct GNUNET_MessageHeader *msg)
2007 GNUNET_break_op (0);
2012 * Signature of the callback passed to #GNUNET_NAT_register() for
2013 * a function to call whenever our set of 'valid' addresses changes.
2015 * @param cls closure
2016 * @param app_ctx[in,out] location where the app can store stuff
2017 * on add and retrieve it on remove
2018 * @param add_remove #GNUNET_YES to add a new public IP address,
2019 * #GNUNET_NO to remove a previous (now invalid) one
2020 * @param ac address class the address belongs to
2021 * @param addr either the previous or the new public IP address
2022 * @param addrlen actual length of the @a addr
2025 nat_address_cb (void *cls,
2028 enum GNUNET_NAT_AddressClass ac,
2029 const struct sockaddr *addr,
2033 struct GNUNET_TRANSPORT_AddressIdentifier *ai;
2035 if (GNUNET_YES == add_remove)
2037 enum GNUNET_NetworkType nt;
2039 GNUNET_asprintf (&my_addr,
2041 COMMUNICATOR_ADDRESS_PREFIX,
2042 GNUNET_a2s (addr, addrlen));
2043 nt = GNUNET_NT_scanner_get_type (is, addr, addrlen);
2045 GNUNET_TRANSPORT_communicator_address_add (ch,
2048 GNUNET_TIME_UNIT_FOREVER_REL);
2049 GNUNET_free (my_addr);
2055 GNUNET_TRANSPORT_communicator_address_remove (ai);
2062 * Setup communicator and launch network interactions.
2064 * @param cls NULL (always)
2065 * @param args remaining command-line arguments
2066 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2067 * @param c configuration
2072 const char *cfgfile,
2073 const struct GNUNET_CONFIGURATION_Handle *c)
2076 struct sockaddr *in;
2078 struct sockaddr_storage in_sto;
2084 GNUNET_CONFIGURATION_get_value_filename (cfg,
2085 COMMUNICATOR_CONFIG_SECTION,
2089 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2090 COMMUNICATOR_CONFIG_SECTION,
2095 GNUNET_CONFIGURATION_get_value_number (cfg,
2096 COMMUNICATOR_CONFIG_SECTION,
2099 max_queue_length = DEFAULT_MAX_QUEUE_LENGTH;
2101 in = tcp_address_to_sockaddr (bindto, &in_len);
2104 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2105 "Failed to setup TCP socket address with path `%s'\n",
2107 GNUNET_free (bindto);
2111 GNUNET_NETWORK_socket_create (in->sa_family, SOCK_STREAM, IPPROTO_TCP);
2112 if (NULL == listen_sock)
2114 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
2116 GNUNET_free (bindto);
2119 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (listen_sock, in, in_len))
2121 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "bind", bindto);
2122 GNUNET_NETWORK_socket_close (listen_sock);
2125 GNUNET_free (bindto);
2128 /* We might have bound to port 0, allowing the OS to figure it out;
2129 thus, get the real IN-address from the socket */
2130 sto_len = sizeof(in_sto);
2131 if (0 != getsockname (GNUNET_NETWORK_get_fd (listen_sock),
2132 (struct sockaddr *) &in_sto,
2135 memcpy (&in_sto, in, in_len);
2139 GNUNET_free (bindto);
2140 in = (struct sockaddr *) &in_sto;
2142 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2144 GNUNET_a2s ((const struct sockaddr *) &in_sto, sto_len));
2145 stats = GNUNET_STATISTICS_create ("C-TCP", cfg);
2146 GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
2147 is = GNUNET_NT_scanner_init ();
2148 my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
2149 if (NULL == my_private_key)
2152 GNUNET_ERROR_TYPE_ERROR,
2154 "Transport service is lacking key configuration settings. Exiting.\n"));
2155 GNUNET_SCHEDULER_shutdown ();
2158 GNUNET_CRYPTO_eddsa_key_get_public (my_private_key, &my_identity.public_key);
2159 /* start listening */
2160 listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2164 queue_map = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
2165 ch = GNUNET_TRANSPORT_communicator_connect (cfg,
2166 COMMUNICATOR_CONFIG_SECTION,
2167 COMMUNICATOR_ADDRESS_PREFIX,
2168 GNUNET_TRANSPORT_CC_RELIABLE,
2176 GNUNET_SCHEDULER_shutdown ();
2179 nat = GNUNET_NAT_register (cfg,
2180 COMMUNICATOR_CONFIG_SECTION,
2182 1 /* one address */,
2183 (const struct sockaddr **) &in,
2186 NULL /* FIXME: support reversal: #5529 */,
2187 NULL /* closure */);
2192 * The main function for the UNIX communicator.
2194 * @param argc number of arguments from the command line
2195 * @param argv command line arguments
2196 * @return 0 ok, 1 on error
2199 main (int argc, char *const *argv)
2201 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2202 GNUNET_GETOPT_OPTION_END
2206 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
2209 ret = (GNUNET_OK == GNUNET_PROGRAM_run (argc,
2211 "gnunet-communicator-tcp",
2212 _ ("GNUnet TCP communicator"),
2218 GNUNET_free ((void *) argv);
2223 /* end of gnunet-communicator-tcp.c */