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 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 4)
52 * How many messages do we keep at most in the queue to the
53 * transport service before we start to drop (default,
54 * can be changed via the configuration file).
55 * Should be _below_ the level of the communicator API, as
56 * otherwise we may read messages just to have them dropped
57 * by the communicator API.
59 #define DEFAULT_MAX_QUEUE_LENGTH 8
62 * Size of our IO buffers for ciphertext data. Must be at
63 * least UINT_MAX + sizeof (struct TCPBox).
65 #define BUF_SIZE (2 * 64 * 1024 + sizeof (struct TCPBox))
68 * How often do we rekey based on time (at least)
70 #define REKEY_TIME_INTERVAL GNUNET_TIME_UNIT_DAYS
73 * How long do we wait until we must have received the initial KX?
75 #define PROTO_QUEUE_TIMEOUT GNUNET_TIME_UNIT_MINUTES
78 * How often do we rekey based on number of bytes transmitted?
79 * (additionally randomized).
81 #define REKEY_MAX_BYTES (1024LLU * 1024 * 1024 * 4LLU)
84 * Size of the initial key exchange message sent first in both
87 #define INITIAL_KX_SIZE (sizeof (struct GNUNET_CRYPTO_EcdhePublicKey)+sizeof (struct TCPConfirmation))
91 * Address prefix used by the communicator.
93 #define COMMUNICATOR_ADDRESS_PREFIX "tcp"
96 * Configuration section used by the communicator.
98 #define COMMUNICATOR_CONFIG_SECTION "communicator-tcp"
100 GNUNET_NETWORK_STRUCT_BEGIN
104 * Signature we use to verify that the ephemeral key was really chosen by
105 * the specified sender.
107 struct TcpHandshakeSignature
110 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE
112 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
115 * Identity of the inititor of the TCP connection (TCP client).
117 struct GNUNET_PeerIdentity sender;
120 * Presumed identity of the target of the TCP connection (TCP server)
122 struct GNUNET_PeerIdentity receiver;
125 * Ephemeral key used by the @e sender.
127 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
130 * Monotonic time of @e sender, to possibly help detect replay attacks
131 * (if receiver persists times by sender).
133 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
138 * Encrypted continuation of TCP initial handshake.
140 struct TCPConfirmation
145 struct GNUNET_PeerIdentity sender;
148 * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE
150 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
153 * Monotonic time of @e sender, to possibly help detect replay attacks
154 * (if receiver persists times by sender).
156 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
162 * TCP message box. Always sent encrypted!
168 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX. Warning: the
169 * header size EXCLUDES the size of the `struct TCPBox`. We usually
170 * never do this, but here the payload may truly be 64k *after* the
171 * TCPBox (as we have no MTU)!!
173 struct GNUNET_MessageHeader header;
176 * HMAC for the following encrypted message. Yes, we MUST use
177 * mac-then-encrypt here, as we want to hide the message sizes on
178 * the wire (zero plaintext design!). Using CTR mode padding oracle
179 * attacks do not apply. Besides, due to the use of ephemeral keys
180 * (hopefully with effective replay protection from monotonic time!)
181 * the attacker is limited in using the oracle.
183 struct GNUNET_ShortHashCode hmac;
185 /* followed by as may bytes of payload as indicated in @e header,
186 excluding the TCPBox itself! */
192 * TCP rekey message box. Always sent encrypted! Data after
193 * this message will use the new key.
199 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY.
201 struct GNUNET_MessageHeader header;
204 * HMAC for the following encrypted message. Yes, we MUST use
205 * mac-then-encrypt here, as we want to hide the message sizes on
206 * the wire (zero plaintext design!). Using CTR mode padding oracle
207 * attacks do not apply. Besides, due to the use of ephemeral keys
208 * (hopefully with effective replay protection from monotonic time!)
209 * the attacker is limited in using the oracle.
211 struct GNUNET_ShortHashCode hmac;
216 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
219 * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY
221 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
224 * Monotonic time of @e sender, to possibly help detect replay attacks
225 * (if receiver persists times by sender).
227 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
233 * TCP finish. Sender asks for the connection to be closed.
234 * Needed/useful in case we drop RST/FIN packets on the GNUnet
235 * port due to the possibility of malicious RST/FIN injection.
241 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH.
243 struct GNUNET_MessageHeader header;
246 * HMAC for the following encrypted message. Yes, we MUST use
247 * mac-then-encrypt here, as we want to hide the message sizes on
248 * the wire (zero plaintext design!). Using CTR mode padding oracle
249 * attacks do not apply. Besides, due to the use of ephemeral keys
250 * (hopefully with effective replay protection from monotonic time!)
251 * the attacker is limited in using the oracle.
253 struct GNUNET_ShortHashCode hmac;
258 GNUNET_NETWORK_STRUCT_END
262 * Handle for a queue.
268 * To whom are we talking to.
270 struct GNUNET_PeerIdentity target;
273 * socket that we transmit all data with on this queue
275 struct GNUNET_NETWORK_Handle *sock;
278 * cipher for decryption of incoming data.
280 gcry_cipher_hd_t in_cipher;
283 * cipher for encryption of outgoing data.
285 gcry_cipher_hd_t out_cipher;
288 * Shared secret for HMAC verification on incoming data.
290 struct GNUNET_HashCode in_hmac;
293 * Shared secret for HMAC generation on outgoing data, ratcheted after
296 struct GNUNET_HashCode out_hmac;
299 * Our ephemeral key. Stored here temporarily during rekeying / key generation.
301 struct GNUNET_CRYPTO_EcdhePrivateKey ephemeral;
304 * ID of read task for this connection.
306 struct GNUNET_SCHEDULER_Task *read_task;
309 * ID of write task for this connection.
311 struct GNUNET_SCHEDULER_Task *write_task;
314 * Address of the other peer.
316 struct sockaddr *address;
319 * How many more bytes may we sent with the current @e out_cipher
320 * before we should rekey?
322 uint64_t rekey_left_bytes;
325 * Until what time may we sent with the current @e out_cipher
326 * before we should rekey?
328 struct GNUNET_TIME_Absolute rekey_time;
331 * Length of the address.
333 socklen_t address_len;
336 * Message queue we are providing for the #ch.
338 struct GNUNET_MQ_Handle *mq;
341 * handle for this queue with the #ch.
343 struct GNUNET_TRANSPORT_QueueHandle *qh;
346 * Number of bytes we currently have in our write queue.
348 unsigned long long bytes_in_queue;
351 * Buffer for reading ciphertext from network into.
353 char cread_buf[BUF_SIZE];
356 * buffer for writing ciphertext to network.
358 char cwrite_buf[BUF_SIZE];
361 * Plaintext buffer for decrypted plaintext.
363 char pread_buf[UINT16_MAX + 1 + sizeof (struct TCPBox)];
366 * Plaintext buffer for messages to be encrypted.
368 char pwrite_buf[UINT16_MAX + 1 + sizeof (struct TCPBox)];
371 * At which offset in the ciphertext read buffer should we
372 * append more ciphertext for transmission next?
377 * At which offset in the ciphertext write buffer should we
378 * append more ciphertext from reading next?
383 * At which offset in the plaintext input buffer should we
384 * append more plaintext from decryption next?
389 * At which offset in the plaintext output buffer should we
390 * append more plaintext for encryption next?
395 * Timeout for this queue.
397 struct GNUNET_TIME_Absolute timeout;
400 * How may messages did we pass from this queue to CORE for which we
401 * have yet to receive an acknoweldgement that CORE is done with
402 * them? If "large" (or even just non-zero), we should throttle
403 * reading to provide flow control. See also #DEFAULT_MAX_QUEUE_LENGTH
404 * and #max_queue_length.
406 unsigned int backpressure;
409 * Which network type does this queue use?
411 enum GNUNET_NetworkType nt;
414 * Is MQ awaiting a #GNUNET_MQ_impl_send_continue() call?
416 int mq_awaits_continue;
419 * Did we enqueue a finish message and are closing down the queue?
424 * Did we technically destroy this queue, but kept the allocation
425 * around because of @e backpressure not being zero yet? Used
426 * simply to delay the final #GNUNET_free() operation until
427 * #core_read_finished_cb() has been called.
432 * #GNUNET_YES after #inject_key() placed the rekey message into the
433 * plaintext buffer. Once the plaintext buffer is drained, this
434 * means we must switch to the new key material.
439 * #GNUNET_YES if we just rekeyed and must thus possibly
440 * re-decrypt ciphertext.
447 * Handle for an incoming connection where we do not yet have enough
448 * information to setup a full queue.
456 struct ProtoQueue *next;
461 struct ProtoQueue *prev;
464 * socket that we transmit all data with on this queue
466 struct GNUNET_NETWORK_Handle *sock;
469 * ID of read task for this connection.
471 struct GNUNET_SCHEDULER_Task *read_task;
474 * Address of the other peer.
476 struct sockaddr *address;
479 * Length of the address.
481 socklen_t address_len;
484 * Timeout for this protoqueue.
486 struct GNUNET_TIME_Absolute timeout;
489 * Buffer for reading all the information we need to upgrade from
490 * protoqueue to queue.
492 char ibuf[INITIAL_KX_SIZE];
495 * Current offset for reading into @e ibuf.
504 static struct GNUNET_SCHEDULER_Task *listen_task;
507 * Maximum queue length before we stop reading towards the transport service.
509 static unsigned long long max_queue_length;
512 * For logging statistics.
514 static struct GNUNET_STATISTICS_Handle *stats;
519 static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
522 * Queues (map from peer identity to `struct Queue`)
524 static struct GNUNET_CONTAINER_MultiPeerMap *queue_map;
529 static struct GNUNET_NETWORK_Handle *listen_sock;
534 static struct GNUNET_PeerIdentity my_identity;
539 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
544 static const struct GNUNET_CONFIGURATION_Handle *cfg;
547 * Network scanner to determine network types.
549 static struct GNUNET_NT_InterfaceScanner *is;
552 * Connection to NAT service.
554 static struct GNUNET_NAT_Handle *nat;
557 * Protoqueues DLL head.
559 static struct ProtoQueue *proto_head;
562 * Protoqueues DLL tail.
564 static struct ProtoQueue *proto_tail;
568 * We have been notified that our listen socket has something to
569 * read. Do the read and reschedule this function to be called again
570 * once more is available.
575 listen_cb (void *cls);
579 * Functions with this signature are called whenever we need
580 * to close a queue due to a disconnect or failure to
581 * establish a connection.
583 * @param queue queue to close down
586 queue_destroy (struct Queue *queue)
588 struct GNUNET_MQ_Handle *mq;
590 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
591 "Disconnecting queue for peer `%s'\n",
592 GNUNET_i2s (&queue->target));
593 if (NULL != (mq = queue->mq))
596 GNUNET_MQ_destroy (mq);
598 if (NULL != queue->qh)
600 GNUNET_TRANSPORT_communicator_mq_del (queue->qh);
603 GNUNET_assert (GNUNET_YES ==
604 GNUNET_CONTAINER_multipeermap_remove (queue_map,
607 GNUNET_STATISTICS_set (stats,
609 GNUNET_CONTAINER_multipeermap_size (queue_map),
611 if (NULL != queue->read_task)
613 GNUNET_SCHEDULER_cancel (queue->read_task);
614 queue->read_task = NULL;
616 if (NULL != queue->write_task)
618 GNUNET_SCHEDULER_cancel (queue->write_task);
619 queue->write_task = NULL;
621 GNUNET_NETWORK_socket_close (queue->sock);
622 gcry_cipher_close (queue->in_cipher);
623 gcry_cipher_close (queue->out_cipher);
624 GNUNET_free (queue->address);
625 if (0 != queue->backpressure)
626 queue->destroyed = GNUNET_YES;
629 if (NULL == listen_task)
630 listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
638 * Compute @a mac over @a buf, and ratched the @a hmac_secret.
640 * @param[in,out] hmac_secret secret for HMAC calculation
641 * @param buf buffer to MAC
642 * @param buf_size number of bytes in @a buf
643 * @param smac[out] where to write the HMAC
646 calculate_hmac (struct GNUNET_HashCode *hmac_secret,
649 struct GNUNET_ShortHashCode *smac)
651 struct GNUNET_HashCode mac;
653 GNUNET_CRYPTO_hmac_raw (hmac_secret,
654 sizeof (struct GNUNET_HashCode),
658 /* truncate to `struct GNUNET_ShortHashCode` */
661 sizeof (struct GNUNET_ShortHashCode));
662 /* ratchet hmac key */
663 GNUNET_CRYPTO_hash (hmac_secret,
664 sizeof (struct GNUNET_HashCode),
670 * Append a 'finish' message to the outgoing transmission. Once the
671 * finish has been transmitted, destroy the queue.
673 * @param queue queue to shut down nicely
676 queue_finish (struct Queue *queue)
678 struct TCPFinish fin;
683 fin.header.size = htons (sizeof (fin));
684 fin.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH);
685 calculate_hmac (&queue->out_hmac,
689 /* if there is any message left in pwrite_buf, we
690 overwrite it (possibly dropping the last message
691 from CORE hard here) */
692 memcpy (queue->pwrite_buf,
695 queue->pwrite_off = sizeof (fin);
696 /* This flag will ensure that #queue_write() no longer
697 notifies CORE about the possibility of sending
698 more data, and that #queue_write() will call
699 #queue_destroy() once the @c fin was fully written. */
700 queue->finishing = GNUNET_YES;
705 * Increment queue timeout due to activity. We do not immediately
706 * notify the monitor here as that might generate excessive
709 * @param queue queue for which the timeout should be rescheduled
712 reschedule_queue_timeout (struct Queue *queue)
715 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
720 * Queue read task. If we hit the timeout, disconnect it
722 * @param cls the `struct Queue *` to disconnect
725 queue_read (void *cls);
729 * Core tells us it is done processing a message that transport
730 * received on a queue with status @a success.
732 * @param cls a `struct Queue *` where the message originally came from
733 * @param success #GNUNET_OK on success
736 core_read_finished_cb (void *cls,
739 struct Queue *queue = cls;
741 if (GNUNET_OK != success)
742 GNUNET_STATISTICS_update (stats,
743 "# messages lost in communicator API towards CORE",
746 queue->backpressure--;
747 /* handle deferred queue destruction */
748 if ( (queue->destroyed) &&
749 (0 == queue->backpressure) )
754 reschedule_queue_timeout (queue);
755 /* possibly unchoke reading, now that CORE made progress */
756 if (NULL == queue->read_task)
758 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining (queue->timeout),
766 * We received @a plaintext_len bytes of @a plaintext on @a queue.
767 * Pass it on to CORE. If transmission is actually happening,
768 * increase backpressure counter.
770 * @param queue the queue that received the plaintext
771 * @param plaintext the plaintext that was received
772 * @param plaintext_len number of bytes of plaintext received
775 pass_plaintext_to_core (struct Queue *queue,
776 const void *plaintext,
777 size_t plaintext_len)
779 const struct GNUNET_MessageHeader *hdr = plaintext;
782 if (ntohs (hdr->size) != plaintext_len)
784 /* NOTE: If we ever allow multiple CORE messages in one
785 BOX, this will have to change! */
789 ret = GNUNET_TRANSPORT_communicator_receive (ch,
792 ADDRESS_VALIDITY_PERIOD,
793 &core_read_finished_cb,
795 if (GNUNET_OK == ret)
796 queue->backpressure++;
797 GNUNET_break (GNUNET_NO != ret); /* backpressure not working!? */
798 if (GNUNET_SYSERR == ret)
799 GNUNET_STATISTICS_update (stats,
800 "# bytes lost due to CORE not running",
807 * Setup @a cipher based on shared secret @a dh and decrypting
810 * @param dh shared secret
811 * @param pid decrypting peer's identity
812 * @param cipher[out] cipher to initialize
813 * @param hmac_key[out] HMAC key to initialize
816 setup_cipher (const struct GNUNET_HashCode *dh,
817 const struct GNUNET_PeerIdentity *pid,
818 gcry_cipher_hd_t *cipher,
819 struct GNUNET_HashCode *hmac_key)
824 gcry_cipher_open (cipher,
825 GCRY_CIPHER_AES256 /* low level: go for speed */,
826 GCRY_CIPHER_MODE_CTR,
828 GNUNET_assert (GNUNET_YES ==
829 GNUNET_CRYPTO_kdf (key,
838 gcry_cipher_setkey (*cipher,
841 GNUNET_assert (GNUNET_YES ==
842 GNUNET_CRYPTO_kdf (ctr,
851 gcry_cipher_setctr (*cipher,
854 GNUNET_assert (GNUNET_YES ==
855 GNUNET_CRYPTO_kdf (hmac_key,
856 sizeof (struct GNUNET_HashCode),
868 * Setup cipher of @a queue for decryption.
870 * @param ephemeral ephemeral key we received from the other peer
871 * @param queue[in,out] queue to initialize decryption cipher for
874 setup_in_cipher (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
877 struct GNUNET_HashCode dh;
879 GNUNET_CRYPTO_eddsa_ecdh (my_private_key,
890 * Handle @a rekey message on @a queue. The message was already
891 * HMAC'ed, but we should additionally still check the signature.
892 * Then we need to stop the old cipher and start afresh.
894 * @param queue the queue @a rekey was received on
895 * @param rekey the rekey message
898 do_rekey (struct Queue *queue,
899 const struct TCPRekey *rekey)
901 struct TcpHandshakeSignature thp;
903 thp.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY);
904 thp.purpose.size = htonl (sizeof (thp));
905 thp.sender = queue->target;
906 thp.receiver = my_identity;
907 thp.ephemeral = rekey->ephemeral;
908 thp.monotonic_time = rekey->monotonic_time;
910 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY,
913 &queue->target.public_key))
916 queue_finish (queue);
919 gcry_cipher_close (queue->in_cipher);
920 queue->rekeyed = GNUNET_YES;
921 setup_in_cipher (&rekey->ephemeral,
927 * Test if we have received a full message in plaintext.
930 * @param queue queue to process inbound plaintext for
931 * @return number of bytes of plaintext handled, 0 for none
934 try_handle_plaintext (struct Queue *queue)
936 const struct GNUNET_MessageHeader *hdr
937 = (const struct GNUNET_MessageHeader *) queue->pread_buf;
938 const struct TCPBox *box
939 = (const struct TCPBox *) queue->pread_buf;
940 const struct TCPRekey *rekey
941 = (const struct TCPRekey *) queue->pread_buf;
942 const struct TCPFinish *fin
943 = (const struct TCPFinish *) queue->pread_buf;
944 struct TCPRekey rekeyz;
945 struct TCPFinish finz;
946 struct GNUNET_ShortHashCode tmac;
948 size_t size = 0; /* make compiler happy */
950 if (sizeof (*hdr) > queue->pread_off)
951 return 0; /* not even a header */
952 type = ntohs (hdr->type);
955 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX:
956 /* Special case: header size excludes box itself! */
957 if (ntohs (hdr->size) + sizeof (struct TCPBox) > queue->pread_off)
959 calculate_hmac (&queue->in_hmac,
963 if (0 != memcmp (&tmac,
968 queue_finish (queue);
971 pass_plaintext_to_core (queue,
972 (const void *) &box[1],
974 size = ntohs (hdr->size) + sizeof (*box);
976 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY:
977 if (sizeof (*rekey) > queue->pread_off)
979 if (ntohs (hdr->size) != sizeof (*rekey))
982 queue_finish (queue);
986 memset (&rekeyz.hmac,
988 sizeof (rekeyz.hmac));
989 calculate_hmac (&queue->in_hmac,
993 if (0 != memcmp (&tmac,
998 queue_finish (queue);
1003 size = ntohs (hdr->size);
1005 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH:
1006 if (sizeof (*fin) > queue->pread_off)
1008 if (ntohs (hdr->size) != sizeof (*fin))
1010 GNUNET_break_op (0);
1011 queue_finish (queue);
1017 sizeof (finz.hmac));
1018 calculate_hmac (&queue->in_hmac,
1022 if (0 != memcmp (&tmac,
1026 GNUNET_break_op (0);
1027 queue_finish (queue);
1030 /* handle FINISH by destroying queue */
1031 queue_destroy (queue);
1034 GNUNET_break_op (0);
1035 queue_finish (queue);
1038 GNUNET_assert (0 != size);
1044 * Queue read task. If we hit the timeout, disconnect it
1046 * @param cls the `struct Queue *` to disconnect
1049 queue_read (void *cls)
1051 struct Queue *queue = cls;
1052 struct GNUNET_TIME_Relative left;
1055 queue->read_task = NULL;
1056 rcvd = GNUNET_NETWORK_socket_recv (queue->sock,
1057 &queue->cread_buf[queue->cread_off],
1058 BUF_SIZE - queue->cread_off);
1061 if ( (EAGAIN != errno) &&
1064 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1066 queue_finish (queue);
1071 = GNUNET_SCHEDULER_add_read_net (left,
1078 reschedule_queue_timeout (queue);
1079 queue->cread_off += rcvd;
1080 while ( (queue->pread_off < sizeof (queue->pread_buf)) &&
1081 (queue->cread_off > 0) )
1083 size_t max = GNUNET_MIN (sizeof (queue->pread_buf) - queue->pread_off,
1089 gcry_cipher_decrypt (queue->in_cipher,
1090 &queue->pread_buf[queue->pread_off],
1094 queue->pread_off += max;
1096 while ( (GNUNET_NO == queue->rekeyed) &&
1097 (0 != (done = try_handle_plaintext (queue))) )
1099 /* 'done' bytes of plaintext were used, shift buffer */
1100 GNUNET_assert (done <= queue->pread_off);
1101 /* NOTE: this memmove() could possibly sometimes be
1102 avoided if we pass 'total' into try_handle_plaintext()
1103 and use it at an offset into the buffer there! */
1104 memmove (queue->pread_buf,
1105 &queue->pread_buf[done],
1106 queue->pread_off - done);
1107 queue->pread_off -= done;
1110 /* when we encounter a rekey message, the decryption above uses the
1111 wrong key for everything after the rekey; in that case, we have
1112 to re-do the decryption at 'total' instead of at 'max'. If there
1113 is no rekey and the last message is incomplete (max > total),
1114 it is safe to keep the decryption so we shift by 'max' */
1115 if (GNUNET_YES == queue->rekeyed)
1118 queue->rekeyed = GNUNET_NO;
1120 memmove (queue->cread_buf,
1121 &queue->cread_buf[max],
1122 queue->cread_off - max);
1123 queue->cread_off -= max;
1126 if (BUF_SIZE == queue->cread_off)
1127 return; /* buffer full, suspend reading */
1128 left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
1129 if (0 != left.rel_value_us)
1131 if (max_queue_length < queue->backpressure)
1133 /* continue reading */
1135 = GNUNET_SCHEDULER_add_read_net (left,
1142 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1143 "Queue %p was idle for %s, disconnecting\n",
1145 GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1147 queue_finish (queue);
1152 * Convert TCP bind specification to a `struct sockaddr *`
1154 * @param bindto bind specification to convert
1155 * @param[out] sock_len set to the length of the address
1156 * @return converted bindto specification
1158 static struct sockaddr *
1159 tcp_address_to_sockaddr (const char *bindto,
1160 socklen_t *sock_len)
1162 struct sockaddr *in;
1168 if (1 == SSCANF (bindto,
1173 /* interpreting value as just a PORT number */
1174 if (port > UINT16_MAX)
1176 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1177 "BINDTO specification `%s' invalid: value too large for port\n",
1182 GNUNET_NETWORK_test_pf (PF_INET6)) ||
1184 GNUNET_CONFIGURATION_get_value_yesno (cfg,
1185 COMMUNICATOR_CONFIG_SECTION,
1188 struct sockaddr_in *i4;
1190 i4 = GNUNET_malloc (sizeof (struct sockaddr_in));
1191 i4->sin_family = AF_INET;
1192 i4->sin_port = htons ((uint16_t) port);
1193 *sock_len = sizeof (struct sockaddr_in);
1194 in = (struct sockaddr *) i4;
1198 struct sockaddr_in6 *i6;
1200 i6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
1201 i6->sin6_family = AF_INET6;
1202 i6->sin6_port = htons ((uint16_t) port);
1203 *sock_len = sizeof (struct sockaddr_in6);
1204 in = (struct sockaddr *) i6;
1208 cp = GNUNET_strdup (bindto);
1209 colon = strrchr (cp, ':');
1212 /* interpet value after colon as port */
1215 if (1 == SSCANF (colon,
1220 /* interpreting value as just a PORT number */
1221 if (port > UINT16_MAX)
1223 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1224 "BINDTO specification `%s' invalid: value too large for port\n",
1232 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1233 "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1241 /* interpret missing port as 0, aka pick any free one */
1246 struct sockaddr_in v4;
1248 if (1 == inet_pton (AF_INET,
1252 v4.sin_port = htons ((uint16_t) port);
1253 in = GNUNET_memdup (&v4,
1255 *sock_len = sizeof (v4);
1262 struct sockaddr_in6 v6;
1266 if ( ('[' == *cp) &&
1267 (']' == cp[strlen (cp)-1]) )
1269 start++; /* skip over '[' */
1270 cp[strlen (cp) -1] = '\0'; /* eat ']' */
1272 if (1 == inet_pton (AF_INET6,
1276 v6.sin6_port = htons ((uint16_t) port);
1277 in = GNUNET_memdup (&v6,
1279 *sock_len = sizeof (v6);
1284 /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1291 * Setup cipher for outgoing data stream based on target and
1292 * our ephemeral private key.
1294 * @param queue queue to setup outgoing (encryption) cipher for
1297 setup_out_cipher (struct Queue *queue)
1299 struct GNUNET_HashCode dh;
1301 GNUNET_CRYPTO_ecdh_eddsa (&queue->ephemeral,
1302 &queue->target.public_key,
1304 /* we don't need the private key anymore, drop it! */
1305 memset (&queue->ephemeral,
1307 sizeof (queue->ephemeral));
1312 queue->rekey_time = GNUNET_TIME_relative_to_absolute (REKEY_TIME_INTERVAL);
1313 queue->rekey_left_bytes = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
1319 * Inject a `struct TCPRekey` message into the queue's plaintext
1322 * @param queue queue to perform rekeying on
1325 inject_rekey (struct Queue *queue)
1327 struct TCPRekey rekey;
1328 struct TcpHandshakeSignature thp;
1330 GNUNET_assert (0 == queue->pwrite_off);
1334 GNUNET_assert (GNUNET_OK ==
1335 GNUNET_CRYPTO_ecdhe_key_create2 (&queue->ephemeral));
1336 rekey.header.type = ntohs (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY);
1337 rekey.header.size = ntohs (sizeof (rekey));
1338 GNUNET_CRYPTO_ecdhe_key_get_public (&queue->ephemeral,
1340 rekey.monotonic_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1341 thp.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY);
1342 thp.purpose.size = htonl (sizeof (thp));
1343 thp.sender = my_identity;
1344 thp.receiver = queue->target;
1345 thp.ephemeral = rekey.ephemeral;
1346 thp.monotonic_time = rekey.monotonic_time;
1347 GNUNET_assert (GNUNET_OK ==
1348 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1350 &rekey.sender_sig));
1351 calculate_hmac (&queue->out_hmac,
1355 memcpy (queue->pwrite_buf,
1358 queue->rekey_state = GNUNET_YES;
1363 * We encrypted the rekey message, now update actually swap the key
1364 * material and update the key freshness parameters of @a queue.
1367 switch_key (struct Queue *queue)
1369 queue->rekey_state = GNUNET_NO;
1370 gcry_cipher_close (queue->out_cipher);
1371 setup_out_cipher (queue);
1376 * We have been notified that our socket is ready to write.
1377 * Then reschedule this function to be called again once more is available.
1379 * @param cls a `struct Queue`
1382 queue_write (void *cls)
1384 struct Queue *queue = cls;
1387 queue->write_task = NULL;
1388 sent = GNUNET_NETWORK_socket_send (queue->sock,
1391 if ( (-1 == sent) &&
1392 (EAGAIN != errno) &&
1395 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1397 queue_destroy (queue);
1402 size_t usent = (size_t) sent;
1404 memmove (queue->cwrite_buf,
1405 &queue->cwrite_buf[usent],
1406 queue->cwrite_off - usent);
1407 reschedule_queue_timeout (queue);
1409 /* can we encrypt more? (always encrypt full messages, needed
1410 such that #mq_cancel() can work!) */
1411 if (queue->cwrite_off + queue->pwrite_off <= BUF_SIZE)
1414 gcry_cipher_encrypt (queue->out_cipher,
1415 &queue->cwrite_buf[queue->cwrite_off],
1418 queue->pwrite_off));
1419 if (queue->rekey_left_bytes > queue->pwrite_off)
1420 queue->rekey_left_bytes -= queue->pwrite_off;
1422 queue->rekey_left_bytes = 0;
1423 queue->cwrite_off += queue->pwrite_off;
1424 queue->pwrite_off = 0;
1426 if ( (GNUNET_YES == queue->rekey_state) &&
1427 (0 == queue->pwrite_off) )
1429 if ( (0 == queue->pwrite_off) &&
1430 ( (0 == queue->rekey_left_bytes) ||
1431 (0 == GNUNET_TIME_absolute_get_remaining (queue->rekey_time).rel_value_us) ) )
1432 inject_rekey (queue);
1433 if ( (0 == queue->pwrite_off) &&
1434 (! queue->finishing) &&
1435 (queue->mq_awaits_continue) )
1437 queue->mq_awaits_continue = GNUNET_NO;
1438 GNUNET_MQ_impl_send_continue (queue->mq);
1440 /* did we just finish writing 'finish'? */
1441 if ( (0 == queue->cwrite_off) &&
1442 (GNUNET_YES == queue->finishing) )
1444 queue_destroy (queue);
1447 /* do we care to write more? */
1448 if (0 < queue->cwrite_off)
1450 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1458 * Signature of functions implementing the sending functionality of a
1461 * @param mq the message queue
1462 * @param msg the message to send
1463 * @param impl_state our `struct Queue`
1466 mq_send (struct GNUNET_MQ_Handle *mq,
1467 const struct GNUNET_MessageHeader *msg,
1470 struct Queue *queue = impl_state;
1471 uint16_t msize = ntohs (msg->size);
1474 GNUNET_assert (mq == queue->mq);
1475 if (GNUNET_YES == queue->finishing)
1476 return; /* this queue is dying, drop msg */
1477 GNUNET_assert (0 == queue->pread_off);
1478 box.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX);
1479 box.header.size = htons (msize);
1480 calculate_hmac (&queue->out_hmac,
1484 memcpy (&queue->pread_buf[queue->pread_off],
1487 queue->pread_off += sizeof (box);
1488 memcpy (&queue->pread_buf[queue->pread_off],
1491 queue->pread_off += msize;
1492 GNUNET_assert (NULL != queue->sock);
1493 if (NULL == queue->write_task)
1495 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1503 * Signature of functions implementing the destruction of a message
1504 * queue. Implementations must not free @a mq, but should take care
1507 * @param mq the message queue to destroy
1508 * @param impl_state our `struct Queue`
1511 mq_destroy (struct GNUNET_MQ_Handle *mq,
1514 struct Queue *queue = impl_state;
1516 if (mq == queue->mq)
1519 queue_finish (queue);
1525 * Implementation function that cancels the currently sent message.
1527 * @param mq message queue
1528 * @param impl_state our `struct Queue`
1531 mq_cancel (struct GNUNET_MQ_Handle *mq,
1534 struct Queue *queue = impl_state;
1536 GNUNET_assert (0 != queue->pwrite_off);
1537 queue->pwrite_off = 0;
1542 * Generic error handler, called with the appropriate
1543 * error code and the same closure specified at the creation of
1544 * the message queue.
1545 * Not every message queue implementation supports an error handler.
1547 * @param cls our `struct Queue`
1548 * @param error error code
1551 mq_error (void *cls,
1552 enum GNUNET_MQ_Error error)
1554 struct Queue *queue = cls;
1556 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1557 "MQ error in queue to %s: %d\n",
1558 GNUNET_i2s (&queue->target),
1560 queue_finish (queue);
1565 * Add the given @a queue to our internal data structure. Setup the
1566 * MQ processing and inform transport that the queue is ready. Must
1567 * be called after the KX for outgoing messages has been bootstrapped.
1569 * @param queue queue to boot
1572 boot_queue (struct Queue *queue,
1573 enum GNUNET_TRANSPORT_ConnectionStatus cs)
1575 queue->nt = GNUNET_NT_scanner_get_type (is,
1577 queue->address_len);
1578 (void) GNUNET_CONTAINER_multipeermap_put (queue_map,
1581 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1582 GNUNET_STATISTICS_set (stats,
1584 GNUNET_CONTAINER_multipeermap_size (queue_map),
1587 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1589 = GNUNET_MQ_queue_for_callbacks (&mq_send,
1599 switch (queue->address->sa_family)
1602 GNUNET_asprintf (&foreign_addr,
1604 COMMUNICATOR_ADDRESS_PREFIX,
1605 GNUNET_a2s(queue->address,
1606 queue->address_len));
1609 GNUNET_asprintf (&foreign_addr,
1611 COMMUNICATOR_ADDRESS_PREFIX,
1612 GNUNET_a2s(queue->address,
1613 queue->address_len));
1619 = GNUNET_TRANSPORT_communicator_mq_add (ch,
1626 GNUNET_free (foreign_addr);
1632 * Generate and transmit our ephemeral key and the signature for
1633 * the initial KX with the other peer. Must be called first, before
1634 * any other bytes are ever written to the output buffer. Note that
1635 * our cipher must already be initialized when calling this function.
1636 * Helper function for #start_initial_kx_out().
1638 * @param queue queue to do KX for
1639 * @param epub our public key for the KX
1642 transmit_kx (struct Queue *queue,
1643 const struct GNUNET_CRYPTO_EcdhePublicKey *epub)
1645 struct TcpHandshakeSignature ths;
1646 struct TCPConfirmation tc;
1648 memcpy (queue->cwrite_buf,
1651 queue->cwrite_off = sizeof (epub);
1652 /* compute 'tc' and append in encrypted format to cwrite_buf */
1653 tc.sender = my_identity;
1654 tc.monotonic_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1655 ths.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE);
1656 ths.purpose.size = htonl (sizeof (ths));
1657 ths.sender = my_identity;
1658 ths.receiver = queue->target;
1659 ths.ephemeral = *epub;
1660 ths.monotonic_time = tc.monotonic_time;
1661 GNUNET_assert (GNUNET_OK ==
1662 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1666 gcry_cipher_encrypt (queue->out_cipher,
1667 &queue->cwrite_buf[queue->cwrite_off],
1671 queue->cwrite_off += sizeof (tc);
1676 * Initialize our key material for outgoing transmissions and
1677 * inform the other peer about it. Must be called first before
1680 * @param queue the queue to setup
1683 start_initial_kx_out (struct Queue *queue)
1685 struct GNUNET_CRYPTO_EcdhePublicKey epub;
1687 GNUNET_assert (GNUNET_OK ==
1688 GNUNET_CRYPTO_ecdhe_key_create2 (&queue->ephemeral));
1689 GNUNET_CRYPTO_ecdhe_key_get_public (&queue->ephemeral,
1691 setup_out_cipher (queue);
1698 * We have received the first bytes from the other side on a @a queue.
1699 * Decrypt the @a tc contained in @a ibuf and check the signature.
1700 * Note that #setup_in_cipher() must have already been called.
1702 * @param queue queue to decrypt initial bytes from other peer for
1703 * @param tc[out] where to store the result
1704 * @param ibuf incoming data, of size
1706 * @return #GNUNET_OK if the signature was OK, #GNUNET_SYSERR if not
1709 decrypt_and_check_tc (struct Queue *queue,
1710 struct TCPConfirmation *tc,
1713 struct TcpHandshakeSignature ths;
1716 gcry_cipher_decrypt (queue->in_cipher,
1719 &ibuf[sizeof (struct GNUNET_CRYPTO_EcdhePublicKey)],
1721 ths.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE);
1722 ths.purpose.size = htonl (sizeof (ths));
1723 ths.sender = tc->sender;
1724 ths.receiver = my_identity;
1725 memcpy (&ths.ephemeral,
1727 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey));
1728 ths.monotonic_time = tc->monotonic_time;
1729 return GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE,
1732 &tc->sender.public_key);
1737 * Closes socket and frees memory associated with @a pq.
1739 * @param pq proto queue to free
1742 free_proto_queue (struct ProtoQueue *pq)
1744 GNUNET_NETWORK_socket_close (pq->sock);
1745 GNUNET_free (pq->address);
1746 GNUNET_CONTAINER_DLL_remove (proto_head,
1754 * Read from the socket of the proto queue until we have enough data
1755 * to upgrade to full queue.
1757 * @param cls a `struct ProtoQueue`
1760 proto_read_kx (void *cls)
1762 struct ProtoQueue *pq = cls;
1764 struct GNUNET_TIME_Relative left;
1765 struct Queue *queue;
1766 struct TCPConfirmation tc;
1768 pq->read_task = NULL;
1769 left = GNUNET_TIME_absolute_get_remaining (pq->timeout);
1770 if (0 == left.rel_value_us)
1772 free_proto_queue (pq);
1775 rcvd = GNUNET_NETWORK_socket_recv (pq->sock,
1776 &pq->ibuf[pq->ibuf_off],
1777 sizeof (pq->ibuf) - pq->ibuf_off);
1780 if ( (EAGAIN != errno) &&
1783 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1785 free_proto_queue (pq);
1789 pq->read_task = GNUNET_SCHEDULER_add_read_net (left,
1795 pq->ibuf_off += rcvd;
1796 if (pq->ibuf_off > sizeof (pq->ibuf))
1799 pq->read_task = GNUNET_SCHEDULER_add_read_net (left,
1805 /* we got all the data, let's find out who we are talking to! */
1806 queue = GNUNET_new (struct Queue);
1807 setup_in_cipher ((const struct GNUNET_CRYPTO_EcdhePublicKey *) pq->ibuf,
1810 decrypt_and_check_tc (queue,
1814 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1815 "Invalid TCP KX received from %s\n",
1816 GNUNET_a2s (queue->address,
1817 queue->address_len));
1818 gcry_cipher_close (queue->in_cipher);
1819 GNUNET_free (queue);
1820 free_proto_queue (pq);
1823 queue->address = pq->address; /* steals reference */
1824 queue->address_len = pq->address_len;
1825 queue->target = tc.sender;
1826 start_initial_kx_out (queue);
1828 GNUNET_TRANSPORT_CS_INBOUND);
1830 = GNUNET_SCHEDULER_add_read_net (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1834 GNUNET_CONTAINER_DLL_remove (proto_head,
1842 * We have been notified that our listen socket has something to
1843 * read. Do the read and reschedule this function to be called again
1844 * once more is available.
1849 listen_cb (void *cls)
1851 struct sockaddr_storage in;
1853 struct GNUNET_NETWORK_Handle *sock;
1854 struct ProtoQueue *pq;
1857 GNUNET_assert (NULL != listen_sock);
1858 addrlen = sizeof (in);
1862 sock = GNUNET_NETWORK_socket_accept (listen_sock,
1863 (struct sockaddr *) &in,
1865 if ( (NULL == sock) &&
1866 ( (EMFILE == errno) ||
1867 (ENFILE == errno) ) )
1868 return; /* system limit reached, wait until connection goes down */
1869 listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1873 if ( (NULL == sock) &&
1874 ( (EAGAIN == errno) ||
1875 (ENOBUFS == errno) ) )
1879 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1883 pq = GNUNET_new (struct ProtoQueue);
1884 pq->address_len = addrlen;
1885 pq->address = GNUNET_memdup (&in,
1887 pq->timeout = GNUNET_TIME_relative_to_absolute (PROTO_QUEUE_TIMEOUT);
1889 pq->read_task = GNUNET_SCHEDULER_add_read_net (PROTO_QUEUE_TIMEOUT,
1893 GNUNET_CONTAINER_DLL_insert (proto_head,
1900 * Read from the socket of the queue until we have enough data
1901 * to initialize the decryption logic and can switch to regular
1904 * @param cls a `struct Queue`
1907 queue_read_kx (void *cls)
1909 struct Queue *queue = cls;
1911 struct GNUNET_TIME_Relative left;
1912 struct TCPConfirmation tc;
1914 queue->read_task = NULL;
1915 left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
1916 if (0 == left.rel_value_us)
1918 queue_destroy (queue);
1921 rcvd = GNUNET_NETWORK_socket_recv (queue->sock,
1922 &queue->cread_buf[queue->cread_off],
1923 BUF_SIZE - queue->cread_off);
1926 if ( (EAGAIN != errno) &&
1929 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1931 queue_destroy (queue);
1934 queue->read_task = GNUNET_SCHEDULER_add_read_net (left,
1940 queue->cread_off += rcvd;
1941 if (queue->cread_off <
1945 queue->read_task = GNUNET_SCHEDULER_add_read_net (left,
1951 /* we got all the data, let's find out who we are talking to! */
1952 setup_in_cipher ((const struct GNUNET_CRYPTO_EcdhePublicKey *) queue->cread_buf,
1955 decrypt_and_check_tc (queue,
1959 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1960 "Invalid TCP KX received from %s\n",
1961 GNUNET_a2s (queue->address,
1962 queue->address_len));
1963 queue_destroy (queue);
1966 if (0 != memcmp (&tc.sender,
1968 sizeof (struct GNUNET_PeerIdentity)))
1970 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1971 "Invalid sender in TCP KX received from %s\n",
1972 GNUNET_a2s (queue->address,
1973 queue->address_len));
1974 queue_destroy (queue);
1978 /* update queue timeout */
1979 reschedule_queue_timeout (queue);
1980 /* prepare to continue with regular read task immediately */
1981 memmove (queue->cread_buf,
1982 &queue->cread_buf[INITIAL_KX_SIZE],
1983 queue->cread_off - (INITIAL_KX_SIZE));
1984 queue->cread_off -= INITIAL_KX_SIZE;
1985 queue->read_task = GNUNET_SCHEDULER_add_now (&queue_read,
1991 * Function called by the transport service to initialize a
1992 * message queue given address information about another peer.
1993 * If and when the communication channel is established, the
1994 * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
1995 * to notify the service that the channel is now up. It is
1996 * the responsibility of the communicator to manage sane
1997 * retries and timeouts for any @a peer/@a address combination
1998 * provided by the transport service. Timeouts and retries
1999 * do not need to be signalled to the transport service.
2001 * @param cls closure
2002 * @param peer identity of the other peer
2003 * @param address where to send the message, human-readable
2004 * communicator-specific format, 0-terminated, UTF-8
2005 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is invalid
2009 const struct GNUNET_PeerIdentity *peer,
2010 const char *address)
2012 struct Queue *queue;
2014 struct sockaddr *in;
2016 struct GNUNET_NETWORK_Handle *sock;
2018 if (0 != strncmp (address,
2019 COMMUNICATOR_ADDRESS_PREFIX "-",
2020 strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
2022 GNUNET_break_op (0);
2023 return GNUNET_SYSERR;
2025 path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
2026 in = tcp_address_to_sockaddr (path,
2029 sock = GNUNET_NETWORK_socket_create (in->sa_family,
2034 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2035 "socket(%d) failed: %s",
2039 return GNUNET_SYSERR;
2042 GNUNET_NETWORK_socket_connect (sock,
2046 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2047 "connect to `%s' failed: %s",
2050 GNUNET_NETWORK_socket_close (sock);
2052 return GNUNET_SYSERR;
2055 queue = GNUNET_new (struct Queue);
2056 queue->target = *peer;
2057 queue->address = in;
2058 queue->address_len = in_len;
2061 GNUNET_TRANSPORT_CS_OUTBOUND);
2063 = GNUNET_SCHEDULER_add_read_net (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2069 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2070 "Failed to setup queue to %s at `%s'\n",
2073 GNUNET_NETWORK_socket_close (sock);
2076 start_initial_kx_out (queue);
2082 * Iterator over all message queues to clean up.
2085 * @param target unused
2086 * @param value the queue to destroy
2087 * @return #GNUNET_OK to continue to iterate
2090 get_queue_delete_it (void *cls,
2091 const struct GNUNET_PeerIdentity *target,
2094 struct Queue *queue = value;
2098 queue_destroy (queue);
2104 * Shutdown the UNIX communicator.
2106 * @param cls NULL (always)
2109 do_shutdown (void *cls)
2113 GNUNET_NAT_unregister (nat);
2116 if (NULL != listen_task)
2118 GNUNET_SCHEDULER_cancel (listen_task);
2121 if (NULL != listen_sock)
2123 GNUNET_break (GNUNET_OK ==
2124 GNUNET_NETWORK_socket_close (listen_sock));
2127 GNUNET_CONTAINER_multipeermap_iterate (queue_map,
2128 &get_queue_delete_it,
2130 GNUNET_CONTAINER_multipeermap_destroy (queue_map);
2133 GNUNET_TRANSPORT_communicator_disconnect (ch);
2138 GNUNET_STATISTICS_destroy (stats,
2142 if (NULL != my_private_key)
2144 GNUNET_free (my_private_key);
2145 my_private_key = NULL;
2149 GNUNET_NT_scanner_done (is);
2156 * Function called when the transport service has received an
2157 * acknowledgement for this communicator (!) via a different return
2160 * Not applicable for TCP.
2162 * @param cls closure
2163 * @param sender which peer sent the notification
2164 * @param msg payload
2167 enc_notify_cb (void *cls,
2168 const struct GNUNET_PeerIdentity *sender,
2169 const struct GNUNET_MessageHeader *msg)
2174 GNUNET_break_op (0);
2179 * Signature of the callback passed to #GNUNET_NAT_register() for
2180 * a function to call whenever our set of 'valid' addresses changes.
2182 * @param cls closure
2183 * @param app_ctx[in,out] location where the app can store stuff
2184 * on add and retrieve it on remove
2185 * @param add_remove #GNUNET_YES to add a new public IP address,
2186 * #GNUNET_NO to remove a previous (now invalid) one
2187 * @param ac address class the address belongs to
2188 * @param addr either the previous or the new public IP address
2189 * @param addrlen actual length of the @a addr
2192 nat_address_cb (void *cls,
2195 enum GNUNET_NAT_AddressClass ac,
2196 const struct sockaddr *addr,
2200 struct GNUNET_TRANSPORT_AddressIdentifier *ai;
2202 if (GNUNET_YES == add_remove)
2204 enum GNUNET_NetworkType nt;
2206 GNUNET_asprintf (&my_addr,
2208 COMMUNICATOR_ADDRESS_PREFIX,
2211 nt = GNUNET_NT_scanner_get_type (is,
2214 ai = GNUNET_TRANSPORT_communicator_address_add (ch,
2217 GNUNET_TIME_UNIT_FOREVER_REL);
2218 GNUNET_free (my_addr);
2224 GNUNET_TRANSPORT_communicator_address_remove (ai);
2231 * Setup communicator and launch network interactions.
2233 * @param cls NULL (always)
2234 * @param args remaining command-line arguments
2235 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2236 * @param c configuration
2241 const char *cfgfile,
2242 const struct GNUNET_CONFIGURATION_Handle *c)
2245 struct sockaddr *in;
2247 struct sockaddr_storage in_sto;
2253 GNUNET_CONFIGURATION_get_value_filename (cfg,
2254 COMMUNICATOR_CONFIG_SECTION,
2258 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2259 COMMUNICATOR_CONFIG_SECTION,
2264 GNUNET_CONFIGURATION_get_value_number (cfg,
2265 COMMUNICATOR_CONFIG_SECTION,
2268 max_queue_length = DEFAULT_MAX_QUEUE_LENGTH;
2270 in = tcp_address_to_sockaddr (bindto,
2274 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2275 "Failed to setup TCP socket address with path `%s'\n",
2277 GNUNET_free (bindto);
2280 listen_sock = GNUNET_NETWORK_socket_create (in->sa_family,
2283 if (NULL == listen_sock)
2285 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
2288 GNUNET_free (bindto);
2292 GNUNET_NETWORK_socket_bind (listen_sock,
2296 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
2299 GNUNET_NETWORK_socket_close (listen_sock);
2302 GNUNET_free (bindto);
2305 /* We might have bound to port 0, allowing the OS to figure it out;
2306 thus, get the real IN-address from the socket */
2307 sto_len = sizeof (in_sto);
2308 if (0 != getsockname (GNUNET_NETWORK_get_fd (listen_sock),
2309 (struct sockaddr *) &in_sto,
2318 GNUNET_free (bindto);
2319 in = (struct sockaddr *) &in_sto;
2321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2323 GNUNET_a2s ((const struct sockaddr *) &in_sto,
2325 stats = GNUNET_STATISTICS_create ("C-TCP",
2327 GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
2329 is = GNUNET_NT_scanner_init ();
2330 my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
2331 if (NULL == my_private_key)
2333 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2334 _("Transport service is lacking key configuration settings. Exiting.\n"));
2335 GNUNET_SCHEDULER_shutdown ();
2338 GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
2339 &my_identity.public_key);
2340 /* start listening */
2341 listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2345 queue_map = GNUNET_CONTAINER_multipeermap_create (10,
2347 ch = GNUNET_TRANSPORT_communicator_connect (cfg,
2348 COMMUNICATOR_CONFIG_SECTION,
2349 COMMUNICATOR_ADDRESS_PREFIX,
2350 GNUNET_TRANSPORT_CC_RELIABLE,
2358 GNUNET_SCHEDULER_shutdown ();
2361 nat = GNUNET_NAT_register (cfg,
2362 COMMUNICATOR_CONFIG_SECTION,
2364 1 /* one address */,
2365 (const struct sockaddr **) &in,
2368 NULL /* FIXME: support reversal: #5529 */,
2369 NULL /* closure */);
2374 * The main function for the UNIX communicator.
2376 * @param argc number of arguments from the command line
2377 * @param argv command line arguments
2378 * @return 0 ok, 1 on error
2384 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2385 GNUNET_GETOPT_OPTION_END
2390 GNUNET_STRINGS_get_utf8_args (argc, argv,
2396 GNUNET_PROGRAM_run (argc, argv,
2397 "gnunet-communicator-tcp",
2398 _("GNUnet TCP communicator"),
2402 GNUNET_free ((void*) argv);
2407 /* end of gnunet-communicator-tcp.c */