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 many messages do we keep at most in the queue to the
47 * transport service before we start to drop (default,
48 * can be changed via the configuration file).
49 * Should be _below_ the level of the communicator API, as
50 * otherwise we may read messages just to have them dropped
51 * by the communicator API.
53 #define DEFAULT_MAX_QUEUE_LENGTH 8
56 * Size of our IO buffers for ciphertext data. Must be at
57 * least UINT_MAX + sizeof (struct TCPBox).
59 #define BUF_SIZE (2 * 64 * 1024 + sizeof (struct TCPBox))
62 * How often do we rekey based on time (at least)
64 #define REKEY_TIME_INTERVAL GNUNET_TIME_UNIT_DAYS
67 * How long do we wait until we must have received the initial KX?
69 #define PROTO_QUEUE_TIMEOUT GNUNET_TIME_UNIT_MINUTES
72 * How often do we rekey based on number of bytes transmitted?
73 * (additionally randomized).
75 #define REKEY_MAX_BYTES (1024LLU * 1024 * 1024 * 4LLU)
78 * Size of the initial key exchange message sent first in both
81 #define INITIAL_KX_SIZE (sizeof (struct GNUNET_CRYPTO_EcdhePublicKey)+sizeof (struct TCPConfirmation))
85 * Address prefix used by the communicator.
87 #define COMMUNICATOR_ADDRESS_PREFIX "tcp"
90 * Configuration section used by the communicator.
92 #define COMMUNICATOR_CONFIG_SECTION "communicator-tcp"
94 GNUNET_NETWORK_STRUCT_BEGIN
98 * Signature we use to verify that the ephemeral key was really chosen by
99 * the specified sender.
101 struct TcpHandshakeSignature
104 * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE
106 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
109 * Identity of the inititor of the TCP connection (TCP client).
111 struct GNUNET_PeerIdentity sender;
114 * Presumed identity of the target of the TCP connection (TCP server)
116 struct GNUNET_PeerIdentity receiver;
119 * Ephemeral key used by the @e sender.
121 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
124 * Monotonic time of @e sender, to possibly help detect replay attacks
125 * (if receiver persists times by sender).
127 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
132 * Encrypted continuation of TCP initial handshake.
134 struct TCPConfirmation
139 struct GNUNET_PeerIdentity sender;
142 * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE
144 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
147 * Monotonic time of @e sender, to possibly help detect replay attacks
148 * (if receiver persists times by sender).
150 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
156 * TCP message box. Always sent encrypted!
162 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX. Warning: the
163 * header size EXCLUDES the size of the `struct TCPBox`. We usually
164 * never do this, but here the payload may truly be 64k *after* the
165 * TCPBox (as we have no MTU)!!
167 struct GNUNET_MessageHeader header;
170 * HMAC for the following encrypted message. Yes, we MUST use
171 * mac-then-encrypt here, as we want to hide the message sizes on
172 * the wire (zero plaintext design!). Using CTR mode padding oracle
173 * attacks do not apply. Besides, due to the use of ephemeral keys
174 * (hopefully with effective replay protection from monotonic time!)
175 * the attacker is limited in using the oracle.
177 struct GNUNET_ShortHashCode hmac;
179 /* followed by as may bytes of payload as indicated in @e header,
180 excluding the TCPBox itself! */
186 * TCP rekey message box. Always sent encrypted! Data after
187 * this message will use the new key.
193 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY.
195 struct GNUNET_MessageHeader header;
198 * HMAC for the following encrypted message. Yes, we MUST use
199 * mac-then-encrypt here, as we want to hide the message sizes on
200 * the wire (zero plaintext design!). Using CTR mode padding oracle
201 * attacks do not apply. Besides, due to the use of ephemeral keys
202 * (hopefully with effective replay protection from monotonic time!)
203 * the attacker is limited in using the oracle.
205 struct GNUNET_ShortHashCode hmac;
210 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
213 * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY
215 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
218 * Monotonic time of @e sender, to possibly help detect replay attacks
219 * (if receiver persists times by sender).
221 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
227 * TCP finish. Sender asks for the connection to be closed.
228 * Needed/useful in case we drop RST/FIN packets on the GNUnet
229 * port due to the possibility of malicious RST/FIN injection.
235 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH.
237 struct GNUNET_MessageHeader header;
240 * HMAC for the following encrypted message. Yes, we MUST use
241 * mac-then-encrypt here, as we want to hide the message sizes on
242 * the wire (zero plaintext design!). Using CTR mode padding oracle
243 * attacks do not apply. Besides, due to the use of ephemeral keys
244 * (hopefully with effective replay protection from monotonic time!)
245 * the attacker is limited in using the oracle.
247 struct GNUNET_ShortHashCode hmac;
252 GNUNET_NETWORK_STRUCT_END
256 * Handle for a queue.
262 * To whom are we talking to.
264 struct GNUNET_PeerIdentity target;
267 * socket that we transmit all data with on this queue
269 struct GNUNET_NETWORK_Handle *sock;
272 * cipher for decryption of incoming data.
274 gcry_cipher_hd_t in_cipher;
277 * cipher for encryption of outgoing data.
279 gcry_cipher_hd_t out_cipher;
282 * Shared secret for HMAC verification on incoming data.
284 struct GNUNET_HashCode in_hmac;
287 * Shared secret for HMAC generation on outgoing data, ratcheted after
290 struct GNUNET_HashCode out_hmac;
293 * Our ephemeral key. Stored here temporarily during rekeying / key generation.
295 struct GNUNET_CRYPTO_EcdhePrivateKey ephemeral;
298 * ID of read task for this connection.
300 struct GNUNET_SCHEDULER_Task *read_task;
303 * ID of write task for this connection.
305 struct GNUNET_SCHEDULER_Task *write_task;
308 * Address of the other peer.
310 struct sockaddr *address;
313 * How many more bytes may we sent with the current @e out_cipher
314 * before we should rekey?
316 uint64_t rekey_left_bytes;
319 * Until what time may we sent with the current @e out_cipher
320 * before we should rekey?
322 struct GNUNET_TIME_Absolute rekey_time;
325 * Length of the address.
327 socklen_t address_len;
330 * Message queue we are providing for the #ch.
332 struct GNUNET_MQ_Handle *mq;
335 * handle for this queue with the #ch.
337 struct GNUNET_TRANSPORT_QueueHandle *qh;
340 * Number of bytes we currently have in our write queue.
342 unsigned long long bytes_in_queue;
345 * Buffer for reading ciphertext from network into.
347 char cread_buf[BUF_SIZE];
350 * buffer for writing ciphertext to network.
352 char cwrite_buf[BUF_SIZE];
355 * Plaintext buffer for decrypted plaintext.
357 char pread_buf[UINT16_MAX + 1 + sizeof (struct TCPBox)];
360 * Plaintext buffer for messages to be encrypted.
362 char pwrite_buf[UINT16_MAX + 1 + sizeof (struct TCPBox)];
365 * At which offset in the ciphertext read buffer should we
366 * append more ciphertext for transmission next?
371 * At which offset in the ciphertext write buffer should we
372 * append more ciphertext from reading next?
377 * At which offset in the plaintext input buffer should we
378 * append more plaintext from decryption next?
383 * At which offset in the plaintext output buffer should we
384 * append more plaintext for encryption next?
389 * Timeout for this queue.
391 struct GNUNET_TIME_Absolute timeout;
394 * How may messages did we pass from this queue to CORE for which we
395 * have yet to receive an acknoweldgement that CORE is done with
396 * them? If "large" (or even just non-zero), we should throttle
397 * reading to provide flow control. See also #DEFAULT_MAX_QUEUE_LENGTH
398 * and #max_queue_length.
400 unsigned int backpressure;
403 * Which network type does this queue use?
405 enum GNUNET_NetworkType nt;
408 * Is MQ awaiting a #GNUNET_MQ_impl_send_continue() call?
410 int mq_awaits_continue;
413 * Did we enqueue a finish message and are closing down the queue?
418 * Did we technically destroy this queue, but kept the allocation
419 * around because of @e backpressure not being zero yet? Used
420 * simply to delay the final #GNUNET_free() operation until
421 * #core_read_finished_cb() has been called.
426 * #GNUNET_YES after #inject_key() placed the rekey message into the
427 * plaintext buffer. Once the plaintext buffer is drained, this
428 * means we must switch to the new key material.
433 * #GNUNET_YES if we just rekeyed and must thus possibly
434 * re-decrypt ciphertext.
441 * Handle for an incoming connection where we do not yet have enough
442 * information to setup a full queue.
450 struct ProtoQueue *next;
455 struct ProtoQueue *prev;
458 * socket that we transmit all data with on this queue
460 struct GNUNET_NETWORK_Handle *sock;
463 * ID of read task for this connection.
465 struct GNUNET_SCHEDULER_Task *read_task;
468 * Address of the other peer.
470 struct sockaddr *address;
473 * Length of the address.
475 socklen_t address_len;
478 * Timeout for this protoqueue.
480 struct GNUNET_TIME_Absolute timeout;
483 * Buffer for reading all the information we need to upgrade from
484 * protoqueue to queue.
486 char ibuf[INITIAL_KX_SIZE];
489 * Current offset for reading into @e ibuf.
498 static struct GNUNET_SCHEDULER_Task *listen_task;
501 * Maximum queue length before we stop reading towards the transport service.
503 static unsigned long long max_queue_length;
506 * For logging statistics.
508 static struct GNUNET_STATISTICS_Handle *stats;
513 static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
516 * Queues (map from peer identity to `struct Queue`)
518 static struct GNUNET_CONTAINER_MultiPeerMap *queue_map;
523 static struct GNUNET_NETWORK_Handle *listen_sock;
528 static struct GNUNET_PeerIdentity my_identity;
533 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
538 static const struct GNUNET_CONFIGURATION_Handle *cfg;
541 * Network scanner to determine network types.
543 static struct GNUNET_NT_InterfaceScanner *is;
546 * Connection to NAT service.
548 static struct GNUNET_NAT_Handle *nat;
551 * Protoqueues DLL head.
553 static struct ProtoQueue *proto_head;
556 * Protoqueues DLL tail.
558 static struct ProtoQueue *proto_tail;
562 * We have been notified that our listen socket has something to
563 * read. Do the read and reschedule this function to be called again
564 * once more is available.
569 listen_cb (void *cls);
573 * Functions with this signature are called whenever we need
574 * to close a queue due to a disconnect or failure to
575 * establish a connection.
577 * @param queue queue to close down
580 queue_destroy (struct Queue *queue)
582 struct GNUNET_MQ_Handle *mq;
584 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
585 "Disconnecting queue for peer `%s'\n",
586 GNUNET_i2s (&queue->target));
587 if (NULL != (mq = queue->mq))
590 GNUNET_MQ_destroy (mq);
592 GNUNET_assert (GNUNET_YES ==
593 GNUNET_CONTAINER_multipeermap_remove (queue_map,
596 GNUNET_STATISTICS_set (stats,
598 GNUNET_CONTAINER_multipeermap_size (queue_map),
600 if (NULL != queue->read_task)
602 GNUNET_SCHEDULER_cancel (queue->read_task);
603 queue->read_task = NULL;
605 if (NULL != queue->write_task)
607 GNUNET_SCHEDULER_cancel (queue->write_task);
608 queue->write_task = NULL;
610 GNUNET_NETWORK_socket_close (queue->sock);
611 gcry_cipher_close (queue->in_cipher);
612 gcry_cipher_close (queue->out_cipher);
613 GNUNET_free (queue->address);
614 if (0 != queue->backpressure)
615 queue->destroyed = GNUNET_YES;
618 if (NULL == listen_task)
619 listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
627 * Compute @a mac over @a buf, and ratched the @a hmac_secret.
629 * @param[in,out] hmac_secret secret for HMAC calculation
630 * @param buf buffer to MAC
631 * @param buf_size number of bytes in @a buf
632 * @param smac[out] where to write the HMAC
635 hmac (struct GNUNET_HashCode *hmac_secret,
638 struct GNUNET_ShortHashCode *smac)
640 struct GNUNET_HashCode mac;
642 GNUNET_CRYPTO_hmac_raw (hmac_secret,
643 sizeof (struct GNUNET_HashCode),
647 /* truncate to `struct GNUNET_ShortHashCode` */
650 sizeof (struct GNUNET_ShortHashCode));
651 /* ratchet hmac key */
652 GNUNET_CRYPTO_hash (hmac_secret,
653 sizeof (struct GNUNET_HashCode),
659 * Append a 'finish' message to the outgoing transmission. Once the
660 * finish has been transmitted, destroy the queue.
662 * @param queue queue to shut down nicely
665 queue_finish (struct Queue *queue)
667 struct TCPFinish fin;
672 fin.header.size = htons (sizeof (fin));
673 fin.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH);
674 hmac (&queue->out_hmac,
678 /* if there is any message left in pwrite_buf, we
679 overwrite it (possibly dropping the last message
680 from CORE hard here) */
681 memcpy (queue->pwrite_buf,
684 queue->pwrite_off = sizeof (fin);
685 /* This flag will ensure that #queue_write() no longer
686 notifies CORE about the possibility of sending
687 more data, and that #queue_write() will call
688 #queue_destroy() once the @c fin was fully written. */
689 queue->finishing = GNUNET_YES;
694 * Increment queue timeout due to activity. We do not immediately
695 * notify the monitor here as that might generate excessive
698 * @param queue queue for which the timeout should be rescheduled
701 reschedule_queue_timeout (struct Queue *queue)
704 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
709 * Queue read task. If we hit the timeout, disconnect it
711 * @param cls the `struct Queue *` to disconnect
714 queue_read (void *cls);
718 * Core tells us it is done processing a message that transport
719 * received on a queue with status @a success.
721 * @param cls a `struct Queue *` where the message originally came from
722 * @param success #GNUNET_OK on success
725 core_read_finished_cb (void *cls,
728 struct Queue *queue = cls;
730 if (GNUNET_OK != success)
731 GNUNET_STATISTICS_update (stats,
732 "# messages lost in communicator API towards CORE",
735 queue->backpressure--;
736 /* handle deferred queue destruction */
737 if ( (queue->destroyed) &&
738 (0 == queue->backpressure) )
743 reschedule_queue_timeout (queue);
744 /* possibly unchoke reading, now that CORE made progress */
745 if (NULL == queue->read_task)
747 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining (queue->timeout),
755 * We received @a plaintext_len bytes of @a plaintext on @a queue.
756 * Pass it on to CORE. If transmission is actually happening,
757 * increase backpressure counter.
759 * @param queue the queue that received the plaintext
760 * @param plaintext the plaintext that was received
761 * @param plaintext_len number of bytes of plaintext received
764 pass_plaintext_to_core (struct Queue *queue,
765 const void *plaintext,
766 size_t plaintext_len)
768 const struct GNUNET_MessageHeader *hdr = plaintext;
771 if (ntohs (hdr->size) != plaintext_len)
773 /* NOTE: If we ever allow multiple CORE messages in one
774 BOX, this will have to change! */
778 ret = GNUNET_TRANSPORT_communicator_receive (ch,
781 &core_read_finished_cb,
783 if (GNUNET_OK == ret)
784 queue->backpressure++;
785 GNUNET_break (GNUNET_NO != ret); /* backpressure not working!? */
786 if (GNUNET_SYSERR == ret)
787 GNUNET_STATISTICS_update (stats,
788 "# bytes lost due to CORE not running",
795 * Setup @a cipher based on shared secret @a dh and decrypting
798 * @param dh shared secret
799 * @param pid decrypting peer's identity
800 * @param cipher[out] cipher to initialize
801 * @param hmac_key[out] HMAC key to initialize
804 setup_cipher (const struct GNUNET_HashCode *dh,
805 const struct GNUNET_PeerIdentity *pid,
806 gcry_cipher_hd_t *cipher,
807 struct GNUNET_HashCode *hmac_key)
812 gcry_cipher_open (cipher,
813 GCRY_CIPHER_AES256 /* low level: go for speed */,
814 GCRY_CIPHER_MODE_CTR,
816 GNUNET_assert (GNUNET_YES ==
817 GNUNET_CRYPTO_kdf (key,
826 gcry_cipher_setkey (*cipher,
829 GNUNET_assert (GNUNET_YES ==
830 GNUNET_CRYPTO_kdf (ctr,
839 gcry_cipher_setctr (*cipher,
842 GNUNET_assert (GNUNET_YES ==
843 GNUNET_CRYPTO_kdf (hmac_key,
844 sizeof (struct GNUNET_HashCode),
856 * Setup cipher of @a queue for decryption.
858 * @param ephemeral ephemeral key we received from the other peer
859 * @param queue[in,out] queue to initialize decryption cipher for
862 setup_in_cipher (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
865 struct GNUNET_HashCode dh;
867 GNUNET_CRYPTO_eddsa_ecdh (my_private_key,
878 * Handle @a rekey message on @a queue. The message was already
879 * HMAC'ed, but we should additionally still check the signature.
880 * Then we need to stop the old cipher and start afresh.
882 * @param queue the queue @a rekey was received on
883 * @param rekey the rekey message
886 do_rekey (struct Queue *queue,
887 const struct TCPRekey *rekey)
889 struct TcpHandshakeSignature thp;
891 thp.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY);
892 thp.purpose.size = htonl (sizeof (thp));
893 thp.sender = queue->target;
894 thp.receiver = my_identity;
895 thp.ephemeral = rekey->ephemeral;
896 thp.monotonic_time = rekey->monotonic_time;
898 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY,
901 &queue->target.public_key))
904 queue_finish (queue);
907 gcry_cipher_close (queue->in_cipher);
908 queue->rekeyed = GNUNET_YES;
909 setup_in_cipher (&rekey->ephemeral,
915 * Test if we have received a full message in plaintext.
918 * @param queue queue to process inbound plaintext for
919 * @return number of bytes of plaintext handled, 0 for none
922 try_handle_plaintext (struct Queue *queue)
924 const struct GNUNET_MessageHeader *hdr
925 = (const struct GNUNET_MessageHeader *) queue->pread_buf;
926 const struct TCPBox *box
927 = (const struct TCPBox *) queue->pread_buf;
928 const struct TCPRekey *rekey
929 = (const struct TCPRekey *) queue->pread_buf;
930 const struct TCPFinish *fin
931 = (const struct TCPFinish *) queue->pread_buf;
932 struct TCPRekey rekeyz;
933 struct TCPFinish finz;
934 struct GNUNET_ShortHashCode tmac;
936 size_t size = 0; /* make compiler happy */
938 if (sizeof (*hdr) > queue->pread_off)
939 return 0; /* not even a header */
940 type = ntohs (hdr->type);
943 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX:
944 /* Special case: header size excludes box itself! */
945 if (ntohs (hdr->size) + sizeof (struct TCPBox) > queue->pread_off)
947 hmac (&queue->in_hmac,
951 if (0 != memcmp (&tmac,
956 queue_finish (queue);
959 pass_plaintext_to_core (queue,
960 (const void *) &box[1],
962 size = ntohs (hdr->size) + sizeof (*box);
964 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY:
965 if (sizeof (*rekey) > queue->pread_off)
967 if (ntohs (hdr->size) != sizeof (*rekey))
970 queue_finish (queue);
974 memset (&rekeyz.hmac,
976 sizeof (rekeyz.hmac));
977 hmac (&queue->in_hmac,
981 if (0 != memcmp (&tmac,
986 queue_finish (queue);
991 size = ntohs (hdr->size);
993 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH:
994 if (sizeof (*fin) > queue->pread_off)
996 if (ntohs (hdr->size) != sizeof (*fin))
999 queue_finish (queue);
1005 sizeof (finz.hmac));
1006 hmac (&queue->in_hmac,
1010 if (0 != memcmp (&tmac,
1014 GNUNET_break_op (0);
1015 queue_finish (queue);
1018 /* handle FINISH by destroying queue */
1019 queue_destroy (queue);
1022 GNUNET_break_op (0);
1023 queue_finish (queue);
1026 GNUNET_assert (0 != size);
1032 * Queue read task. If we hit the timeout, disconnect it
1034 * @param cls the `struct Queue *` to disconnect
1037 queue_read (void *cls)
1039 struct Queue *queue = cls;
1040 struct GNUNET_TIME_Relative left;
1043 queue->read_task = NULL;
1044 rcvd = GNUNET_NETWORK_socket_recv (queue->sock,
1045 &queue->cread_buf[queue->cread_off],
1046 BUF_SIZE - queue->cread_off);
1049 if ( (EAGAIN != errno) &&
1052 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1054 queue_finish (queue);
1059 = GNUNET_SCHEDULER_add_read_net (left,
1066 reschedule_queue_timeout (queue);
1067 queue->cread_off += rcvd;
1068 while ( (queue->pread_off < sizeof (queue->pread_buf)) &&
1069 (queue->cread_off > 0) )
1071 size_t max = GNUNET_MIN (sizeof (queue->pread_buf) - queue->pread_off,
1077 gcry_cipher_decrypt (queue->in_cipher,
1078 &queue->pread_buf[queue->pread_off],
1082 queue->pread_off += max;
1084 while ( (GNUNET_NO == queue->rekeyed) &&
1085 (0 != (done = try_handle_plaintext (queue))) )
1087 /* 'done' bytes of plaintext were used, shift buffer */
1088 GNUNET_assert (done <= queue->pread_off);
1089 /* NOTE: this memmove() could possibly sometimes be
1090 avoided if we pass 'total' into try_handle_plaintext()
1091 and use it at an offset into the buffer there! */
1092 memmove (queue->pread_buf,
1093 &queue->pread_buf[done],
1094 queue->pread_off - done);
1095 queue->pread_off -= done;
1098 /* when we encounter a rekey message, the decryption above uses the
1099 wrong key for everything after the rekey; in that case, we have
1100 to re-do the decryption at 'total' instead of at 'max'. If there
1101 is no rekey and the last message is incomplete (max > total),
1102 it is safe to keep the decryption so we shift by 'max' */
1103 if (GNUNET_YES == queue->rekeyed)
1106 queue->rekeyed = GNUNET_NO;
1108 memmove (queue->cread_buf,
1109 &queue->cread_buf[max],
1110 queue->cread_off - max);
1111 queue->cread_off -= max;
1114 if (BUF_SIZE == queue->cread_off)
1115 return; /* buffer full, suspend reading */
1116 left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
1117 if (0 != left.rel_value_us)
1119 if (max_queue_length < queue->backpressure)
1121 /* continue reading */
1123 = GNUNET_SCHEDULER_add_read_net (left,
1130 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1131 "Queue %p was idle for %s, disconnecting\n",
1133 GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1135 queue_finish (queue);
1140 * Convert TCP bind specification to a `struct sockaddr *`
1142 * @param bindto bind specification to convert
1143 * @param[out] sock_len set to the length of the address
1144 * @return converted bindto specification
1146 static struct sockaddr *
1147 tcp_address_to_sockaddr (const char *bindto,
1148 socklen_t *sock_len)
1150 struct sockaddr *in;
1156 if (1 == SSCANF (bindto,
1161 /* interpreting value as just a PORT number */
1162 if (port > UINT16_MAX)
1164 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1165 "BINDTO specification `%s' invalid: value too large for port\n",
1170 GNUNET_CONFIGURATION_get_value_yesno (cfg,
1171 COMMUNICATOR_CONFIG_SECTION,
1174 struct sockaddr_in *i4;
1176 i4 = GNUNET_malloc (sizeof (struct sockaddr_in));
1177 i4->sin_family = AF_INET;
1178 i4->sin_port = htons ((uint16_t) port);
1179 *sock_len = sizeof (struct sockaddr_in);
1180 in = (struct sockaddr *) i4;
1184 struct sockaddr_in6 *i6;
1186 i6 = GNUNET_malloc (sizeof (struct sockaddr_in6));
1187 i6->sin6_family = AF_INET6;
1188 i6->sin6_port = htons ((uint16_t) port);
1189 *sock_len = sizeof (struct sockaddr_in6);
1190 in = (struct sockaddr *) i6;
1194 cp = GNUNET_strdup (bindto);
1195 colon = strrchr (cp, ':');
1198 /* interpet value after colon as port */
1201 if (1 == SSCANF (colon,
1206 /* interpreting value as just a PORT number */
1207 if (port > UINT16_MAX)
1209 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1210 "BINDTO specification `%s' invalid: value too large for port\n",
1218 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1219 "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1227 /* interpret missing port as 0, aka pick any free one */
1232 struct sockaddr_in v4;
1234 if (1 == inet_pton (AF_INET,
1238 v4.sin_port = htons ((uint16_t) port);
1239 in = GNUNET_memdup (&v4,
1241 *sock_len = sizeof (v4);
1248 struct sockaddr_in6 v6;
1252 if ( ('[' == *cp) &&
1253 (']' == cp[strlen (cp)-1]) )
1255 start++; /* skip over '[' */
1256 cp[strlen (cp) -1] = '\0'; /* eat ']' */
1258 if (1 == inet_pton (AF_INET6,
1262 v6.sin6_port = htons ((uint16_t) port);
1263 in = GNUNET_memdup (&v6,
1265 *sock_len = sizeof (v6);
1270 /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1277 * Setup cipher for outgoing data stream based on target and
1278 * our ephemeral private key.
1280 * @param queue queue to setup outgoing (encryption) cipher for
1283 setup_out_cipher (struct Queue *queue)
1285 struct GNUNET_HashCode dh;
1287 GNUNET_CRYPTO_ecdh_eddsa (&queue->ephemeral,
1288 &queue->target.public_key,
1290 /* we don't need the private key anymore, drop it! */
1291 memset (&queue->ephemeral,
1293 sizeof (queue->ephemeral));
1299 queue->rekey_time = GNUNET_TIME_relative_to_absolute (REKEY_TIME_INTERVAL);
1300 queue->rekey_left_bytes = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
1306 * Inject a `struct TCPRekey` message into the queue's plaintext
1309 * @param queue queue to perform rekeying on
1312 inject_rekey (struct Queue *queue)
1314 struct TCPRekey rekey;
1315 struct TcpHandshakeSignature thp;
1317 GNUNET_assert (0 == queue->pwrite_off);
1321 GNUNET_assert (GNUNET_OK ==
1322 GNUNET_CRYPTO_ecdhe_key_create2 (&queue->ephemeral));
1323 rekey.header.type = ntohs (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY);
1324 rekey.header.size = ntohs (sizeof (rekey));
1325 GNUNET_CRYPTO_ecdhe_key_get_public (&queue->ephemeral,
1327 rekey.monotonic_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1328 thp.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY);
1329 thp.purpose.size = htonl (sizeof (thp));
1330 thp.sender = my_identity;
1331 thp.receiver = queue->target;
1332 thp.ephemeral = rekey.ephemeral;
1333 thp.monotonic_time = rekey.monotonic_time;
1334 GNUNET_assert (GNUNET_OK ==
1335 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1337 &rekey.sender_sig));
1338 hmac (&queue->out_hmac,
1342 memcpy (queue->pwrite_buf,
1345 queue->rekey_state = GNUNET_YES;
1350 * We encrypted the rekey message, now update actually swap the key
1351 * material and update the key freshness parameters of @a queue.
1354 switch_key (struct Queue *queue)
1356 queue->rekey_state = GNUNET_NO;
1357 gcry_cipher_close (queue->out_cipher);
1358 setup_out_cipher (queue);
1363 * We have been notified that our socket is ready to write.
1364 * Then reschedule this function to be called again once more is available.
1366 * @param cls a `struct Queue`
1369 queue_write (void *cls)
1371 struct Queue *queue = cls;
1374 queue->write_task = NULL;
1375 sent = GNUNET_NETWORK_socket_send (queue->sock,
1378 if ( (-1 == sent) &&
1379 (EAGAIN != errno) &&
1382 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1384 queue_destroy (queue);
1389 size_t usent = (size_t) sent;
1391 memmove (queue->cwrite_buf,
1392 &queue->cwrite_buf[usent],
1393 queue->cwrite_off - usent);
1394 reschedule_queue_timeout (queue);
1396 /* can we encrypt more? (always encrypt full messages, needed
1397 such that #mq_cancel() can work!) */
1398 if (queue->cwrite_off + queue->pwrite_off <= BUF_SIZE)
1401 gcry_cipher_encrypt (queue->out_cipher,
1402 &queue->cwrite_buf[queue->cwrite_off],
1405 queue->pwrite_off));
1406 if (queue->rekey_left_bytes > queue->pwrite_off)
1407 queue->rekey_left_bytes -= queue->pwrite_off;
1409 queue->rekey_left_bytes = 0;
1410 queue->cwrite_off += queue->pwrite_off;
1411 queue->pwrite_off = 0;
1413 if ( (GNUNET_YES == queue->rekey_state) &&
1414 (0 == queue->pwrite_off) )
1416 if ( (0 == queue->pwrite_off) &&
1417 ( (0 == queue->rekey_left_bytes) ||
1418 (0 == GNUNET_TIME_absolute_get_remaining (queue->rekey_time).rel_value_us) ) )
1419 inject_rekey (queue);
1420 if ( (0 == queue->pwrite_off) &&
1421 (! queue->finishing) &&
1422 (queue->mq_awaits_continue) )
1424 queue->mq_awaits_continue = GNUNET_NO;
1425 GNUNET_MQ_impl_send_continue (queue->mq);
1427 /* did we just finish writing 'finish'? */
1428 if ( (0 == queue->cwrite_off) &&
1429 (GNUNET_YES == queue->finishing) )
1431 queue_destroy (queue);
1434 /* do we care to write more? */
1435 if (0 < queue->cwrite_off)
1437 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1445 * Signature of functions implementing the sending functionality of a
1448 * @param mq the message queue
1449 * @param msg the message to send
1450 * @param impl_state our `struct Queue`
1453 mq_send (struct GNUNET_MQ_Handle *mq,
1454 const struct GNUNET_MessageHeader *msg,
1457 struct Queue *queue = impl_state;
1458 uint16_t msize = ntohs (msg->size);
1461 GNUNET_assert (mq == queue->mq);
1462 if (GNUNET_YES == queue->finishing)
1463 return; /* this queue is dying, drop msg */
1464 GNUNET_assert (0 == queue->pread_off);
1465 box.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX);
1466 box.header.size = htons (msize);
1467 hmac (&queue->out_hmac,
1471 memcpy (&queue->pread_buf[queue->pread_off],
1474 queue->pread_off += sizeof (box);
1475 memcpy (&queue->pread_buf[queue->pread_off],
1478 queue->pread_off += msize;
1479 GNUNET_assert (NULL != queue->sock);
1480 if (NULL == queue->write_task)
1482 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1490 * Signature of functions implementing the destruction of a message
1491 * queue. Implementations must not free @a mq, but should take care
1494 * @param mq the message queue to destroy
1495 * @param impl_state our `struct Queue`
1498 mq_destroy (struct GNUNET_MQ_Handle *mq,
1501 struct Queue *queue = impl_state;
1503 if (mq == queue->mq)
1506 queue_finish (queue);
1512 * Implementation function that cancels the currently sent message.
1514 * @param mq message queue
1515 * @param impl_state our `struct Queue`
1518 mq_cancel (struct GNUNET_MQ_Handle *mq,
1521 struct Queue *queue = impl_state;
1523 GNUNET_assert (0 != queue->pwrite_off);
1524 queue->pwrite_off = 0;
1529 * Generic error handler, called with the appropriate
1530 * error code and the same closure specified at the creation of
1531 * the message queue.
1532 * Not every message queue implementation supports an error handler.
1534 * @param cls our `struct Queue`
1535 * @param error error code
1538 mq_error (void *cls,
1539 enum GNUNET_MQ_Error error)
1541 struct Queue *queue = cls;
1543 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1544 "MQ error in queue to %s: %d\n",
1545 GNUNET_i2s (&queue->target),
1547 queue_finish (queue);
1552 * Add the given @a queue to our internal data structure. Setup the
1553 * MQ processing and inform transport that the queue is ready. Must
1554 * be called after the KX for outgoing messages has been bootstrapped.
1556 * @param queue queue to boot
1559 boot_queue (struct Queue *queue,
1560 enum GNUNET_TRANSPORT_ConnectionStatus cs)
1562 queue->nt = GNUNET_NT_scanner_get_type (is,
1564 queue->address_len);
1565 (void) GNUNET_CONTAINER_multipeermap_put (queue_map,
1568 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1569 GNUNET_STATISTICS_set (stats,
1571 GNUNET_CONTAINER_multipeermap_size (queue_map),
1574 = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1576 = GNUNET_MQ_queue_for_callbacks (&mq_send,
1586 switch (queue->address->sa_family)
1589 GNUNET_asprintf (&foreign_addr,
1591 COMMUNICATOR_ADDRESS_PREFIX,
1592 GNUNET_a2s(queue->address,
1593 queue->address_len));
1596 GNUNET_asprintf (&foreign_addr,
1598 COMMUNICATOR_ADDRESS_PREFIX,
1599 GNUNET_a2s(queue->address,
1600 queue->address_len));
1606 = GNUNET_TRANSPORT_communicator_mq_add (ch,
1613 GNUNET_free (foreign_addr);
1619 * Generate and transmit our ephemeral key and the signature for
1620 * the initial KX with the other peer. Must be called first, before
1621 * any other bytes are ever written to the output buffer. Note that
1622 * our cipher must already be initialized when calling this function.
1623 * Helper function for #start_initial_kx_out().
1625 * @param queue queue to do KX for
1626 * @param epub our public key for the KX
1629 transmit_kx (struct Queue *queue,
1630 const struct GNUNET_CRYPTO_EcdhePublicKey *epub)
1632 struct TcpHandshakeSignature ths;
1633 struct TCPConfirmation tc;
1635 memcpy (queue->cwrite_buf,
1638 queue->cwrite_off = sizeof (epub);
1639 /* compute 'tc' and append in encrypted format to cwrite_buf */
1640 tc.sender = my_identity;
1641 tc.monotonic_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1642 ths.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE);
1643 ths.purpose.size = htonl (sizeof (ths));
1644 ths.sender = my_identity;
1645 ths.receiver = queue->target;
1646 ths.ephemeral = *epub;
1647 ths.monotonic_time = tc.monotonic_time;
1648 GNUNET_assert (GNUNET_OK ==
1649 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1653 gcry_cipher_encrypt (queue->out_cipher,
1654 &queue->cwrite_buf[queue->cwrite_off],
1658 queue->cwrite_off += sizeof (tc);
1663 * Initialize our key material for outgoing transmissions and
1664 * inform the other peer about it. Must be called first before
1667 * @param queue the queue to setup
1670 start_initial_kx_out (struct Queue *queue)
1672 struct GNUNET_CRYPTO_EcdhePublicKey epub;
1674 GNUNET_assert (GNUNET_OK ==
1675 GNUNET_CRYPTO_ecdhe_key_create2 (&queue->ephemeral));
1676 GNUNET_CRYPTO_ecdhe_key_get_public (&queue->ephemeral,
1678 setup_out_cipher (queue);
1685 * We have received the first bytes from the other side on a @a queue.
1686 * Decrypt the @a tc contained in @a ibuf and check the signature.
1687 * Note that #setup_in_cipher() must have already been called.
1689 * @param queue queue to decrypt initial bytes from other peer for
1690 * @param tc[out] where to store the result
1691 * @param ibuf incoming data, of size
1693 * @return #GNUNET_OK if the signature was OK, #GNUNET_SYSERR if not
1696 decrypt_and_check_tc (struct Queue *queue,
1697 struct TCPConfirmation *tc,
1700 struct TcpHandshakeSignature ths;
1703 gcry_cipher_decrypt (queue->in_cipher,
1706 &ibuf[sizeof (struct GNUNET_CRYPTO_EcdhePublicKey)],
1708 ths.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE);
1709 ths.purpose.size = htonl (sizeof (ths));
1710 ths.sender = tc->sender;
1711 ths.receiver = my_identity;
1712 memcpy (&ths.ephemeral,
1714 sizeof (struct GNUNET_CRYPTO_EcdhePublicKey));
1715 ths.monotonic_time = tc->monotonic_time;
1716 return GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE,
1719 &tc->sender.public_key);
1724 * Closes socket and frees memory associated with @a pq.
1726 * @param pq proto queue to free
1729 free_proto_queue (struct ProtoQueue *pq)
1731 GNUNET_NETWORK_socket_close (pq->sock);
1732 GNUNET_free (pq->address);
1733 GNUNET_CONTAINER_DLL_remove (proto_head,
1741 * Read from the socket of the proto queue until we have enough data
1742 * to upgrade to full queue.
1744 * @param cls a `struct ProtoQueue`
1747 proto_read_kx (void *cls)
1749 struct ProtoQueue *pq = cls;
1751 struct GNUNET_TIME_Relative left;
1752 struct Queue *queue;
1753 struct TCPConfirmation tc;
1755 pq->read_task = NULL;
1756 left = GNUNET_TIME_absolute_get_remaining (pq->timeout);
1757 if (0 == left.rel_value_us)
1759 free_proto_queue (pq);
1762 rcvd = GNUNET_NETWORK_socket_recv (pq->sock,
1763 &pq->ibuf[pq->ibuf_off],
1764 sizeof (pq->ibuf) - pq->ibuf_off);
1767 if ( (EAGAIN != errno) &&
1770 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1772 free_proto_queue (pq);
1776 pq->read_task = GNUNET_SCHEDULER_add_read_net (left,
1782 pq->ibuf_off += rcvd;
1783 if (pq->ibuf_off > sizeof (pq->ibuf))
1786 pq->read_task = GNUNET_SCHEDULER_add_read_net (left,
1792 /* we got all the data, let's find out who we are talking to! */
1793 queue = GNUNET_new (struct Queue);
1794 setup_in_cipher ((const struct GNUNET_CRYPTO_EcdhePublicKey *) pq->ibuf,
1797 decrypt_and_check_tc (queue,
1801 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1802 "Invalid TCP KX received from %s\n",
1803 GNUNET_a2s (queue->address,
1804 queue->address_len));
1805 gcry_cipher_close (queue->in_cipher);
1806 GNUNET_free (queue);
1807 free_proto_queue (pq);
1810 queue->address = pq->address; /* steals reference */
1811 queue->address_len = pq->address_len;
1812 queue->target = tc.sender;
1813 start_initial_kx_out (queue);
1815 GNUNET_TRANSPORT_CS_INBOUND);
1817 = GNUNET_SCHEDULER_add_read_net (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1821 GNUNET_CONTAINER_DLL_remove (proto_head,
1829 * We have been notified that our listen socket has something to
1830 * read. Do the read and reschedule this function to be called again
1831 * once more is available.
1836 listen_cb (void *cls)
1838 struct sockaddr_storage in;
1840 struct GNUNET_NETWORK_Handle *sock;
1841 struct ProtoQueue *pq;
1844 GNUNET_assert (NULL != listen_sock);
1845 addrlen = sizeof (in);
1849 sock = GNUNET_NETWORK_socket_accept (listen_sock,
1850 (struct sockaddr *) &in,
1852 if ( (NULL == sock) &&
1853 ( (EMFILE == errno) ||
1854 (ENFILE == errno) ) )
1855 return; /* system limit reached, wait until connection goes down */
1856 listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1860 if ( (NULL == sock) &&
1861 ( (EAGAIN == errno) ||
1862 (ENOBUFS == errno) ) )
1866 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
1870 pq = GNUNET_new (struct ProtoQueue);
1871 pq->address_len = addrlen;
1872 pq->address = GNUNET_memdup (&in,
1874 pq->timeout = GNUNET_TIME_relative_to_absolute (PROTO_QUEUE_TIMEOUT);
1876 pq->read_task = GNUNET_SCHEDULER_add_read_net (PROTO_QUEUE_TIMEOUT,
1880 GNUNET_CONTAINER_DLL_insert (proto_head,
1887 * Read from the socket of the queue until we have enough data
1888 * to initialize the decryption logic and can switch to regular
1891 * @param cls a `struct Queue`
1894 queue_read_kx (void *cls)
1896 struct Queue *queue = cls;
1898 struct GNUNET_TIME_Relative left;
1899 struct TCPConfirmation tc;
1901 queue->read_task = NULL;
1902 left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
1903 if (0 == left.rel_value_us)
1905 queue_destroy (queue);
1908 rcvd = GNUNET_NETWORK_socket_recv (queue->sock,
1909 &queue->cread_buf[queue->cread_off],
1910 BUF_SIZE - queue->cread_off);
1913 if ( (EAGAIN != errno) &&
1916 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG,
1918 queue_destroy (queue);
1921 queue->read_task = GNUNET_SCHEDULER_add_read_net (left,
1927 queue->cread_off += rcvd;
1928 if (queue->cread_off <
1932 queue->read_task = GNUNET_SCHEDULER_add_read_net (left,
1938 /* we got all the data, let's find out who we are talking to! */
1939 setup_in_cipher ((const struct GNUNET_CRYPTO_EcdhePublicKey *) queue->cread_buf,
1942 decrypt_and_check_tc (queue,
1946 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1947 "Invalid TCP KX received from %s\n",
1948 GNUNET_a2s (queue->address,
1949 queue->address_len));
1950 queue_destroy (queue);
1953 if (0 != memcmp (&tc.sender,
1955 sizeof (struct GNUNET_PeerIdentity)))
1957 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1958 "Invalid sender in TCP KX received from %s\n",
1959 GNUNET_a2s (queue->address,
1960 queue->address_len));
1961 queue_destroy (queue);
1965 /* update queue timeout */
1966 reschedule_queue_timeout (queue);
1967 /* prepare to continue with regular read task immediately */
1968 memmove (queue->cread_buf,
1969 &queue->cread_buf[INITIAL_KX_SIZE],
1970 queue->cread_off - (INITIAL_KX_SIZE));
1971 queue->cread_off -= INITIAL_KX_SIZE;
1972 queue->read_task = GNUNET_SCHEDULER_add_now (&queue_read,
1978 * Function called by the transport service to initialize a
1979 * message queue given address information about another peer.
1980 * If and when the communication channel is established, the
1981 * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
1982 * to notify the service that the channel is now up. It is
1983 * the responsibility of the communicator to manage sane
1984 * retries and timeouts for any @a peer/@a address combination
1985 * provided by the transport service. Timeouts and retries
1986 * do not need to be signalled to the transport service.
1988 * @param cls closure
1989 * @param peer identity of the other peer
1990 * @param address where to send the message, human-readable
1991 * communicator-specific format, 0-terminated, UTF-8
1992 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is invalid
1996 const struct GNUNET_PeerIdentity *peer,
1997 const char *address)
1999 struct Queue *queue;
2001 struct sockaddr *in;
2003 struct GNUNET_NETWORK_Handle *sock;
2005 if (0 != strncmp (address,
2006 COMMUNICATOR_ADDRESS_PREFIX "-",
2007 strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
2009 GNUNET_break_op (0);
2010 return GNUNET_SYSERR;
2012 path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
2013 in = tcp_address_to_sockaddr (path,
2016 sock = GNUNET_NETWORK_socket_create (in->sa_family,
2021 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2022 "socket(%d) failed: %s",
2026 return GNUNET_SYSERR;
2029 GNUNET_NETWORK_socket_connect (sock,
2033 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2034 "connect to `%s' failed: %s",
2037 GNUNET_NETWORK_socket_close (sock);
2039 return GNUNET_SYSERR;
2042 queue = GNUNET_new (struct Queue);
2043 queue->target = *peer;
2044 queue->address = in;
2045 queue->address_len = in_len;
2048 GNUNET_TRANSPORT_CS_OUTBOUND);
2050 = GNUNET_SCHEDULER_add_read_net (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2056 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2057 "Failed to setup queue to %s at `%s'\n",
2060 GNUNET_NETWORK_socket_close (sock);
2063 start_initial_kx_out (queue);
2069 * Iterator over all message queues to clean up.
2072 * @param target unused
2073 * @param value the queue to destroy
2074 * @return #GNUNET_OK to continue to iterate
2077 get_queue_delete_it (void *cls,
2078 const struct GNUNET_PeerIdentity *target,
2081 struct Queue *queue = value;
2085 queue_destroy (queue);
2091 * Shutdown the UNIX communicator.
2093 * @param cls NULL (always)
2096 do_shutdown (void *cls)
2100 GNUNET_NAT_unregister (nat);
2103 if (NULL != listen_task)
2105 GNUNET_SCHEDULER_cancel (listen_task);
2108 if (NULL != listen_sock)
2110 GNUNET_break (GNUNET_OK ==
2111 GNUNET_NETWORK_socket_close (listen_sock));
2114 GNUNET_CONTAINER_multipeermap_iterate (queue_map,
2115 &get_queue_delete_it,
2117 GNUNET_CONTAINER_multipeermap_destroy (queue_map);
2120 GNUNET_TRANSPORT_communicator_disconnect (ch);
2125 GNUNET_STATISTICS_destroy (stats,
2129 if (NULL != my_private_key)
2131 GNUNET_free (my_private_key);
2132 my_private_key = NULL;
2136 GNUNET_NT_scanner_done (is);
2143 * Function called when the transport service has received an
2144 * acknowledgement for this communicator (!) via a different return
2147 * Not applicable for TCP.
2149 * @param cls closure
2150 * @param sender which peer sent the notification
2151 * @param msg payload
2154 enc_notify_cb (void *cls,
2155 const struct GNUNET_PeerIdentity *sender,
2156 const struct GNUNET_MessageHeader *msg)
2161 GNUNET_break_op (0);
2166 * Signature of the callback passed to #GNUNET_NAT_register() for
2167 * a function to call whenever our set of 'valid' addresses changes.
2169 * @param cls closure
2170 * @param app_ctx[in,out] location where the app can store stuff
2171 * on add and retrieve it on remove
2172 * @param add_remove #GNUNET_YES to add a new public IP address,
2173 * #GNUNET_NO to remove a previous (now invalid) one
2174 * @param ac address class the address belongs to
2175 * @param addr either the previous or the new public IP address
2176 * @param addrlen actual length of the @a addr
2179 nat_address_cb (void *cls,
2182 enum GNUNET_NAT_AddressClass ac,
2183 const struct sockaddr *addr,
2187 struct GNUNET_TRANSPORT_AddressIdentifier *ai;
2189 if (GNUNET_YES == add_remove)
2191 enum GNUNET_NetworkType nt;
2193 GNUNET_asprintf (&my_addr,
2195 COMMUNICATOR_ADDRESS_PREFIX,
2198 nt = GNUNET_NT_scanner_get_type (is,
2201 ai = GNUNET_TRANSPORT_communicator_address_add (ch,
2204 GNUNET_TIME_UNIT_FOREVER_REL);
2205 GNUNET_free (my_addr);
2211 GNUNET_TRANSPORT_communicator_address_remove (ai);
2218 * Setup communicator and launch network interactions.
2220 * @param cls NULL (always)
2221 * @param args remaining command-line arguments
2222 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2223 * @param c configuration
2228 const char *cfgfile,
2229 const struct GNUNET_CONFIGURATION_Handle *c)
2232 struct sockaddr *in;
2234 struct sockaddr_storage in_sto;
2240 GNUNET_CONFIGURATION_get_value_filename (cfg,
2241 COMMUNICATOR_CONFIG_SECTION,
2245 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2246 COMMUNICATOR_CONFIG_SECTION,
2251 GNUNET_CONFIGURATION_get_value_number (cfg,
2252 COMMUNICATOR_CONFIG_SECTION,
2255 max_queue_length = DEFAULT_MAX_QUEUE_LENGTH;
2257 in = tcp_address_to_sockaddr (bindto,
2261 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2262 "Failed to setup TCP socket address with path `%s'\n",
2264 GNUNET_free (bindto);
2267 listen_sock = GNUNET_NETWORK_socket_create (in->sa_family,
2270 if (NULL == listen_sock)
2272 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
2275 GNUNET_free (bindto);
2279 GNUNET_NETWORK_socket_bind (listen_sock,
2283 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
2286 GNUNET_NETWORK_socket_close (listen_sock);
2289 GNUNET_free (bindto);
2292 /* We might have bound to port 0, allowing the OS to figure it out;
2293 thus, get the real IN-address from the socket */
2294 sto_len = sizeof (in_sto);
2295 if (0 != getsockname (GNUNET_NETWORK_get_fd (listen_sock),
2296 (struct sockaddr *) &in_sto,
2305 GNUNET_free (bindto);
2306 in = (struct sockaddr *) &in_sto;
2308 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2310 GNUNET_a2s ((const struct sockaddr *) &in_sto,
2312 stats = GNUNET_STATISTICS_create ("C-TCP",
2314 GNUNET_SCHEDULER_add_shutdown (&do_shutdown,
2316 is = GNUNET_NT_scanner_init ();
2317 my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
2318 if (NULL == my_private_key)
2320 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2321 _("Transport service is lacking key configuration settings. Exiting.\n"));
2322 GNUNET_SCHEDULER_shutdown ();
2325 GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
2326 &my_identity.public_key);
2327 /* start listening */
2328 listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2332 queue_map = GNUNET_CONTAINER_multipeermap_create (10,
2334 ch = GNUNET_TRANSPORT_communicator_connect (cfg,
2335 COMMUNICATOR_CONFIG_SECTION,
2336 COMMUNICATOR_ADDRESS_PREFIX,
2337 GNUNET_TRANSPORT_CC_RELIABLE,
2345 GNUNET_SCHEDULER_shutdown ();
2348 nat = GNUNET_NAT_register (cfg,
2349 COMMUNICATOR_CONFIG_SECTION,
2351 1 /* one address */,
2352 (const struct sockaddr **) &in,
2355 NULL /* FIXME: support reversal: #5529 */,
2356 NULL /* closure */);
2361 * The main function for the UNIX communicator.
2363 * @param argc number of arguments from the command line
2364 * @param argv command line arguments
2365 * @return 0 ok, 1 on error
2371 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2372 GNUNET_GETOPT_OPTION_END
2377 GNUNET_STRINGS_get_utf8_args (argc, argv,
2383 GNUNET_PROGRAM_run (argc, argv,
2384 "gnunet-communicator-tcp",
2385 _("GNUnet TCP communicator"),
2389 GNUNET_free ((void*) argv);
2394 /* end of gnunet-communicator-tcp.c */