aboutsummaryrefslogtreecommitdiff
path: root/src/service/transport/gnunet-communicator-tcp.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/service/transport/gnunet-communicator-tcp.c')
-rw-r--r--src/service/transport/gnunet-communicator-tcp.c4182
1 files changed, 4182 insertions, 0 deletions
diff --git a/src/service/transport/gnunet-communicator-tcp.c b/src/service/transport/gnunet-communicator-tcp.c
new file mode 100644
index 000000000..02f5fc9f9
--- /dev/null
+++ b/src/service/transport/gnunet-communicator-tcp.c
@@ -0,0 +1,4182 @@
1/*
2 This file is part of GNUnet
3 Copyright (C) 2010-2014, 2018, 2019 GNUnet e.V.
4
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version.
9
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details.
14
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 SPDX-License-Identifier: AGPL3.0-or-later
19 */
20
21/**
22 * @file transport/gnunet-communicator-tcp.c
23 * @brief Transport plugin using TCP.
24 * @author Christian Grothoff
25 *
26 * TODO:
27 * - support NAT connection reversal method (#5529)
28 * - support other TCP-specific NAT traversal methods (#5531)
29 */
30#include "gnunet_common.h"
31#include "platform.h"
32#include "gnunet_util_lib.h"
33#include "gnunet_core_service.h"
34#include "gnunet_peerstore_service.h"
35#include "gnunet_protocols.h"
36#include "gnunet_signatures.h"
37#include "gnunet_constants.h"
38#include "gnunet_nat_service.h"
39#include "gnunet_statistics_service.h"
40#include "gnunet_transport_communication_service.h"
41#include "gnunet_resolver_service.h"
42
43
44/**
45 * How long until we give up on establishing an NAT connection?
46 * Must be > 4 RTT
47 */
48#define NAT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
49
50/**
51 * How long do we believe our addresses to remain up (before
52 * the other peer should revalidate).
53 */
54#define ADDRESS_VALIDITY_PERIOD \
55 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 4)
56
57/**
58 * How many messages do we keep at most in the queue to the
59 * transport service before we start to drop (default,
60 * can be changed via the configuration file).
61 * Should be _below_ the level of the communicator API, as
62 * otherwise we may read messages just to have them dropped
63 * by the communicator API.
64 */
65#define DEFAULT_MAX_QUEUE_LENGTH 8
66
67/**
68 * Size of our IO buffers for ciphertext data. Must be at
69 * least UINT_MAX + sizeof (struct TCPBox).
70 */
71#define BUF_SIZE (2 * 64 * 1024 + sizeof(struct TCPBox))
72
73/**
74 * How often do we rekey based on time (at least)
75 */
76#define DEFAULT_REKEY_INTERVAL GNUNET_TIME_UNIT_DAYS
77
78/**
79 * How long do we wait until we must have received the initial KX?
80 */
81#define PROTO_QUEUE_TIMEOUT GNUNET_TIME_UNIT_MINUTES
82
83/**
84 * How often do we rekey based on number of bytes transmitted?
85 * (additionally randomized). Currently 400 MB
86 */
87#define REKEY_MAX_BYTES (1024LLU * 1024 * 400)
88
89/**
90 * Size of the initial key exchange message sent first in both
91 * directions.
92 */
93#define INITIAL_KX_SIZE \
94 (sizeof(struct GNUNET_CRYPTO_EcdhePublicKey) \
95 + sizeof(struct TCPConfirmation))
96
97/**
98 * Size of the initial core key exchange messages.
99 */
100#define INITIAL_CORE_KX_SIZE \
101 (sizeof(struct EphemeralKeyMessage) \
102 + sizeof(struct PingMessage) \
103 + sizeof(struct PongMessage))
104
105/**
106 * Address prefix used by the communicator.
107 */
108#define COMMUNICATOR_ADDRESS_PREFIX "tcp"
109
110/**
111 * Configuration section used by the communicator.
112 */
113#define COMMUNICATOR_CONFIG_SECTION "communicator-tcp"
114
115GNUNET_NETWORK_STRUCT_BEGIN
116
117
118/**
119 * Signature we use to verify that the ephemeral key was really chosen by
120 * the specified sender.
121 */
122struct TcpHandshakeSignature
123{
124 /**
125 * Purpose must be #GNUNET_SIGNATURE_PURPOSE_COMMUNICATOR_TCP_HANDSHAKE
126 */
127 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
128
129 /**
130 * Identity of the inititor of the TCP connection (TCP client).
131 */
132 struct GNUNET_PeerIdentity sender;
133
134 /**
135 * Presumed identity of the target of the TCP connection (TCP server)
136 */
137 struct GNUNET_PeerIdentity receiver;
138
139 /**
140 * Ephemeral key used by the @e sender.
141 */
142 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
143
144 /**
145 * Monotonic time of @e sender, to possibly help detect replay attacks
146 * (if receiver persists times by sender).
147 */
148 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
149
150 /**
151 * Challenge value used to protect against replay attack, if there is no stored monotonic time value.
152 */
153 struct GNUNET_CRYPTO_ChallengeNonceP challenge;
154};
155
156/**
157 * Signature we use to verify that the ack from the receiver of the ephemeral key was really send by
158 * the specified sender.
159 */
160struct TcpHandshakeAckSignature
161{
162 /**
163 * Purpose must be #GNUNET_SIGNATURE_PURPOSE_COMMUNICATOR_TCP_HANDSHAKE_ACK
164 */
165 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
166
167 /**
168 * Identity of the inititor of the TCP connection (TCP client).
169 */
170 struct GNUNET_PeerIdentity sender;
171
172 /**
173 * Presumed identity of the target of the TCP connection (TCP server)
174 */
175 struct GNUNET_PeerIdentity receiver;
176
177 /**
178 * Monotonic time of @e sender, to possibly help detect replay attacks
179 * (if receiver persists times by sender).
180 */
181 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
182
183 /**
184 * Challenge value used to protect against replay attack, if there is no stored monotonic time value.
185 */
186 struct GNUNET_CRYPTO_ChallengeNonceP challenge;
187};
188
189/**
190 * Encrypted continuation of TCP initial handshake.
191 */
192struct TCPConfirmation
193{
194 /**
195 * Sender's identity
196 */
197 struct GNUNET_PeerIdentity sender;
198
199 /**
200 * Sender's signature of type #GNUNET_SIGNATURE_PURPOSE_COMMUNICATOR_TCP_HANDSHAKE
201 */
202 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
203
204 /**
205 * Monotonic time of @e sender, to possibly help detect replay attacks
206 * (if receiver persists times by sender).
207 */
208 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
209
210 /**
211 * Challenge value used to protect against replay attack, if there is no stored monotonic time value.
212 */
213 struct GNUNET_CRYPTO_ChallengeNonceP challenge;
214
215};
216
217/**
218 * Ack for the encrypted continuation of TCP initial handshake.
219 */
220struct TCPConfirmationAck
221{
222
223
224 /**
225 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_CONFIRMATION_ACK.
226 */
227 struct GNUNET_MessageHeader header;
228
229 /**
230 * Sender's identity
231 */
232 struct GNUNET_PeerIdentity sender;
233
234 /**
235 * Sender's signature of type #GNUNET_SIGNATURE_PURPOSE_COMMUNICATOR_TCP_HANDSHAKE_ACK
236 */
237 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
238
239 /**
240 * Monotonic time of @e sender, to possibly help detect replay attacks
241 * (if receiver persists times by sender).
242 */
243 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
244
245 /**
246 * Challenge value used to protect against replay attack, if there is no stored monotonic time value.
247 */
248 struct GNUNET_CRYPTO_ChallengeNonceP challenge;
249
250};
251
252/**
253 * TCP message box. Always sent encrypted!
254 */
255struct TCPBox
256{
257 /**
258 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX. Warning: the
259 * header size EXCLUDES the size of the `struct TCPBox`. We usually
260 * never do this, but here the payload may truly be 64k *after* the
261 * TCPBox (as we have no MTU)!!
262 */
263 struct GNUNET_MessageHeader header;
264
265 /**
266 * HMAC for the following encrypted message. Yes, we MUST use
267 * mac-then-encrypt here, as we want to hide the message sizes on
268 * the wire (zero plaintext design!). Using CTR mode, padding oracle
269 * attacks do not apply. Besides, due to the use of ephemeral keys
270 * (hopefully with effective replay protection from monotonic time!)
271 * the attacker is limited in using the oracle.
272 */
273 struct GNUNET_ShortHashCode hmac;
274
275 /* followed by as may bytes of payload as indicated in @e header,
276 excluding the TCPBox itself! */
277};
278
279
280/**
281 * TCP rekey message box. Always sent encrypted! Data after
282 * this message will use the new key.
283 */
284struct TCPRekey
285{
286 /**
287 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY.
288 */
289 struct GNUNET_MessageHeader header;
290
291 /**
292 * HMAC for the following encrypted message. Yes, we MUST use
293 * mac-then-encrypt here, as we want to hide the message sizes on
294 * the wire (zero plaintext design!). Using CTR mode padding oracle
295 * attacks do not apply. Besides, due to the use of ephemeral keys
296 * (hopefully with effective replay protection from monotonic time!)
297 * the attacker is limited in using the oracle.
298 */
299 struct GNUNET_ShortHashCode hmac;
300
301 /**
302 * New ephemeral key.
303 */
304 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
305
306 /**
307 * Sender's signature of type #GNUNET_SIGNATURE_PURPOSE_COMMUNICATOR_TCP_REKEY
308 */
309 struct GNUNET_CRYPTO_EddsaSignature sender_sig;
310
311 /**
312 * Monotonic time of @e sender, to possibly help detect replay attacks
313 * (if receiver persists times by sender).
314 */
315 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
316};
317
318/**
319 * Signature we use to verify that the ephemeral key was really chosen by
320 * the specified sender.
321 */
322struct TcpRekeySignature
323{
324 /**
325 * Purpose must be #GNUNET_SIGNATURE_PURPOSE_COMMUNICATOR_TCP_REKEY
326 */
327 struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
328
329 /**
330 * Identity of the inititor of the TCP connection (TCP client).
331 */
332 struct GNUNET_PeerIdentity sender;
333
334 /**
335 * Presumed identity of the target of the TCP connection (TCP server)
336 */
337 struct GNUNET_PeerIdentity receiver;
338
339 /**
340 * Ephemeral key used by the @e sender.
341 */
342 struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
343
344 /**
345 * Monotonic time of @e sender, to possibly help detect replay attacks
346 * (if receiver persists times by sender).
347 */
348 struct GNUNET_TIME_AbsoluteNBO monotonic_time;
349};
350
351/**
352 * TCP finish. Sender asks for the connection to be closed.
353 * Needed/useful in case we drop RST/FIN packets on the GNUnet
354 * port due to the possibility of malicious RST/FIN injection.
355 */
356struct TCPFinish
357{
358 /**
359 * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH.
360 */
361 struct GNUNET_MessageHeader header;
362
363 /**
364 * HMAC for the following encrypted message. Yes, we MUST use
365 * mac-then-encrypt here, as we want to hide the message sizes on
366 * the wire (zero plaintext design!). Using CTR mode padding oracle
367 * attacks do not apply. Besides, due to the use of ephemeral keys
368 * (hopefully with effective replay protection from monotonic time!)
369 * the attacker is limited in using the oracle.
370 */
371 struct GNUNET_ShortHashCode hmac;
372};
373
374/**
375 * Basically a WELCOME message, but with the purpose
376 * of giving the waiting peer a client handle to use
377 */
378struct TCPNATProbeMessage
379{
380 /**
381 * Type is #GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE.
382 */
383 struct GNUNET_MessageHeader header;
384
385 /**
386 * Identity of the sender of the message.
387 */
388 struct GNUNET_PeerIdentity clientIdentity;
389};
390
391GNUNET_NETWORK_STRUCT_END
392
393/**
394 * Struct for pending nat reversals.
395 */
396struct PendingReversal
397{
398 /*
399 * Timeout task.
400 */
401 struct GNUNET_SCHEDULER_Task *timeout_task;
402
403 /**
404 * To whom are we like to talk to.
405 */
406 struct GNUNET_PeerIdentity target;
407
408 /**
409 * Address the reversal was send to.
410 */
411 struct sockaddr *in;
412};
413
414/**
415 * Struct to use as closure.
416 */
417struct ListenTask
418{
419 /**
420 * ID of listen task
421 */
422 struct GNUNET_SCHEDULER_Task *listen_task;
423
424 /**
425 * Listen socket.
426 */
427 struct GNUNET_NETWORK_Handle *listen_sock;
428};
429
430/**
431 * Handle for a queue.
432 */
433struct Queue
434{
435 /**
436 * To whom are we talking to.
437 */
438 struct GNUNET_PeerIdentity target;
439
440 /**
441 * Listen socket.
442 */
443 struct GNUNET_NETWORK_Handle *listen_sock;
444
445 /**
446 * socket that we transmit all data with on this queue
447 */
448 struct GNUNET_NETWORK_Handle *sock;
449
450 /**
451 * cipher for decryption of incoming data.
452 */
453 gcry_cipher_hd_t in_cipher;
454
455 /**
456 * cipher for encryption of outgoing data.
457 */
458 gcry_cipher_hd_t out_cipher;
459
460 /**
461 * Key in hash map
462 */
463 struct GNUNET_HashCode key;
464
465 /**
466 * Shared secret for HMAC verification on incoming data.
467 */
468 struct GNUNET_HashCode in_hmac;
469
470 /**
471 * Shared secret for HMAC generation on outgoing data, ratcheted after
472 * each operation.
473 */
474 struct GNUNET_HashCode out_hmac;
475
476 /**
477 * ID of read task for this connection.
478 */
479 struct GNUNET_SCHEDULER_Task *read_task;
480
481 /**
482 * ID of write task for this connection.
483 */
484 struct GNUNET_SCHEDULER_Task *write_task;
485
486 /**
487 * Address of the other peer.
488 */
489 struct sockaddr *address;
490
491 /**
492 * How many more bytes may we sent with the current @e out_cipher
493 * before we should rekey?
494 */
495 uint64_t rekey_left_bytes;
496
497 /**
498 * Until what time may we sent with the current @e out_cipher
499 * before we should rekey?
500 */
501 struct GNUNET_TIME_Absolute rekey_time;
502
503 /**
504 * Length of the address.
505 */
506 socklen_t address_len;
507
508 /**
509 * Message queue we are providing for the #ch.
510 */
511 struct GNUNET_MQ_Handle *mq;
512
513 /**
514 * handle for this queue with the #ch.
515 */
516 struct GNUNET_TRANSPORT_QueueHandle *qh;
517
518 /**
519 * Number of bytes we currently have in our write queue.
520 */
521 unsigned long long bytes_in_queue;
522
523 /**
524 * Buffer for reading ciphertext from network into.
525 */
526 char cread_buf[BUF_SIZE];
527
528 /**
529 * buffer for writing ciphertext to network.
530 */
531 char cwrite_buf[BUF_SIZE];
532
533 /**
534 * Plaintext buffer for decrypted plaintext.
535 */
536 char pread_buf[UINT16_MAX + 1 + sizeof(struct TCPBox)];
537
538 /**
539 * Plaintext buffer for messages to be encrypted.
540 */
541 char pwrite_buf[UINT16_MAX + 1 + sizeof(struct TCPBox)];
542
543 /**
544 * At which offset in the ciphertext read buffer should we
545 * append more ciphertext for transmission next?
546 */
547 size_t cread_off;
548
549 /**
550 * At which offset in the ciphertext write buffer should we
551 * append more ciphertext from reading next?
552 */
553 size_t cwrite_off;
554
555 /**
556 * At which offset in the plaintext input buffer should we
557 * append more plaintext from decryption next?
558 */
559 size_t pread_off;
560
561 /**
562 * At which offset in the plaintext output buffer should we
563 * append more plaintext for encryption next?
564 */
565 size_t pwrite_off;
566
567 /**
568 * Timeout for this queue.
569 */
570 struct GNUNET_TIME_Absolute timeout;
571
572 /**
573 * How may messages did we pass from this queue to CORE for which we
574 * have yet to receive an acknoweldgement that CORE is done with
575 * them? If "large" (or even just non-zero), we should throttle
576 * reading to provide flow control. See also #DEFAULT_MAX_QUEUE_LENGTH
577 * and #max_queue_length.
578 */
579 unsigned int backpressure;
580
581 /**
582 * Which network type does this queue use?
583 */
584 enum GNUNET_NetworkType nt;
585
586 /**
587 * The connection status of this queue.
588 */
589 enum GNUNET_TRANSPORT_ConnectionStatus cs;
590
591 /**
592 * Is MQ awaiting a #GNUNET_MQ_impl_send_continue() call?
593 */
594 int mq_awaits_continue;
595
596 /**
597 * Did we enqueue a finish message and are closing down the queue?
598 */
599 int finishing;
600
601 /**
602 * Did we technically destroy this queue, but kept the allocation
603 * around because of @e backpressure not being zero yet? Used
604 * simply to delay the final #GNUNET_free() operation until
605 * #core_read_finished_cb() has been called.
606 */
607 int destroyed;
608
609 /**
610 * #GNUNET_YES if we just rekeyed and must thus possibly
611 * re-decrypt ciphertext.
612 */
613 int rekeyed;
614
615 /**
616 * Monotonic time value for rekey message.
617 */
618 struct GNUNET_TIME_AbsoluteNBO rekey_monotonic_time;
619
620 /**
621 * Monotonic time value for handshake message.
622 */
623 struct GNUNET_TIME_AbsoluteNBO handshake_monotonic_time;
624
625 /**
626 * Monotonic time value for handshake ack message.
627 */
628 struct GNUNET_TIME_AbsoluteNBO handshake_ack_monotonic_time;
629
630 /**
631 * Challenge value used to protect against replay attack, if there is no stored monotonic time value.
632 */
633 struct GNUNET_CRYPTO_ChallengeNonceP challenge;
634
635 /**
636 * Challenge value received. In case of inbound connection we have to remember the value, because we send the challenge back later after we received the GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_CONFIRMATION_ACK.
637 */
638 struct GNUNET_CRYPTO_ChallengeNonceP challenge_received;
639
640 /**
641 * Iteration Context for retrieving the monotonic time send with key for rekeying.
642 */
643 struct GNUNET_PEERSTORE_IterateContext *rekey_monotime_get;
644
645 /**
646 * Iteration Context for retrieving the monotonic time send with the handshake.
647 */
648 struct GNUNET_PEERSTORE_IterateContext *handshake_monotime_get;
649
650 /**
651 * Iteration Context for retrieving the monotonic time send with the handshake ack.
652 */
653 struct GNUNET_PEERSTORE_IterateContext *handshake_ack_monotime_get;
654
655 /**
656 * Store Context for retrieving the monotonic time send with key for rekeying.
657 */
658 struct GNUNET_PEERSTORE_StoreContext *rekey_monotime_sc;
659
660 /**
661 * Store Context for retrieving the monotonic time send with the handshake.
662 */
663 struct GNUNET_PEERSTORE_StoreContext *handshake_monotime_sc;
664
665 /**
666 * Store Context for retrieving the monotonic time send with the handshake ack.
667 */
668 struct GNUNET_PEERSTORE_StoreContext *handshake_ack_monotime_sc;
669
670 /**
671 * Size of data received without KX challenge played back.
672 */
673 // TODO remove?
674 size_t unverified_size;
675
676 /**
677 * Has the initial (core) handshake already happened?
678 */
679 int initial_core_kx_done;
680};
681
682
683/**
684 * Handle for an incoming connection where we do not yet have enough
685 * information to setup a full queue.
686 */
687struct ProtoQueue
688{
689 /**
690 * Kept in a DLL.
691 */
692 struct ProtoQueue *next;
693
694 /**
695 * Kept in a DLL.
696 */
697 struct ProtoQueue *prev;
698
699 /**
700 * Listen socket.
701 */
702 struct GNUNET_NETWORK_Handle *listen_sock;
703
704 /**
705 * socket that we transmit all data with on this queue
706 */
707 struct GNUNET_NETWORK_Handle *sock;
708
709 /**
710 * ID of write task for this connection.
711 */
712 struct GNUNET_SCHEDULER_Task *write_task;
713
714 /**
715 * buffer for writing struct TCPNATProbeMessage to network.
716 */
717 char write_buf[sizeof (struct TCPNATProbeMessage)];
718
719 /**
720 * Offset of the buffer?
721 */
722 size_t write_off;
723
724 /**
725 * ID of read task for this connection.
726 */
727 struct GNUNET_SCHEDULER_Task *read_task;
728
729 /**
730 * Address of the other peer.
731 */
732 struct sockaddr *address;
733
734 /**
735 * Length of the address.
736 */
737 socklen_t address_len;
738
739 /**
740 * Timeout for this protoqueue.
741 */
742 struct GNUNET_TIME_Absolute timeout;
743
744 /**
745 * Buffer for reading all the information we need to upgrade from
746 * protoqueue to queue.
747 */
748 char ibuf[INITIAL_KX_SIZE];
749
750 /**
751 * Current offset for reading into @e ibuf.
752 */
753 size_t ibuf_off;
754};
755
756/**
757 * In case of port only configuration we like to bind to ipv4 and ipv6 addresses.
758 */
759struct PortOnlyIpv4Ipv6
760{
761 /**
762 * Ipv4 address we like to bind to.
763 */
764 struct sockaddr *addr_ipv4;
765
766 /**
767 * Length of ipv4 address.
768 */
769 socklen_t addr_len_ipv4;
770
771 /**
772 * Ipv6 address we like to bind to.
773 */
774 struct sockaddr *addr_ipv6;
775
776 /**
777 * Length of ipv6 address.
778 */
779 socklen_t addr_len_ipv6;
780
781};
782
783/**
784 * DLL to store the addresses we like to register at NAT service.
785 */
786struct Addresses
787{
788 /**
789 * Kept in a DLL.
790 */
791 struct Addresses *next;
792
793 /**
794 * Kept in a DLL.
795 */
796 struct Addresses *prev;
797
798 /**
799 * Address we like to register at NAT service.
800 */
801 struct sockaddr *addr;
802
803 /**
804 * Length of address we like to register at NAT service.
805 */
806 socklen_t addr_len;
807
808};
809
810
811/**
812 * Maximum queue length before we stop reading towards the transport service.
813 */
814static unsigned long long max_queue_length;
815
816/**
817 * For logging statistics.
818 */
819static struct GNUNET_STATISTICS_Handle *stats;
820
821/**
822 * Our environment.
823 */
824static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
825
826/**
827 * Queues (map from peer identity to `struct Queue`)
828 */
829static struct GNUNET_CONTAINER_MultiHashMap *queue_map;
830
831/**
832 * ListenTasks (map from socket to `struct ListenTask`)
833 */
834static struct GNUNET_CONTAINER_MultiHashMap *lt_map;
835
836/**
837 * Our public key.
838 */
839static struct GNUNET_PeerIdentity my_identity;
840
841/**
842 * The rekey byte maximum
843 */
844static unsigned long long rekey_max_bytes;
845
846/**
847 * The rekey interval
848 */
849static struct GNUNET_TIME_Relative rekey_interval;
850
851/**
852 * Our private key.
853 */
854static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
855
856/**
857 * Our configuration.
858 */
859static const struct GNUNET_CONFIGURATION_Handle *cfg;
860
861/**
862 * Network scanner to determine network types.
863 */
864static struct GNUNET_NT_InterfaceScanner *is;
865
866/**
867 * Connection to NAT service.
868 */
869static struct GNUNET_NAT_Handle *nat;
870
871/**
872 * Protoqueues DLL head.
873 */
874static struct ProtoQueue *proto_head;
875
876/**
877 * Protoqueues DLL tail.
878 */
879static struct ProtoQueue *proto_tail;
880
881/**
882 * Handle for DNS lookup of bindto address
883 */
884struct GNUNET_RESOLVER_RequestHandle *resolve_request_handle;
885
886/**
887 * Head of DLL with addresses we like to register at NAT servcie.
888 */
889static struct Addresses *addrs_head;
890
891/**
892 * Head of DLL with addresses we like to register at NAT servcie.
893 */
894static struct Addresses *addrs_tail;
895
896/**
897 * Number of addresses in the DLL for register at NAT service.
898 */
899static int addrs_lens;
900
901/**
902 * Database for peer's HELLOs.
903 */
904static struct GNUNET_PEERSTORE_Handle *peerstore;
905
906/**
907* A flag indicating we are already doing a shutdown.
908*/
909static int shutdown_running = GNUNET_NO;
910
911/**
912 * IPv6 disabled.
913 */
914static int disable_v6;
915
916/**
917 * The port the communicator should be assigned to.
918 */
919static unsigned int bind_port;
920
921/**
922 * Map of pending reversals.
923 */
924static struct GNUNET_CONTAINER_MultiHashMap *pending_reversals;
925
926/**
927 * We have been notified that our listen socket has something to
928 * read. Do the read and reschedule this function to be called again
929 * once more is available.
930 *
931 * @param cls NULL
932 */
933static void
934listen_cb (void *cls);
935
936/**
937 * Functions with this signature are called whenever we need
938 * to close a queue due to a disconnect or failure to
939 * establish a connection.
940 *
941 * @param queue queue to close down
942 */
943static void
944queue_destroy (struct Queue *queue)
945{
946 struct ListenTask *lt = NULL;
947 struct GNUNET_HashCode h_sock;
948 int sockfd;
949
950 if (NULL != queue->listen_sock)
951 {
952 sockfd = GNUNET_NETWORK_get_fd (queue->listen_sock);
953 GNUNET_CRYPTO_hash (&sockfd,
954 sizeof(int),
955 &h_sock);
956
957 lt = GNUNET_CONTAINER_multihashmap_get (lt_map, &h_sock);
958 }
959
960 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
961 "Disconnecting queue for peer `%s'\n",
962 GNUNET_i2s (&queue->target));
963 if (NULL != queue->rekey_monotime_sc)
964 {
965 GNUNET_PEERSTORE_store_cancel (queue->rekey_monotime_sc);
966 queue->rekey_monotime_sc = NULL;
967 }
968 if (NULL != queue->handshake_monotime_sc)
969 {
970 GNUNET_PEERSTORE_store_cancel (queue->handshake_monotime_sc);
971 queue->handshake_monotime_sc = NULL;
972 }
973 if (NULL != queue->handshake_ack_monotime_sc)
974 {
975 GNUNET_PEERSTORE_store_cancel (queue->handshake_ack_monotime_sc);
976 queue->handshake_ack_monotime_sc = NULL;
977 }
978 if (NULL != queue->rekey_monotime_get)
979 {
980 GNUNET_PEERSTORE_iteration_stop (queue->rekey_monotime_get);
981 queue->rekey_monotime_get = NULL;
982 }
983 if (NULL != queue->handshake_monotime_get)
984 {
985 GNUNET_PEERSTORE_iteration_stop (queue->handshake_monotime_get);
986 queue->handshake_monotime_get = NULL;
987 }
988 if (NULL != queue->handshake_ack_monotime_get)
989 {
990 GNUNET_PEERSTORE_iteration_stop (queue->handshake_ack_monotime_get);
991 queue->handshake_ack_monotime_get = NULL;
992 }
993 if (NULL != queue->qh)
994 {
995 GNUNET_TRANSPORT_communicator_mq_del (queue->qh);
996 queue->qh = NULL;
997 }
998 GNUNET_assert (
999 GNUNET_YES ==
1000 GNUNET_CONTAINER_multihashmap_remove (queue_map, &queue->key, queue));
1001 GNUNET_STATISTICS_set (stats,
1002 "# queues active",
1003 GNUNET_CONTAINER_multihashmap_size (queue_map),
1004 GNUNET_NO);
1005 if (NULL != queue->read_task)
1006 {
1007 GNUNET_SCHEDULER_cancel (queue->read_task);
1008 queue->read_task = NULL;
1009 }
1010 if (NULL != queue->write_task)
1011 {
1012 GNUNET_SCHEDULER_cancel (queue->write_task);
1013 queue->write_task = NULL;
1014 }
1015 if (GNUNET_SYSERR == GNUNET_NETWORK_socket_close (queue->sock))
1016 {
1017 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1018 "closing socket failed\n");
1019 }
1020 gcry_cipher_close (queue->in_cipher);
1021 gcry_cipher_close (queue->out_cipher);
1022 GNUNET_free (queue->address);
1023 if (0 != queue->backpressure)
1024 queue->destroyed = GNUNET_YES;
1025 else
1026 GNUNET_free (queue);
1027
1028 if (NULL == lt)
1029 return;
1030
1031 if ((! shutdown_running) && (NULL == lt->listen_task))
1032 {
1033 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1034 "add read net listen\n");
1035 lt->listen_task = GNUNET_SCHEDULER_add_read_net (
1036 GNUNET_TIME_UNIT_FOREVER_REL,
1037 lt->listen_sock,
1038 &listen_cb,
1039 lt);
1040 }
1041 else
1042 GNUNET_free (lt);
1043}
1044
1045
1046/**
1047 * Compute @a mac over @a buf, and ratched the @a hmac_secret.
1048 *
1049 * @param[in,out] hmac_secret secret for HMAC calculation
1050 * @param buf buffer to MAC
1051 * @param buf_size number of bytes in @a buf
1052 * @param[out] smac where to write the HMAC
1053 */
1054static void
1055calculate_hmac (struct GNUNET_HashCode *hmac_secret,
1056 const void *buf,
1057 size_t buf_size,
1058 struct GNUNET_ShortHashCode *smac)
1059{
1060 struct GNUNET_HashCode mac;
1061
1062 GNUNET_CRYPTO_hmac_raw (hmac_secret,
1063 sizeof(struct GNUNET_HashCode),
1064 buf,
1065 buf_size,
1066 &mac);
1067 /* truncate to `struct GNUNET_ShortHashCode` */
1068 memcpy (smac, &mac, sizeof(struct GNUNET_ShortHashCode));
1069 /* ratchet hmac key */
1070 GNUNET_CRYPTO_hash (hmac_secret,
1071 sizeof(struct GNUNET_HashCode),
1072 hmac_secret);
1073}
1074
1075
1076/**
1077 * Append a 'finish' message to the outgoing transmission. Once the
1078 * finish has been transmitted, destroy the queue.
1079 *
1080 * @param queue queue to shut down nicely
1081 */
1082static void
1083queue_finish (struct Queue *queue)
1084{
1085 struct TCPFinish fin;
1086
1087 memset (&fin, 0, sizeof(fin));
1088 fin.header.size = htons (sizeof(fin));
1089 fin.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH);
1090 calculate_hmac (&queue->out_hmac, &fin, sizeof(fin), &fin.hmac);
1091 /* if there is any message left in pwrite_buf, we
1092 overwrite it (possibly dropping the last message
1093 from CORE hard here) */
1094 memcpy (queue->pwrite_buf, &fin, sizeof(fin));
1095 queue->pwrite_off = sizeof(fin);
1096 /* This flag will ensure that #queue_write() no longer
1097 notifies CORE about the possibility of sending
1098 more data, and that #queue_write() will call
1099 #queue_destroy() once the @c fin was fully written. */
1100 queue->finishing = GNUNET_YES;
1101}
1102
1103
1104/**
1105 * Queue read task. If we hit the timeout, disconnect it
1106 *
1107 * @param cls the `struct Queue *` to disconnect
1108 */
1109static void
1110queue_read (void *cls);
1111
1112
1113/**
1114 * Core tells us it is done processing a message that transport
1115 * received on a queue with status @a success.
1116 *
1117 * @param cls a `struct Queue *` where the message originally came from
1118 * @param success #GNUNET_OK on success
1119 */
1120static void
1121core_read_finished_cb (void *cls, int success)
1122{
1123 struct Queue *queue = cls;
1124 if (GNUNET_OK != success)
1125 GNUNET_STATISTICS_update (stats,
1126 "# messages lost in communicator API towards CORE",
1127 1,
1128 GNUNET_NO);
1129 if (NULL == queue)
1130 return;
1131
1132 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1133 "backpressure %u\n",
1134 queue->backpressure);
1135
1136 queue->backpressure--;
1137 /* handle deferred queue destruction */
1138 if ((queue->destroyed) && (0 == queue->backpressure))
1139 {
1140 GNUNET_free (queue);
1141 return;
1142 }
1143 else if (GNUNET_YES != queue->destroyed)
1144 {
1145 queue->timeout =
1146 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT
1147 );
1148 /* possibly unchoke reading, now that CORE made progress */
1149 if (NULL == queue->read_task)
1150 queue->read_task =
1151 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining (
1152 queue->timeout),
1153 queue->sock,
1154 &queue_read,
1155 queue);
1156 }
1157}
1158
1159
1160/**
1161 * We received @a plaintext_len bytes of @a plaintext on @a queue.
1162 * Pass it on to CORE. If transmission is actually happening,
1163 * increase backpressure counter.
1164 *
1165 * @param queue the queue that received the plaintext
1166 * @param plaintext the plaintext that was received
1167 * @param plaintext_len number of bytes of plaintext received
1168 */
1169static void
1170pass_plaintext_to_core (struct Queue *queue,
1171 const void *plaintext,
1172 size_t plaintext_len)
1173{
1174 const struct GNUNET_MessageHeader *hdr = plaintext;
1175 int ret;
1176
1177 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1178 "pass message from %s to core\n",
1179 GNUNET_i2s (&queue->target));
1180
1181 if (ntohs (hdr->size) != plaintext_len)
1182 {
1183 /* NOTE: If we ever allow multiple CORE messages in one
1184 BOX, this will have to change! */
1185 GNUNET_break (0);
1186 return;
1187 }
1188 ret = GNUNET_TRANSPORT_communicator_receive (ch,
1189 &queue->target,
1190 hdr,
1191 ADDRESS_VALIDITY_PERIOD,
1192 &core_read_finished_cb,
1193 queue);
1194 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1195 "passed to core\n");
1196 if (GNUNET_OK == ret)
1197 queue->backpressure++;
1198 GNUNET_break (GNUNET_NO != ret); /* backpressure not working!? */
1199 if (GNUNET_SYSERR == ret)
1200 GNUNET_STATISTICS_update (stats,
1201 "# bytes lost due to CORE not running",
1202 plaintext_len,
1203 GNUNET_NO);
1204}
1205
1206
1207/**
1208 * Setup @a cipher based on shared secret @a dh and decrypting
1209 * peer @a pid.
1210 *
1211 * @param dh shared secret
1212 * @param pid decrypting peer's identity
1213 * @param[out] cipher cipher to initialize
1214 * @param[out] hmac_key HMAC key to initialize
1215 */
1216static void
1217setup_cipher (const struct GNUNET_HashCode *dh,
1218 const struct GNUNET_PeerIdentity *pid,
1219 gcry_cipher_hd_t *cipher,
1220 struct GNUNET_HashCode *hmac_key)
1221{
1222 char key[256 / 8];
1223 char ctr[128 / 8];
1224
1225 GNUNET_assert (0 == gcry_cipher_open (cipher,
1226 GCRY_CIPHER_AES256 /* low level: go for speed */
1227 ,
1228 GCRY_CIPHER_MODE_CTR,
1229 0 /* flags */));
1230 GNUNET_assert (GNUNET_YES == GNUNET_CRYPTO_kdf (key,
1231 sizeof(key),
1232 "TCP-key",
1233 strlen ("TCP-key"),
1234 dh,
1235 sizeof(*dh),
1236 pid,
1237 sizeof(*pid),
1238 NULL,
1239 0));
1240 GNUNET_assert (0 == gcry_cipher_setkey (*cipher, key, sizeof(key)));
1241 GNUNET_assert (GNUNET_YES == GNUNET_CRYPTO_kdf (ctr,
1242 sizeof(ctr),
1243 "TCP-ctr",
1244 strlen ("TCP-ctr"),
1245 dh,
1246 sizeof(*dh),
1247 pid,
1248 sizeof(*pid),
1249 NULL,
1250 0));
1251 gcry_cipher_setctr (*cipher, ctr, sizeof(ctr));
1252 GNUNET_assert (GNUNET_YES ==
1253 GNUNET_CRYPTO_kdf (hmac_key,
1254 sizeof(struct GNUNET_HashCode),
1255 "TCP-hmac",
1256 strlen ("TCP-hmac"),
1257 dh,
1258 sizeof(*dh),
1259 pid,
1260 sizeof(*pid),
1261 NULL,
1262 0));
1263}
1264
1265
1266/**
1267 * Callback called when peerstore store operation for rekey monotime value is finished.
1268 * @param cls Queue context the store operation was executed.
1269 * @param success Store operation was successful (GNUNET_OK) or not.
1270 */
1271static void
1272rekey_monotime_store_cb (void *cls, int success)
1273{
1274 struct Queue *queue = cls;
1275 if (GNUNET_OK != success)
1276 {
1277 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1278 "Failed to store rekey monotonic time in PEERSTORE!\n");
1279 }
1280 queue->rekey_monotime_sc = NULL;
1281 GNUNET_PEERSTORE_iteration_next (queue->rekey_monotime_get, 1);
1282}
1283
1284
1285/**
1286 * Callback called by peerstore when records for GNUNET_PEERSTORE_TRANSPORT_TCP_COMMUNICATOR_REKEY
1287 * where found.
1288 * @param cls Queue context the store operation was executed.
1289 * @param record The record found or NULL if there is no record left.
1290 * @param emsg Message from peerstore.
1291 */
1292static void
1293rekey_monotime_cb (void *cls,
1294 const struct GNUNET_PEERSTORE_Record *record,
1295 const char *emsg)
1296{
1297 struct Queue *queue = cls;
1298 struct GNUNET_TIME_AbsoluteNBO *mtbe;
1299 struct GNUNET_TIME_Absolute mt;
1300 const struct GNUNET_PeerIdentity *pid;
1301 struct GNUNET_TIME_AbsoluteNBO *rekey_monotonic_time;
1302
1303 (void) emsg;
1304
1305 rekey_monotonic_time = &queue->rekey_monotonic_time;
1306 pid = &queue->target;
1307 if (NULL == record)
1308 {
1309 queue->rekey_monotime_get = NULL;
1310 return;
1311 }
1312 if (sizeof(*mtbe) != record->value_size)
1313 {
1314 GNUNET_PEERSTORE_iteration_next (queue->rekey_monotime_get, 1);
1315 GNUNET_break (0);
1316 return;
1317 }
1318 mtbe = record->value;
1319 mt = GNUNET_TIME_absolute_ntoh (*mtbe);
1320 if (mt.abs_value_us > GNUNET_TIME_absolute_ntoh (
1321 queue->rekey_monotonic_time).abs_value_us)
1322 {
1323 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1324 "Queue from %s dropped, rekey monotime in the past\n",
1325 GNUNET_i2s (&queue->target));
1326 GNUNET_break (0);
1327 GNUNET_PEERSTORE_iteration_stop (queue->rekey_monotime_get);
1328 queue->rekey_monotime_get = NULL;
1329 // FIXME: Why should we try to gracefully finish here??
1330 queue_finish (queue);
1331 return;
1332 }
1333 queue->rekey_monotime_sc = GNUNET_PEERSTORE_store (peerstore,
1334 "transport_tcp_communicator",
1335 pid,
1336 GNUNET_PEERSTORE_TRANSPORT_TCP_COMMUNICATOR_REKEY,
1337 rekey_monotonic_time,
1338 sizeof(*
1339 rekey_monotonic_time),
1340 GNUNET_TIME_UNIT_FOREVER_ABS,
1341 GNUNET_PEERSTORE_STOREOPTION_REPLACE,
1342 &rekey_monotime_store_cb,
1343 queue);
1344}
1345
1346
1347/**
1348 * Setup cipher of @a queue for decryption.
1349 *
1350 * @param ephemeral ephemeral key we received from the other peer
1351 * @param[in,out] queue queue to initialize decryption cipher for
1352 */
1353static void
1354setup_in_cipher (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
1355 struct Queue *queue)
1356{
1357 struct GNUNET_HashCode k;
1358
1359 GNUNET_CRYPTO_eddsa_kem_decaps (my_private_key, ephemeral, &k);
1360 setup_cipher (&k, &my_identity, &queue->in_cipher, &queue->in_hmac);
1361}
1362
1363
1364/**
1365 * Handle @a rekey message on @a queue. The message was already
1366 * HMAC'ed, but we should additionally still check the signature.
1367 * Then we need to stop the old cipher and start afresh.
1368 *
1369 * @param queue the queue @a rekey was received on
1370 * @param rekey the rekey message
1371 */
1372static void
1373do_rekey (struct Queue *queue, const struct TCPRekey *rekey)
1374{
1375 struct TcpRekeySignature thp;
1376
1377 thp.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_COMMUNICATOR_TCP_REKEY);
1378 thp.purpose.size = htonl (sizeof(thp));
1379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1380 "do_rekey size %u\n",
1381 thp.purpose.size);
1382 thp.sender = queue->target;
1383 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1384 "sender %s\n",
1385 GNUNET_p2s (&thp.sender.public_key));
1386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1387 "sender %s\n",
1388 GNUNET_p2s (&queue->target.public_key));
1389 thp.receiver = my_identity;
1390 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1391 "receiver %s\n",
1392 GNUNET_p2s (&thp.receiver.public_key));
1393 thp.ephemeral = rekey->ephemeral;
1394 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1395 "ephemeral %s\n",
1396 GNUNET_e2s (&thp.ephemeral));
1397 thp.monotonic_time = rekey->monotonic_time;
1398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1399 "time %s\n",
1400 GNUNET_STRINGS_absolute_time_to_string (
1401 GNUNET_TIME_absolute_ntoh (thp.monotonic_time)));
1402 GNUNET_assert (ntohl ((&thp)->purpose.size) == sizeof (*(&thp)));
1403 if (GNUNET_OK !=
1404 GNUNET_CRYPTO_eddsa_verify (
1405 GNUNET_SIGNATURE_PURPOSE_COMMUNICATOR_TCP_REKEY,
1406 &thp,
1407 &rekey->sender_sig,
1408 &queue->target.public_key))
1409 {
1410 GNUNET_break (0);
1411 // FIXME Why should we try to gracefully finish here?
1412 queue_finish (queue);
1413 return;
1414 }
1415 queue->rekey_monotonic_time = rekey->monotonic_time;
1416 queue->rekey_monotime_get = GNUNET_PEERSTORE_iteration_start (peerstore,
1417 "transport_tcp_communicator",
1418 &queue->target,
1419 GNUNET_PEERSTORE_TRANSPORT_TCP_COMMUNICATOR_REKEY,
1420 &
1421 rekey_monotime_cb,
1422 queue);
1423 gcry_cipher_close (queue->in_cipher);
1424 queue->rekeyed = GNUNET_YES;
1425 setup_in_cipher (&rekey->ephemeral, queue);
1426}
1427
1428
1429/**
1430 * Callback called when peerstore store operation for handshake ack monotime value is finished.
1431 * @param cls Queue context the store operation was executed.
1432 * @param success Store operation was successful (GNUNET_OK) or not.
1433 */
1434static void
1435handshake_ack_monotime_store_cb (void *cls, int success)
1436{
1437 struct Queue *queue = cls;
1438
1439 if (GNUNET_OK != success)
1440 {
1441 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1442 "Failed to store handshake ack monotonic time in PEERSTORE!\n");
1443 }
1444 queue->handshake_ack_monotime_sc = NULL;
1445 GNUNET_PEERSTORE_iteration_next (queue->handshake_ack_monotime_get, 1);
1446}
1447
1448
1449/**
1450 * Callback called by peerstore when records for GNUNET_PEERSTORE_TRANSPORT_TCP_COMMUNICATOR_HANDSHAKE_ACK
1451 * where found.
1452 * @param cls Queue context the store operation was executed.
1453 * @param record The record found or NULL if there is no record left.
1454 * @param emsg Message from peerstore.
1455 */
1456static void
1457handshake_ack_monotime_cb (void *cls,
1458 const struct GNUNET_PEERSTORE_Record *record,
1459 const char *emsg)
1460{
1461 struct Queue *queue = cls;
1462 struct GNUNET_TIME_AbsoluteNBO *mtbe;
1463 struct GNUNET_TIME_Absolute mt;
1464 const struct GNUNET_PeerIdentity *pid;
1465 struct GNUNET_TIME_AbsoluteNBO *handshake_ack_monotonic_time;
1466
1467 (void) emsg;
1468
1469 handshake_ack_monotonic_time = &queue->handshake_ack_monotonic_time;
1470 pid = &queue->target;
1471 if (NULL == record)
1472 {
1473 queue->handshake_ack_monotime_get = NULL;
1474 return;
1475 }
1476 if (sizeof(*mtbe) != record->value_size)
1477 {
1478 GNUNET_PEERSTORE_iteration_next (queue->handshake_ack_monotime_get, 1);
1479 GNUNET_break (0);
1480 return;
1481 }
1482 mtbe = record->value;
1483 mt = GNUNET_TIME_absolute_ntoh (*mtbe);
1484 if (mt.abs_value_us > GNUNET_TIME_absolute_ntoh (
1485 queue->handshake_ack_monotonic_time).abs_value_us)
1486 {
1487 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1488 "Queue from %s dropped, handshake ack monotime in the past\n",
1489 GNUNET_i2s (&queue->target));
1490 GNUNET_break (0);
1491 GNUNET_PEERSTORE_iteration_stop (queue->handshake_ack_monotime_get);
1492 queue->handshake_ack_monotime_get = NULL;
1493 // FIXME: Why should we try to gracefully finish here?
1494 queue_finish (queue);
1495 return;
1496 }
1497 queue->handshake_ack_monotime_sc =
1498 GNUNET_PEERSTORE_store (peerstore,
1499 "transport_tcp_communicator",
1500 pid,
1501 GNUNET_PEERSTORE_TRANSPORT_TCP_COMMUNICATOR_HANDSHAKE_ACK,
1502 handshake_ack_monotonic_time,
1503 sizeof(*handshake_ack_monotonic_time),
1504 GNUNET_TIME_UNIT_FOREVER_ABS,
1505 GNUNET_PEERSTORE_STOREOPTION_REPLACE,
1506 &handshake_ack_monotime_store_cb,
1507 queue);
1508}
1509
1510
1511/**
1512 * Sending challenge with TcpConfirmationAck back to sender of ephemeral key.
1513 *
1514 * @param tc The TCPConfirmation originally send.
1515 * @param queue The queue context.
1516 */
1517static void
1518send_challenge (struct GNUNET_CRYPTO_ChallengeNonceP challenge,
1519 struct Queue *queue)
1520{
1521 struct TCPConfirmationAck tca;
1522 struct TcpHandshakeAckSignature thas;
1523
1524 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1525 "sending challenge\n");
1526
1527 tca.header.type = ntohs (
1528 GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_CONFIRMATION_ACK);
1529 tca.header.size = ntohs (sizeof(tca));
1530 tca.challenge = challenge;
1531 tca.sender = my_identity;
1532 tca.monotonic_time =
1533 GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1534 thas.purpose.purpose = htonl (
1535 GNUNET_SIGNATURE_PURPOSE_COMMUNICATOR_TCP_HANDSHAKE_ACK);
1536 thas.purpose.size = htonl (sizeof(thas));
1537 thas.sender = my_identity;
1538 thas.receiver = queue->target;
1539 thas.monotonic_time = tca.monotonic_time;
1540 thas.challenge = tca.challenge;
1541 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1542 &thas,
1543 &tca.sender_sig);
1544 GNUNET_assert (0 ==
1545 gcry_cipher_encrypt (queue->out_cipher,
1546 &queue->cwrite_buf[queue->cwrite_off],
1547 sizeof(tca),
1548 &tca,
1549 sizeof(tca)));
1550 queue->cwrite_off += sizeof(tca);
1551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1552 "sending challenge done\n");
1553}
1554
1555
1556/**
1557 * Setup cipher for outgoing data stream based on target and
1558 * our ephemeral private key.
1559 *
1560 * @param queue queue to setup outgoing (encryption) cipher for
1561 */
1562static void
1563setup_out_cipher (struct Queue *queue, struct GNUNET_HashCode *dh)
1564{
1565 setup_cipher (dh, &queue->target, &queue->out_cipher, &queue->out_hmac);
1566 queue->rekey_time = GNUNET_TIME_relative_to_absolute (rekey_interval);
1567 queue->rekey_left_bytes =
1568 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, rekey_max_bytes);
1569}
1570
1571
1572/**
1573 * Inject a `struct TCPRekey` message into the queue's plaintext
1574 * buffer.
1575 *
1576 * @param queue queue to perform rekeying on
1577 */
1578static void
1579inject_rekey (struct Queue *queue)
1580{
1581 struct TCPRekey rekey;
1582 struct TcpRekeySignature thp;
1583 struct GNUNET_HashCode k;
1584
1585 GNUNET_assert (0 == queue->pwrite_off);
1586 memset (&rekey, 0, sizeof(rekey));
1587 GNUNET_CRYPTO_eddsa_kem_encaps (&queue->target.public_key, &rekey.ephemeral,
1588 &k);
1589 rekey.header.type = ntohs (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY);
1590 rekey.header.size = ntohs (sizeof(rekey));
1591 rekey.monotonic_time =
1592 GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1593 thp.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_COMMUNICATOR_TCP_REKEY);
1594 thp.purpose.size = htonl (sizeof(thp));
1595 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1596 "inject_rekey size %u\n",
1597 thp.purpose.size);
1598 thp.sender = my_identity;
1599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1600 "sender %s\n",
1601 GNUNET_p2s (&thp.sender.public_key));
1602 thp.receiver = queue->target;
1603 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1604 "receiver %s\n",
1605 GNUNET_p2s (&thp.receiver.public_key));
1606 thp.ephemeral = rekey.ephemeral;
1607 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1608 "ephemeral %s\n",
1609 GNUNET_e2s (&thp.ephemeral));
1610 thp.monotonic_time = rekey.monotonic_time;
1611 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1612 "time %s\n",
1613 GNUNET_STRINGS_absolute_time_to_string (
1614 GNUNET_TIME_absolute_ntoh (thp.monotonic_time)));
1615 GNUNET_CRYPTO_eddsa_sign (my_private_key,
1616 &thp,
1617 &rekey.sender_sig);
1618 calculate_hmac (&queue->out_hmac, &rekey, sizeof(rekey), &rekey.hmac);
1619 /* Encrypt rekey message with 'old' cipher */
1620 GNUNET_assert (0 ==
1621 gcry_cipher_encrypt (queue->out_cipher,
1622 &queue->cwrite_buf[queue->cwrite_off],
1623 sizeof(rekey),
1624 &rekey,
1625 sizeof(rekey)));
1626 queue->cwrite_off += sizeof(rekey);
1627 /* Setup new cipher for successive messages */
1628 gcry_cipher_close (queue->out_cipher);
1629 setup_out_cipher (queue, &k);
1630}
1631
1632
1633static int
1634pending_reversals_delete_it (void *cls,
1635 const struct GNUNET_HashCode *key,
1636 void *value)
1637{
1638 (void) cls;
1639 struct PendingReversal *pending_reversal = value;
1640
1641 if (NULL != pending_reversal->timeout_task)
1642 {
1643 GNUNET_SCHEDULER_cancel (pending_reversal->timeout_task);
1644 pending_reversal->timeout_task = NULL;
1645 }
1646 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (
1647 pending_reversals,
1648 key,
1649 pending_reversal));
1650 GNUNET_free (pending_reversal->in);
1651 GNUNET_free (pending_reversal);
1652 return GNUNET_OK;
1653}
1654
1655
1656static void
1657check_and_remove_pending_reversal (struct sockaddr *in, sa_family_t sa_family,
1658 struct GNUNET_PeerIdentity *sender)
1659{
1660 if (AF_INET == sa_family)
1661 {
1662 struct PendingReversal *pending_reversal;
1663 struct GNUNET_HashCode key;
1664 struct sockaddr_in *natted_address;
1665
1666 natted_address = GNUNET_memdup (in, sizeof (struct sockaddr));
1667 natted_address->sin_port = 0;
1668 GNUNET_CRYPTO_hash (natted_address,
1669 sizeof(struct sockaddr),
1670 &key);
1671
1672 pending_reversal = GNUNET_CONTAINER_multihashmap_get (pending_reversals,
1673 &key);
1674 if (NULL != pending_reversal && (NULL == sender ||
1675 0 != memcmp (sender,
1676 &pending_reversal->target,
1677 sizeof(struct
1678 GNUNET_PeerIdentity))))
1679 {
1680 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1681 "Removing invalid pending reversal for `%s'at `%s'\n",
1682 GNUNET_i2s (&pending_reversal->target),
1683 GNUNET_a2s (in, sizeof (struct sockaddr)));
1684 pending_reversals_delete_it (NULL, &key, pending_reversal);
1685 }
1686 GNUNET_free (natted_address);
1687 }
1688}
1689
1690
1691/**
1692 * Closes socket and frees memory associated with @a pq.
1693 *
1694 * @param pq proto queue to free
1695 */
1696static void
1697free_proto_queue (struct ProtoQueue *pq)
1698{
1699 if (NULL != pq->listen_sock)
1700 {
1701 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pq->listen_sock));
1702 pq->listen_sock = NULL;
1703 }
1704 if (NULL != pq->read_task)
1705 {
1706 GNUNET_SCHEDULER_cancel (pq->read_task);
1707 pq->read_task = NULL;
1708 }
1709 if (NULL != pq->write_task)
1710 {
1711 GNUNET_SCHEDULER_cancel (pq->write_task);
1712 pq->write_task = NULL;
1713 }
1714 check_and_remove_pending_reversal (pq->address, pq->address->sa_family, NULL);
1715 GNUNET_NETWORK_socket_close (pq->sock);
1716 GNUNET_free (pq->address);
1717 GNUNET_CONTAINER_DLL_remove (proto_head, proto_tail, pq);
1718 GNUNET_free (pq);
1719}
1720
1721
1722/**
1723 * We have been notified that our socket is ready to write.
1724 * Then reschedule this function to be called again once more is available.
1725 *
1726 * @param cls a `struct ProtoQueue`
1727 */
1728static void
1729proto_queue_write (void *cls)
1730{
1731 struct ProtoQueue *pq = cls;
1732 ssize_t sent;
1733 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "In proto queue write\n");
1734 pq->write_task = NULL;
1735 if (0 != pq->write_off)
1736 {
1737 sent = GNUNET_NETWORK_socket_send (pq->sock,
1738 pq->write_buf,
1739 pq->write_off);
1740 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1741 "Sent %lu bytes to TCP queue\n", sent);
1742 if ((-1 == sent) && (EAGAIN != errno) && (EINTR != errno))
1743 {
1744 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "send");
1745 free_proto_queue (pq);
1746 return;
1747 }
1748 if (sent > 0)
1749 {
1750 size_t usent = (size_t) sent;
1751 pq->write_off -= usent;
1752 memmove (pq->write_buf,
1753 &pq->write_buf[usent],
1754 pq->write_off);
1755 }
1756 }
1757 /* do we care to write more? */
1758 if ((0 < pq->write_off))
1759 pq->write_task =
1760 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1761 pq->sock,
1762 &proto_queue_write,
1763 pq);
1764}
1765
1766
1767/**
1768 * We have been notified that our socket is ready to write.
1769 * Then reschedule this function to be called again once more is available.
1770 *
1771 * @param cls a `struct Queue`
1772 */
1773static void
1774queue_write (void *cls)
1775{
1776 struct Queue *queue = cls;
1777 ssize_t sent;
1778 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "In queue write\n");
1779 queue->write_task = NULL;
1780 if (0 != queue->cwrite_off)
1781 {
1782 sent = GNUNET_NETWORK_socket_send (queue->sock,
1783 queue->cwrite_buf,
1784 queue->cwrite_off);
1785 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1786 "Sent %lu bytes to TCP queue\n", sent);
1787 if ((-1 == sent) && (EAGAIN != errno) && (EINTR != errno))
1788 {
1789 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "send");
1790 queue_destroy (queue);
1791 return;
1792 }
1793 if (sent > 0)
1794 {
1795 size_t usent = (size_t) sent;
1796 queue->cwrite_off -= usent;
1797 memmove (queue->cwrite_buf,
1798 &queue->cwrite_buf[usent],
1799 queue->cwrite_off);
1800 queue->timeout =
1801 GNUNET_TIME_relative_to_absolute (
1802 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1803 }
1804 }
1805 /* can we encrypt more? (always encrypt full messages, needed
1806 such that #mq_cancel() can work!) */
1807 unsigned int we_do_not_need_to_rekey = (0 < queue->rekey_left_bytes
1808 - (queue->cwrite_off
1809 + queue->pwrite_off
1810 + sizeof (struct TCPRekey)));
1811 if (we_do_not_need_to_rekey &&
1812 (queue->pwrite_off > 0) &&
1813 (queue->cwrite_off + queue->pwrite_off <= BUF_SIZE))
1814 {
1815 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1816 "Encrypting %lu bytes\n", queue->pwrite_off);
1817 GNUNET_assert (0 ==
1818 gcry_cipher_encrypt (queue->out_cipher,
1819 &queue->cwrite_buf[queue->cwrite_off],
1820 queue->pwrite_off,
1821 queue->pwrite_buf,
1822 queue->pwrite_off));
1823 if (queue->rekey_left_bytes > queue->pwrite_off)
1824 queue->rekey_left_bytes -= queue->pwrite_off;
1825 else
1826 queue->rekey_left_bytes = 0;
1827 queue->cwrite_off += queue->pwrite_off;
1828 queue->pwrite_off = 0;
1829 }
1830 // if ((-1 != unverified_size)&& ((0 == queue->pwrite_off) &&
1831 if (((0 == queue->rekey_left_bytes) ||
1832 (0 == GNUNET_TIME_absolute_get_remaining (
1833 queue->rekey_time).rel_value_us)) &&
1834 (((0 == queue->pwrite_off) || ! we_do_not_need_to_rekey) &&
1835 (queue->cwrite_off + sizeof (struct TCPRekey) <= BUF_SIZE)))
1836 {
1837 inject_rekey (queue);
1838 }
1839 if ((0 == queue->pwrite_off) && (! queue->finishing) &&
1840 (GNUNET_YES == queue->mq_awaits_continue))
1841 {
1842 queue->mq_awaits_continue = GNUNET_NO;
1843 GNUNET_MQ_impl_send_continue (queue->mq);
1844 }
1845 /* did we just finish writing 'finish'? */
1846 if ((0 == queue->cwrite_off) && (GNUNET_YES == queue->finishing))
1847 {
1848 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1849 "Finishing queue\n");
1850 queue_destroy (queue);
1851 return;
1852 }
1853 /* do we care to write more? */
1854 if ((0 < queue->cwrite_off) || (0 < queue->pwrite_off))
1855 queue->write_task =
1856 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1857 queue->sock,
1858 &queue_write,
1859 queue);
1860}
1861
1862
1863/**
1864 * Test if we have received a full message in plaintext.
1865 * If so, handle it.
1866 *
1867 * @param queue queue to process inbound plaintext for
1868 * @return number of bytes of plaintext handled, 0 for none
1869 */
1870static size_t
1871try_handle_plaintext (struct Queue *queue)
1872{
1873 const struct GNUNET_MessageHeader *hdr;
1874 const struct TCPConfirmationAck *tca;
1875 const struct TCPBox *box;
1876 const struct TCPRekey *rekey;
1877 const struct TCPFinish *fin;
1878 struct TCPRekey rekeyz;
1879 struct TCPFinish finz;
1880 struct GNUNET_ShortHashCode tmac;
1881 uint16_t type;
1882 size_t size = 0;
1883 struct TcpHandshakeAckSignature thas;
1884 const struct GNUNET_CRYPTO_ChallengeNonceP challenge = queue->challenge;
1885
1886 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1887 "try handle plaintext!\n");
1888
1889 hdr = (const struct GNUNET_MessageHeader *) queue->pread_buf;
1890 if ((sizeof(*hdr) > queue->pread_off))
1891 {
1892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1893 "Handling plaintext, not even a header!\n");
1894 return 0; /* not even a header */
1895 }
1896
1897 if ((GNUNET_YES != queue->initial_core_kx_done) && (queue->unverified_size >
1898 INITIAL_CORE_KX_SIZE))
1899 {
1900 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1901 "Already received data of size %lu bigger than KX size %lu!\n",
1902 queue->unverified_size,
1903 INITIAL_CORE_KX_SIZE);
1904 GNUNET_break_op (0);
1905 queue_finish (queue);
1906 return 0;
1907 }
1908
1909 type = ntohs (hdr->type);
1910 switch (type)
1911 {
1912 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_CONFIRMATION_ACK:
1913 tca = (const struct TCPConfirmationAck *) queue->pread_buf;
1914 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1915 "start processing ack\n");
1916 if (sizeof(*tca) > queue->pread_off)
1917 {
1918 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1919 "Handling plaintext size of tca greater than pread offset.\n")
1920 ;
1921 return 0;
1922 }
1923 if (ntohs (hdr->size) != sizeof(*tca))
1924 {
1925 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1926 "Handling plaintext size does not match message type.\n");
1927 GNUNET_break_op (0);
1928 queue_finish (queue);
1929 return 0;
1930 }
1931
1932 thas.purpose.purpose = htonl (
1933 GNUNET_SIGNATURE_PURPOSE_COMMUNICATOR_TCP_HANDSHAKE_ACK);
1934 thas.purpose.size = htonl (sizeof(thas));
1935 thas.sender = tca->sender;
1936 thas.receiver = my_identity;
1937 thas.monotonic_time = tca->monotonic_time;
1938 thas.challenge = tca->challenge;
1939
1940 if (GNUNET_SYSERR == GNUNET_CRYPTO_eddsa_verify (
1941 GNUNET_SIGNATURE_PURPOSE_COMMUNICATOR_TCP_HANDSHAKE_ACK,
1942 &thas,
1943 &tca->sender_sig,
1944 &tca->sender.public_key))
1945 {
1946 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1947 "Verification of signature failed!\n");
1948 GNUNET_break (0);
1949 queue_finish (queue);
1950 return 0;
1951 }
1952 if (0 != GNUNET_memcmp (&tca->challenge, &challenge))
1953 {
1954 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1955 "Challenge in TCPConfirmationAck not correct!\n");
1956 GNUNET_break (0);
1957 queue_finish (queue);
1958 return 0;
1959 }
1960
1961 queue->handshake_ack_monotime_get = GNUNET_PEERSTORE_iteration_start (
1962 peerstore,
1963 "transport_tcp_communicator",
1964 &queue->target,
1965 GNUNET_PEERSTORE_TRANSPORT_TCP_COMMUNICATOR_HANDSHAKE_ACK,
1966 &handshake_ack_monotime_cb,
1967 queue);
1968
1969 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1970 "Handling plaintext, ack processed!\n");
1971
1972 if (GNUNET_TRANSPORT_CS_INBOUND == queue->cs)
1973 {
1974 send_challenge (queue->challenge_received, queue);
1975 queue->write_task =
1976 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1977 queue->sock,
1978 &queue_write,
1979 queue);
1980 }
1981 else if (GNUNET_TRANSPORT_CS_OUTBOUND == queue->cs)
1982 {
1983 check_and_remove_pending_reversal (queue->address,
1984 queue->address->sa_family, NULL);
1985 }
1986
1987 /**
1988 * Once we received this ack, we consider this a verified connection.
1989 * FIXME: I am not sure this logic is sane here.
1990 */
1991 queue->initial_core_kx_done = GNUNET_YES;
1992
1993 char *foreign_addr;
1994
1995 switch (queue->address->sa_family)
1996 {
1997 case AF_INET:
1998 GNUNET_asprintf (&foreign_addr,
1999 "%s-%s",
2000 COMMUNICATOR_ADDRESS_PREFIX,
2001 GNUNET_a2s (queue->address, queue->address_len));
2002 break;
2003
2004 case AF_INET6:
2005 GNUNET_asprintf (&foreign_addr,
2006 "%s-%s",
2007 COMMUNICATOR_ADDRESS_PREFIX,
2008 GNUNET_a2s (queue->address, queue->address_len));
2009 break;
2010
2011 default:
2012 GNUNET_assert (0);
2013 }
2014
2015 queue->qh = GNUNET_TRANSPORT_communicator_mq_add (ch,
2016 &queue->target,
2017 foreign_addr,
2018 UINT16_MAX, /* no MTU */
2019 GNUNET_TRANSPORT_QUEUE_LENGTH_UNLIMITED,
2020 0, /* Priority */
2021 queue->nt,
2022 queue->cs,
2023 queue->mq);
2024
2025 GNUNET_free (foreign_addr);
2026
2027 size = ntohs (hdr->size);
2028 break;
2029 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX:
2030 /* Special case: header size excludes box itself! */
2031 box = (const struct TCPBox *) queue->pread_buf;
2032 if (ntohs (hdr->size) + sizeof(struct TCPBox) > queue->pread_off)
2033 return 0;
2034 calculate_hmac (&queue->in_hmac, &box[1], ntohs (hdr->size), &tmac);
2035 if (0 != memcmp (&tmac, &box->hmac, sizeof(tmac)))
2036 {
2037 GNUNET_break_op (0);
2038 queue_finish (queue);
2039 return 0;
2040 }
2041 pass_plaintext_to_core (queue, (const void *) &box[1], ntohs (hdr->size));
2042 size = ntohs (hdr->size) + sizeof(*box);
2043 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2044 "Handling plaintext, box processed!\n");
2045 GNUNET_STATISTICS_update (stats,
2046 "# bytes decrypted with BOX",
2047 size,
2048 GNUNET_NO);
2049 GNUNET_STATISTICS_update (stats,
2050 "# messages decrypted with BOX",
2051 1,
2052 GNUNET_NO);
2053 break;
2054
2055 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY:
2056 rekey = (const struct TCPRekey *) queue->pread_buf;
2057 if (sizeof(*rekey) > queue->pread_off)
2058 return 0;
2059 if (ntohs (hdr->size) != sizeof(*rekey))
2060 {
2061 GNUNET_break_op (0);
2062 queue_finish (queue);
2063 return 0;
2064 }
2065 rekeyz = *rekey;
2066 memset (&rekeyz.hmac, 0, sizeof(rekeyz.hmac));
2067 calculate_hmac (&queue->in_hmac, &rekeyz, sizeof(rekeyz), &tmac);
2068 if (0 != memcmp (&tmac, &rekey->hmac, sizeof(tmac)))
2069 {
2070 GNUNET_break_op (0);
2071 queue_finish (queue);
2072 return 0;
2073 }
2074 do_rekey (queue, rekey);
2075 size = ntohs (hdr->size);
2076 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2077 "Handling plaintext, rekey processed!\n");
2078 GNUNET_STATISTICS_update (stats,
2079 "# rekeying successful",
2080 1,
2081 GNUNET_NO);
2082 break;
2083
2084 case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH:
2085 fin = (const struct TCPFinish *) queue->pread_buf;
2086 if (sizeof(*fin) > queue->pread_off)
2087 return 0;
2088 if (ntohs (hdr->size) != sizeof(*fin))
2089 {
2090 GNUNET_break_op (0);
2091 queue_finish (queue);
2092 return 0;
2093 }
2094 finz = *fin;
2095 memset (&finz.hmac, 0, sizeof(finz.hmac));
2096 calculate_hmac (&queue->in_hmac, &finz, sizeof(finz), &tmac);
2097 if (0 != memcmp (&tmac, &fin->hmac, sizeof(tmac)))
2098 {
2099 GNUNET_break_op (0);
2100 queue_finish (queue);
2101 return 0;
2102 }
2103 /* handle FINISH by destroying queue */
2104 queue_destroy (queue);
2105 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2106 "Handling plaintext, finish processed!\n");
2107 break;
2108
2109 default:
2110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2111 "Handling plaintext, nothing processed!\n");
2112 GNUNET_break_op (0);
2113 queue_finish (queue);
2114 return 0;
2115 }
2116 GNUNET_assert (0 != size);
2117 if (-1 != queue->unverified_size)
2118 queue->unverified_size += size;
2119 return size;
2120}
2121
2122
2123/**
2124 * Queue read task. If we hit the timeout, disconnect it
2125 *
2126 * @param cls the `struct Queue *` to disconnect
2127 */
2128static void
2129queue_read (void *cls)
2130{
2131 struct Queue *queue = cls;
2132 struct GNUNET_TIME_Relative left;
2133 ssize_t rcvd;
2134
2135 queue->read_task = NULL;
2136 rcvd = GNUNET_NETWORK_socket_recv (queue->sock,
2137 &queue->cread_buf[queue->cread_off],
2138 BUF_SIZE - queue->cread_off);
2139 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2140 "Received %zd bytes from TCP queue\n", rcvd);
2141 if (-1 == rcvd)
2142 {
2143 if ((EAGAIN != errno) && (EINTR != errno))
2144 {
2145 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "recv");
2146 queue_destroy (queue);
2147 return;
2148 }
2149 /* try again */
2150 left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
2151 if (0 != left.rel_value_us)
2152 {
2153 queue->read_task =
2154 GNUNET_SCHEDULER_add_read_net (left, queue->sock, &queue_read, queue);
2155 return;
2156 }
2157 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2158 "Queue %p was idle for %s, disconnecting\n",
2159 queue,
2160 GNUNET_STRINGS_relative_time_to_string (
2161 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2162 GNUNET_YES));
2163 queue_destroy (queue);
2164 return;
2165 }
2166 if (0 == rcvd)
2167 {
2168 /* Orderly shutdown of connection */
2169 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2170 "Socket for queue %p seems to have been closed\n", queue);
2171 queue_destroy (queue);
2172 return;
2173 }
2174 queue->timeout =
2175 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2176 queue->cread_off += rcvd;
2177 while ((queue->pread_off < sizeof(queue->pread_buf)) &&
2178 (queue->cread_off > 0))
2179 {
2180 size_t max = GNUNET_MIN (sizeof(queue->pread_buf) - queue->pread_off,
2181 queue->cread_off);
2182 size_t done;
2183 size_t total;
2184 size_t old_pread_off = queue->pread_off;
2185
2186 GNUNET_assert (0 ==
2187 gcry_cipher_decrypt (queue->in_cipher,
2188 &queue->pread_buf[queue->pread_off],
2189 max,
2190 queue->cread_buf,
2191 max));
2192 queue->pread_off += max;
2193 total = 0;
2194 while (0 != (done = try_handle_plaintext (queue)))
2195 {
2196 /* 'done' bytes of plaintext were used, shift buffer */
2197 GNUNET_assert (done <= queue->pread_off);
2198 /* NOTE: this memmove() could possibly sometimes be
2199 avoided if we pass 'total' into try_handle_plaintext()
2200 and use it at an offset into the buffer there! */
2201 memmove (queue->pread_buf,
2202 &queue->pread_buf[done],
2203 queue->pread_off - done);
2204 queue->pread_off -= done;
2205 total += done;
2206 /* The last plaintext was a rekey, abort for now */
2207 if (GNUNET_YES == queue->rekeyed)
2208 break;
2209 }
2210 /* when we encounter a rekey message, the decryption above uses the
2211 wrong key for everything after the rekey; in that case, we have
2212 to re-do the decryption at 'total' instead of at 'max'.
2213 However, we have to take into account that the plaintext buffer may have
2214 already contained data and not jumped too far ahead in the ciphertext.
2215 If there is no rekey and the last message is incomplete (max > total),
2216 it is safe to keep the decryption so we shift by 'max' */
2217 if (GNUNET_YES == queue->rekeyed)
2218 {
2219 max = total - old_pread_off;
2220 queue->rekeyed = GNUNET_NO;
2221 queue->pread_off = 0;
2222 }
2223 memmove (queue->cread_buf, &queue->cread_buf[max], queue->cread_off - max);
2224 queue->cread_off -= max;
2225 }
2226 if (BUF_SIZE == queue->cread_off)
2227 return; /* buffer full, suspend reading */
2228 left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
2229 if (0 != left.rel_value_us)
2230 {
2231 if (max_queue_length > queue->backpressure)
2232 {
2233 /* continue reading */
2234 queue->read_task =
2235 GNUNET_SCHEDULER_add_read_net (left, queue->sock, &queue_read, queue);
2236 }
2237 return;
2238 }
2239 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2240 "Queue %p was idle for %s, disconnecting\n",
2241 queue,
2242 GNUNET_STRINGS_relative_time_to_string (
2243 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
2244 GNUNET_YES));
2245 queue_destroy (queue);
2246}
2247
2248
2249/**
2250 * Convert a `struct sockaddr_in6 to a `struct sockaddr *`
2251 *
2252 * @param[out] sock_len set to the length of the address.
2253 * @param v6 The sockaddr_in6 to be converted.
2254 * @return The struct sockaddr *.
2255 */
2256static struct sockaddr *
2257tcp_address_to_sockaddr_numeric_v6 (socklen_t *sock_len,
2258 struct sockaddr_in6 v6,
2259 unsigned int port)
2260{
2261 struct sockaddr *in;
2262
2263 v6.sin6_family = AF_INET6;
2264 v6.sin6_port = htons ((uint16_t) port);
2265#if HAVE_SOCKADDR_IN_SIN_LEN
2266 v6.sin6_len = sizeof(struct sockaddr_in6);
2267#endif
2268 v6.sin6_flowinfo = 0;
2269 v6.sin6_scope_id = 0;
2270 in = GNUNET_memdup (&v6, sizeof(v6));
2271 *sock_len = sizeof(struct sockaddr_in6);
2272
2273 return in;
2274}
2275
2276
2277/**
2278 * Convert a `struct sockaddr_in4 to a `struct sockaddr *`
2279 *
2280 * @param[out] sock_len set to the length of the address.
2281 * @param v4 The sockaddr_in4 to be converted.
2282 * @return The struct sockaddr *.
2283 */
2284static struct sockaddr *
2285tcp_address_to_sockaddr_numeric_v4 (socklen_t *sock_len,
2286 struct sockaddr_in v4,
2287 unsigned int port)
2288{
2289 struct sockaddr *in;
2290
2291 v4.sin_family = AF_INET;
2292 v4.sin_port = htons ((uint16_t) port);
2293#if HAVE_SOCKADDR_IN_SIN_LEN
2294 v4.sin_len = sizeof(struct sockaddr_in);
2295#endif
2296 in = GNUNET_memdup (&v4, sizeof(v4));
2297 *sock_len = sizeof(struct sockaddr_in);
2298 return in;
2299}
2300
2301
2302/**
2303 * Convert TCP bind specification to a `struct PortOnlyIpv4Ipv6 *`
2304 *
2305 * @param bindto bind specification to convert.
2306 * @return The converted bindto specification.
2307 */
2308static struct PortOnlyIpv4Ipv6 *
2309tcp_address_to_sockaddr_port_only (const char *bindto, unsigned int *port)
2310{
2311 struct PortOnlyIpv4Ipv6 *po;
2312 struct sockaddr_in *i4;
2313 struct sockaddr_in6 *i6;
2314 socklen_t sock_len_ipv4;
2315 socklen_t sock_len_ipv6;
2316
2317 /* interpreting value as just a PORT number */
2318 if (*port > UINT16_MAX)
2319 {
2320 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2321 "BINDTO specification `%s' invalid: value too large for port\n",
2322 bindto);
2323 return NULL;
2324 }
2325
2326 po = GNUNET_new (struct PortOnlyIpv4Ipv6);
2327
2328 if (GNUNET_YES == disable_v6)
2329 {
2330 i4 = GNUNET_malloc (sizeof(struct sockaddr_in));
2331 po->addr_ipv4 = tcp_address_to_sockaddr_numeric_v4 (&sock_len_ipv4, *i4,
2332 *port);
2333 po->addr_len_ipv4 = sock_len_ipv4;
2334 }
2335 else
2336 {
2337
2338 i4 = GNUNET_malloc (sizeof(struct sockaddr_in));
2339 po->addr_ipv4 = tcp_address_to_sockaddr_numeric_v4 (&sock_len_ipv4, *i4,
2340 *port);
2341 po->addr_len_ipv4 = sock_len_ipv4;
2342
2343 i6 = GNUNET_malloc (sizeof(struct sockaddr_in6));
2344 po->addr_ipv6 = tcp_address_to_sockaddr_numeric_v6 (&sock_len_ipv6, *i6,
2345 *port);
2346
2347 po->addr_len_ipv6 = sock_len_ipv6;
2348
2349 GNUNET_free (i6);
2350 }
2351
2352 GNUNET_free (i4);
2353
2354 return po;
2355}
2356
2357
2358/**
2359 * This Method extracts the address part of the BINDTO string.
2360 *
2361 * @param bindto String we extract the address part from.
2362 * @return The extracted address string.
2363 */
2364static char *
2365extract_address (const char *bindto)
2366{
2367 char *addr;
2368 char *start;
2369 char *token;
2370 char *cp;
2371 char *rest = NULL;
2372
2373 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2374 "extract address with bindto %s\n",
2375 bindto);
2376
2377 if (NULL == bindto)
2378 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2379 "bindto is NULL\n");
2380
2381 cp = GNUNET_strdup (bindto);
2382
2383 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2384 "extract address 2\n");
2385
2386 start = cp;
2387 if (('[' == *cp) && (']' == cp[strlen (cp) - 1]))
2388 {
2389 start++; /* skip over '['*/
2390 cp[strlen (cp) - 1] = '\0'; /* eat ']'*/
2391 addr = GNUNET_strdup (start);
2392 }
2393 else
2394 {
2395 token = strtok_r (cp, "]", &rest);
2396 if (strlen (bindto) == strlen (token))
2397 {
2398 token = strtok_r (cp, ":", &rest);
2399 addr = GNUNET_strdup (token);
2400 }
2401 else
2402 {
2403 token++;
2404 addr = GNUNET_strdup (token);
2405 }
2406 }
2407
2408 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2409 "tcp address: %s\n",
2410 addr);
2411 GNUNET_free (cp);
2412 return addr;
2413}
2414
2415
2416/**
2417 * This Method extracts the port part of the BINDTO string.
2418 *
2419 * @param addr_and_port String we extract the port from.
2420 * @return The extracted port as unsigned int.
2421 */
2422static unsigned int
2423extract_port (const char *addr_and_port)
2424{
2425 unsigned int port;
2426 char dummy[2];
2427 char *token;
2428 char *addr;
2429 char *colon;
2430 char *cp;
2431 char *rest = NULL;
2432
2433 if (NULL != addr_and_port)
2434 {
2435 cp = GNUNET_strdup (addr_and_port);
2436 token = strtok_r (cp, "]", &rest);
2437 if (strlen (addr_and_port) == strlen (token))
2438 {
2439 colon = strrchr (cp, ':');
2440 if (NULL == colon)
2441 {
2442 GNUNET_free (cp);
2443 return 0;
2444 }
2445 addr = colon;
2446 addr++;
2447 }
2448 else
2449 {
2450 token = strtok_r (NULL, "]", &rest);
2451 if (NULL == token)
2452 {
2453 GNUNET_free (cp);
2454 return 0;
2455 }
2456 else
2457 {
2458 addr = token;
2459 addr++;
2460 }
2461 }
2462
2463
2464 if (1 == sscanf (addr, "%u%1s", &port, dummy))
2465 {
2466 /* interpreting value as just a PORT number */
2467 if (port > UINT16_MAX)
2468 {
2469 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2470 "Port `%u' invalid: value too large for port\n",
2471 port);
2472 GNUNET_free (cp);
2473 return 0;
2474 }
2475 }
2476 else
2477 {
2478 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2479 "BINDTO specification invalid: last ':' not followed by number\n");
2480 GNUNET_free (cp);
2481 return 0;
2482 }
2483 GNUNET_free (cp);
2484 }
2485 else
2486 {
2487 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2488 "return 0\n");
2489 /* interpret missing port as 0, aka pick any free one */
2490 port = 0;
2491 }
2492
2493 return port;
2494}
2495
2496
2497/**
2498 * Convert TCP bind specification to a `struct sockaddr *`
2499 *
2500 * @param bindto bind specification to convert
2501 * @param[out] sock_len set to the length of the address
2502 * @return converted bindto specification
2503 */
2504static struct sockaddr *
2505tcp_address_to_sockaddr (const char *bindto, socklen_t *sock_len)
2506{
2507 struct sockaddr *in;
2508 unsigned int port;
2509 struct sockaddr_in v4;
2510 struct sockaddr_in6 v6;
2511 char *start;
2512
2513 memset (&v4, 0, sizeof(v4));
2514 start = extract_address (bindto);
2515 GNUNET_assert (NULL != start);
2516 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2517 "start %s\n",
2518 start);
2519
2520 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2521 "!bindto %s\n",
2522 bindto);
2523
2524
2525 if (1 == inet_pton (AF_INET, start, &v4.sin_addr))
2526 {
2527 port = extract_port (bindto);
2528
2529 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2530 "port %u\n",
2531 port);
2532
2533 in = tcp_address_to_sockaddr_numeric_v4 (sock_len, v4, port);
2534 }
2535 else if (1 == inet_pton (AF_INET6, start, &v6.sin6_addr))
2536 {
2537 port = extract_port (bindto);
2538 in = tcp_address_to_sockaddr_numeric_v6 (sock_len, v6, port);
2539 }
2540 else
2541 {
2542 GNUNET_assert (0);
2543 }
2544
2545 GNUNET_free (start);
2546 return in;
2547}
2548
2549
2550/**
2551 * Signature of functions implementing the sending functionality of a
2552 * message queue.
2553 *
2554 * @param mq the message queue
2555 * @param msg the message to send
2556 * @param impl_state our `struct Queue`
2557 */
2558static void
2559mq_send (struct GNUNET_MQ_Handle *mq,
2560 const struct GNUNET_MessageHeader *msg,
2561 void *impl_state)
2562{
2563 struct Queue *queue = impl_state;
2564 uint16_t msize = ntohs (msg->size);
2565 struct TCPBox box;
2566 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2567 "In MQ send. Queue finishing: %s; write task running: %s\n",
2568 (GNUNET_YES == queue->finishing) ? "yes" : "no",
2569 (NULL == queue->write_task) ? "yes" : "no");
2570 GNUNET_assert (mq == queue->mq);
2571 queue->mq_awaits_continue = GNUNET_YES;
2572 if (GNUNET_YES == queue->finishing)
2573 return; /* this queue is dying, drop msg */
2574 GNUNET_assert (0 == queue->pwrite_off);
2575 box.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX);
2576 box.header.size = htons (msize);
2577 calculate_hmac (&queue->out_hmac, msg, msize, &box.hmac);
2578 memcpy (&queue->pwrite_buf[queue->pwrite_off], &box, sizeof(box));
2579 queue->pwrite_off += sizeof(box);
2580 memcpy (&queue->pwrite_buf[queue->pwrite_off], msg, msize);
2581 queue->pwrite_off += msize;
2582 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2583 "%lu bytes of plaintext to send\n", queue->pwrite_off);
2584 GNUNET_assert (NULL != queue->sock);
2585 if (NULL == queue->write_task)
2586 queue->write_task =
2587 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2588 queue->sock,
2589 &queue_write,
2590 queue);
2591}
2592
2593
2594/**
2595 * Signature of functions implementing the destruction of a message
2596 * queue. Implementations must not free @a mq, but should take care
2597 * of @a impl_state.
2598 *
2599 * @param mq the message queue to destroy
2600 * @param impl_state our `struct Queue`
2601 */
2602static void
2603mq_destroy (struct GNUNET_MQ_Handle *mq, void *impl_state)
2604{
2605 struct Queue *queue = impl_state;
2606
2607 if (mq == queue->mq)
2608 {
2609 queue->mq = NULL;
2610 queue_finish (queue);
2611 }
2612}
2613
2614
2615/**
2616 * Implementation function that cancels the currently sent message.
2617 *
2618 * @param mq message queue
2619 * @param impl_state our `struct Queue`
2620 */
2621static void
2622mq_cancel (struct GNUNET_MQ_Handle *mq, void *impl_state)
2623{
2624 struct Queue *queue = impl_state;
2625
2626 GNUNET_assert (0 != queue->pwrite_off);
2627 queue->pwrite_off = 0;
2628}
2629
2630
2631/**
2632 * Generic error handler, called with the appropriate
2633 * error code and the same closure specified at the creation of
2634 * the message queue.
2635 * Not every message queue implementation supports an error handler.
2636 *
2637 * @param cls our `struct Queue`
2638 * @param error error code
2639 */
2640static void
2641mq_error (void *cls, enum GNUNET_MQ_Error error)
2642{
2643 struct Queue *queue = cls;
2644
2645 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2646 "MQ error in queue to %s: %d\n",
2647 GNUNET_i2s (&queue->target),
2648 (int) error);
2649 queue_finish (queue);
2650}
2651
2652
2653/**
2654 * Add the given @a queue to our internal data structure. Setup the
2655 * MQ processing and inform transport that the queue is ready. Must
2656 * be called after the KX for outgoing messages has been bootstrapped.
2657 *
2658 * @param queue queue to boot
2659 */
2660static void
2661boot_queue (struct Queue *queue)
2662{
2663 queue->nt =
2664 GNUNET_NT_scanner_get_type (is, queue->address, queue->address_len);
2665 (void) GNUNET_CONTAINER_multihashmap_put (
2666 queue_map,
2667 &queue->key,
2668 queue,
2669 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2670 GNUNET_STATISTICS_set (stats,
2671 "# queues active",
2672 GNUNET_CONTAINER_multihashmap_size (queue_map),
2673 GNUNET_NO);
2674 queue->timeout =
2675 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2676 queue->mq = GNUNET_MQ_queue_for_callbacks (&mq_send,
2677 &mq_destroy,
2678 &mq_cancel,
2679 queue,
2680 NULL,
2681 &mq_error,
2682 queue);
2683}
2684
2685
2686/**
2687 * Generate and transmit our ephemeral key and the signature for
2688 * the initial KX with the other peer. Must be called first, before
2689 * any other bytes are ever written to the output buffer. Note that
2690 * our cipher must already be initialized when calling this function.
2691 * Helper function for #start_initial_kx_out().
2692 *
2693 * @param queue queue to do KX for
2694 * @param epub our public key for the KX
2695 */
2696static void
2697transmit_kx (struct Queue *queue,
2698 const struct GNUNET_CRYPTO_EcdhePublicKey *epub)
2699{
2700 struct TcpHandshakeSignature ths;
2701 struct TCPConfirmation tc;
2702
2703 memcpy (queue->cwrite_buf, epub, sizeof(*epub));
2704 queue->cwrite_off = sizeof(*epub);
2705 /* compute 'tc' and append in encrypted format to cwrite_buf */
2706 tc.sender = my_identity;
2707 tc.monotonic_time =
2708 GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
2709 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE,
2710 &tc.challenge,
2711 sizeof(tc.challenge));
2712 ths.purpose.purpose = htonl (
2713 GNUNET_SIGNATURE_PURPOSE_COMMUNICATOR_TCP_HANDSHAKE);
2714 ths.purpose.size = htonl (sizeof(ths));
2715 ths.sender = my_identity;
2716 ths.receiver = queue->target;
2717 ths.ephemeral = *epub;
2718 ths.monotonic_time = tc.monotonic_time;
2719 ths.challenge = tc.challenge;
2720 GNUNET_CRYPTO_eddsa_sign (my_private_key,
2721 &ths,
2722 &tc.sender_sig);
2723 GNUNET_assert (0 ==
2724 gcry_cipher_encrypt (queue->out_cipher,
2725 &queue->cwrite_buf[queue->cwrite_off],
2726 sizeof(tc),
2727 &tc,
2728 sizeof(tc)));
2729 queue->challenge = tc.challenge;
2730 queue->cwrite_off += sizeof(tc);
2731
2732 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2733 "handshake written\n");
2734}
2735
2736
2737/**
2738 * Initialize our key material for outgoing transmissions and
2739 * inform the other peer about it. Must be called first before
2740 * any data is sent.
2741 *
2742 * @param queue the queue to setup
2743 */
2744static void
2745start_initial_kx_out (struct Queue *queue)
2746{
2747 struct GNUNET_CRYPTO_EcdhePublicKey epub;
2748 struct GNUNET_HashCode k;
2749
2750 // TODO: We could use the Elligator KEM here! https://bugs.gnunet.org/view.php?id=8065
2751 GNUNET_CRYPTO_eddsa_kem_encaps (&queue->target.public_key, &epub, &k);
2752 setup_out_cipher (queue, &k);
2753 transmit_kx (queue, &epub);
2754}
2755
2756
2757/**
2758 * Callback called when peerstore store operation for handshake monotime is finished.
2759 * @param cls Queue context the store operation was executed.
2760 * @param success Store operation was successful (GNUNET_OK) or not.
2761 */
2762static void
2763handshake_monotime_store_cb (void *cls, int success)
2764{
2765 struct Queue *queue = cls;
2766 if (GNUNET_OK != success)
2767 {
2768 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2769 "Failed to store handshake monotonic time in PEERSTORE!\n");
2770 }
2771 queue->handshake_monotime_sc = NULL;
2772 GNUNET_PEERSTORE_iteration_next (queue->handshake_ack_monotime_get, 1);
2773}
2774
2775
2776/**
2777 * Callback called by peerstore when records for GNUNET_PEERSTORE_TRANSPORT_TCP_COMMUNICATOR_HANDSHAKE
2778 * where found.
2779 * @param cls Queue context the store operation was executed.
2780 * @param record The record found or NULL if there is no record left.
2781 * @param emsg Message from peerstore.
2782 */
2783static void
2784handshake_monotime_cb (void *cls,
2785 const struct GNUNET_PEERSTORE_Record *record,
2786 const char *emsg)
2787{
2788 struct Queue *queue = cls;
2789 struct GNUNET_TIME_AbsoluteNBO *mtbe;
2790 struct GNUNET_TIME_Absolute mt;
2791 const struct GNUNET_PeerIdentity *pid;
2792 struct GNUNET_TIME_AbsoluteNBO *handshake_monotonic_time;
2793
2794 (void) emsg;
2795
2796 handshake_monotonic_time = &queue->handshake_monotonic_time;
2797 pid = &queue->target;
2798 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2799 "tcp handshake with us %s\n",
2800 GNUNET_i2s (&my_identity));
2801 if (NULL == record)
2802 {
2803 queue->handshake_monotime_get = NULL;
2804 return;
2805 }
2806 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2807 "tcp handshake from peer %s\n",
2808 GNUNET_i2s (pid));
2809 if (sizeof(*mtbe) != record->value_size)
2810 {
2811 GNUNET_PEERSTORE_iteration_next (queue->handshake_ack_monotime_get, 1);
2812 GNUNET_break (0);
2813 return;
2814 }
2815 mtbe = record->value;
2816 mt = GNUNET_TIME_absolute_ntoh (*mtbe);
2817 if (mt.abs_value_us > GNUNET_TIME_absolute_ntoh (
2818 queue->handshake_monotonic_time).abs_value_us)
2819 {
2820 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2821 "Queue from %s dropped, handshake monotime in the past\n",
2822 GNUNET_i2s (&queue->target));
2823 GNUNET_break (0);
2824 GNUNET_PEERSTORE_iteration_stop (queue->handshake_ack_monotime_get);
2825 queue->handshake_ack_monotime_get = NULL;
2826 queue_finish (queue);
2827 return;
2828 }
2829 queue->handshake_monotime_sc = GNUNET_PEERSTORE_store (peerstore,
2830 "transport_tcp_communicator",
2831 pid,
2832 GNUNET_PEERSTORE_TRANSPORT_TCP_COMMUNICATOR_HANDSHAKE,
2833 handshake_monotonic_time,
2834 sizeof(*
2835 handshake_monotonic_time),
2836 GNUNET_TIME_UNIT_FOREVER_ABS,
2837 GNUNET_PEERSTORE_STOREOPTION_REPLACE,
2838 &
2839 handshake_monotime_store_cb,
2840 queue);
2841}
2842
2843
2844/**
2845 * We have received the first bytes from the other side on a @a queue.
2846 * Decrypt the @a tc contained in @a ibuf and check the signature.
2847 * Note that #setup_in_cipher() must have already been called.
2848 *
2849 * @param queue queue to decrypt initial bytes from other peer for
2850 * @param[out] tc where to store the result
2851 * @param ibuf incoming data, of size
2852 * `INITIAL_KX_SIZE`
2853 * @return #GNUNET_OK if the signature was OK, #GNUNET_SYSERR if not
2854 */
2855static int
2856decrypt_and_check_tc (struct Queue *queue,
2857 struct TCPConfirmation *tc,
2858 char *ibuf)
2859{
2860 struct TcpHandshakeSignature ths;
2861 enum GNUNET_GenericReturnValue ret;
2862
2863 GNUNET_assert (
2864 0 ==
2865 gcry_cipher_decrypt (queue->in_cipher,
2866 tc,
2867 sizeof(*tc),
2868 &ibuf[sizeof(struct GNUNET_CRYPTO_EcdhePublicKey)],
2869 sizeof(*tc)));
2870 ths.purpose.purpose = htonl (
2871 GNUNET_SIGNATURE_PURPOSE_COMMUNICATOR_TCP_HANDSHAKE);
2872 ths.purpose.size = htonl (sizeof(ths));
2873 ths.sender = tc->sender;
2874 ths.receiver = my_identity;
2875 memcpy (&ths.ephemeral, ibuf, sizeof(struct GNUNET_CRYPTO_EcdhePublicKey));
2876 ths.monotonic_time = tc->monotonic_time;
2877 ths.challenge = tc->challenge;
2878 ret = GNUNET_CRYPTO_eddsa_verify (
2879 GNUNET_SIGNATURE_PURPOSE_COMMUNICATOR_TCP_HANDSHAKE,
2880 &ths,
2881 &tc->sender_sig,
2882 &tc->sender.public_key);
2883 if (GNUNET_YES == ret)
2884 queue->handshake_monotime_get =
2885 GNUNET_PEERSTORE_iteration_start (peerstore,
2886 "transport_tcp_communicator",
2887 &queue->target,
2888 GNUNET_PEERSTORE_TRANSPORT_TCP_COMMUNICATOR_HANDSHAKE,
2889 &handshake_monotime_cb,
2890 queue);
2891 return ret;
2892}
2893
2894
2895/**
2896 * Read from the socket of the queue until we have enough data
2897 * to initialize the decryption logic and can switch to regular
2898 * reading.
2899 *
2900 * @param cls a `struct Queue`
2901 */
2902static void
2903queue_read_kx (void *cls)
2904{
2905 struct Queue *queue = cls;
2906 ssize_t rcvd;
2907 struct GNUNET_TIME_Relative left;
2908 struct TCPConfirmation tc;
2909
2910 queue->read_task = NULL;
2911 left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
2912 if (0 == left.rel_value_us)
2913 {
2914 queue_destroy (queue);
2915 return;
2916 }
2917 rcvd = GNUNET_NETWORK_socket_recv (queue->sock,
2918 &queue->cread_buf[queue->cread_off],
2919 BUF_SIZE - queue->cread_off);
2920 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2921 "Received %lu bytes to write in buffer of size %lu for KX from queue %p (expires in %"
2922 PRIu64 ")\n",
2923 rcvd, BUF_SIZE - queue->cread_off, queue, left.rel_value_us);
2924 if (-1 == rcvd)
2925 {
2926 if ((EAGAIN != errno) && (EINTR != errno))
2927 {
2928 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "recv");
2929 queue_destroy (queue);
2930 return;
2931 }
2932 queue->read_task =
2933 GNUNET_SCHEDULER_add_read_net (left, queue->sock, &queue_read_kx, queue);
2934 return;
2935 }
2936 if (0 == rcvd)
2937 {
2938 /* Orderly shutdown of connection */
2939 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2940 "Socket for queue %p seems to have been closed\n", queue);
2941 queue_destroy (queue);
2942 return;
2943 }
2944 queue->cread_off += rcvd;
2945 if (queue->cread_off < INITIAL_KX_SIZE)
2946 {
2947 /* read more */
2948 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2949 "%lu/%lu bytes of KX read. Rescheduling...\n",
2950 queue->cread_off, INITIAL_KX_SIZE);
2951 queue->read_task =
2952 GNUNET_SCHEDULER_add_read_net (left, queue->sock, &queue_read_kx, queue);
2953 return;
2954 }
2955 /* we got all the data, let's find out who we are talking to! */
2956 setup_in_cipher ((const struct GNUNET_CRYPTO_EcdhePublicKey *)
2957 queue->cread_buf,
2958 queue);
2959 if (GNUNET_OK != decrypt_and_check_tc (queue, &tc, queue->cread_buf))
2960 {
2961 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2962 "Invalid TCP KX received from %s\n",
2963 GNUNET_a2s (queue->address, queue->address_len));
2964 queue_destroy (queue);
2965 return;
2966 }
2967 if (0 !=
2968 memcmp (&tc.sender, &queue->target, sizeof(struct GNUNET_PeerIdentity)))
2969 {
2970 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2971 "Invalid sender in TCP KX received from %s\n",
2972 GNUNET_a2s (queue->address, queue->address_len));
2973 queue_destroy (queue);
2974 return;
2975 }
2976 send_challenge (tc.challenge, queue);
2977 queue->write_task =
2978 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
2979 queue->sock,
2980 &queue_write,
2981 queue);
2982
2983 /* update queue timeout */
2984 queue->timeout =
2985 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2986 /* prepare to continue with regular read task immediately */
2987 memmove (queue->cread_buf,
2988 &queue->cread_buf[INITIAL_KX_SIZE],
2989 queue->cread_off - (INITIAL_KX_SIZE));
2990 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2991 "cread_off is %lu bytes before adjusting\n",
2992 queue->cread_off);
2993 queue->cread_off -= INITIAL_KX_SIZE;
2994 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2995 "cread_off set to %lu bytes\n",
2996 queue->cread_off);
2997 queue->read_task = GNUNET_SCHEDULER_add_now (&queue_read, queue);
2998}
2999
3000
3001/**
3002 * Read from the socket of the proto queue until we have enough data
3003 * to upgrade to full queue.
3004 *
3005 * @param cls a `struct ProtoQueue`
3006 */
3007static void
3008proto_read_kx (void *cls)
3009{
3010 struct ProtoQueue *pq = cls;
3011 ssize_t rcvd;
3012 struct GNUNET_TIME_Relative left;
3013 struct Queue *queue;
3014 struct TCPConfirmation tc;
3015 GNUNET_SCHEDULER_TaskCallback read_task;
3016
3017 pq->read_task = NULL;
3018 left = GNUNET_TIME_absolute_get_remaining (pq->timeout);
3019 if (0 == left.rel_value_us)
3020 {
3021 free_proto_queue (pq);
3022 return;
3023 }
3024 rcvd = GNUNET_NETWORK_socket_recv (pq->sock,
3025 &pq->ibuf[pq->ibuf_off],
3026 sizeof(pq->ibuf) - pq->ibuf_off);
3027 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3028 "Proto received %lu bytes for KX\n", rcvd);
3029 if (-1 == rcvd)
3030 {
3031 if ((EAGAIN != errno) && (EINTR != errno))
3032 {
3033 GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "recv");
3034 free_proto_queue (pq);
3035 return;
3036 }
3037 /* try again */
3038 pq->read_task =
3039 GNUNET_SCHEDULER_add_read_net (left, pq->sock, &proto_read_kx, pq);
3040 return;
3041 }
3042 if (0 == rcvd)
3043 {
3044 /* Orderly shutdown of connection */
3045 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3046 "Socket for proto queue %p seems to have been closed\n", pq);
3047 free_proto_queue (pq);
3048 return;
3049 }
3050 pq->ibuf_off += rcvd;
3051 if (sizeof (struct TCPNATProbeMessage) == pq->ibuf_off)
3052 {
3053 struct TCPNATProbeMessage *pm = (struct TCPNATProbeMessage *) pq->ibuf;
3054
3055 check_and_remove_pending_reversal (pq->address, pq->address->sa_family,
3056 &pm->clientIdentity);
3057
3058 queue = GNUNET_new (struct Queue);
3059 queue->target = pm->clientIdentity;
3060 queue->cs = GNUNET_TRANSPORT_CS_OUTBOUND;
3061 read_task = &queue_read_kx;
3062 }
3063 else if (pq->ibuf_off > sizeof(pq->ibuf))
3064 {
3065 /* read more */
3066 pq->read_task =
3067 GNUNET_SCHEDULER_add_read_net (left, pq->sock, &proto_read_kx, pq);
3068 return;
3069 }
3070 else
3071 {
3072 /* we got all the data, let's find out who we are talking to! */
3073 queue = GNUNET_new (struct Queue);
3074 setup_in_cipher ((const struct GNUNET_CRYPTO_EcdhePublicKey *) pq->ibuf,
3075 queue);
3076 if (GNUNET_OK != decrypt_and_check_tc (queue, &tc, pq->ibuf))
3077 {
3078 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3079 "Invalid TCP KX received from %s\n",
3080 GNUNET_a2s (pq->address, pq->address_len));
3081 gcry_cipher_close (queue->in_cipher);
3082 GNUNET_free (queue);
3083 free_proto_queue (pq);
3084 return;
3085 }
3086 queue->target = tc.sender;
3087 queue->cs = GNUNET_TRANSPORT_CS_INBOUND;
3088 read_task = &queue_read;
3089 }
3090 queue->address = pq->address; /* steals reference */
3091 queue->address_len = pq->address_len;
3092 queue->listen_sock = pq->listen_sock;
3093 queue->sock = pq->sock;
3094
3095 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3096 "created queue with target %s\n",
3097 GNUNET_i2s (&queue->target));
3098
3099 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3100 "start kx proto\n");
3101
3102 start_initial_kx_out (queue);
3103 boot_queue (queue);
3104 queue->read_task =
3105 GNUNET_SCHEDULER_add_read_net (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3106 queue->sock,
3107 read_task,
3108 queue);
3109 queue->write_task =
3110 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
3111 queue->sock,
3112 &queue_write,
3113 queue);
3114 // TODO To early! Move it somewhere else.
3115 // send_challenge (tc.challenge, queue);
3116 queue->challenge_received = tc.challenge;
3117
3118 GNUNET_CONTAINER_DLL_remove (proto_head, proto_tail, pq);
3119 GNUNET_free (pq);
3120}
3121
3122
3123static struct ProtoQueue *
3124create_proto_queue (struct GNUNET_NETWORK_Handle *sock,
3125 struct sockaddr *in,
3126 socklen_t addrlen)
3127{
3128 struct ProtoQueue *pq = GNUNET_new (struct ProtoQueue);
3129
3130 if (NULL == sock)
3131 {
3132 // sock = GNUNET_CONNECTION_create_from_sockaddr (AF_INET, addr, addrlen);
3133 sock = GNUNET_NETWORK_socket_create (in->sa_family, SOCK_STREAM, 0);
3134 if (NULL == sock)
3135 {
3136 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3137 "socket(%d) failed: %s",
3138 in->sa_family,
3139 strerror (errno));
3140 GNUNET_free (in);
3141 GNUNET_free (pq);
3142 return NULL;
3143 }
3144 if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (sock, in, addrlen)) &&
3145 (errno != EINPROGRESS))
3146 {
3147 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3148 "connect to `%s' failed: %s",
3149 GNUNET_a2s (in, addrlen),
3150 strerror (errno));
3151 GNUNET_NETWORK_socket_close (sock);
3152 GNUNET_free (in);
3153 GNUNET_free (pq);
3154 return NULL;
3155 }
3156 }
3157 pq->address_len = addrlen;
3158 pq->address = in;
3159 pq->timeout = GNUNET_TIME_relative_to_absolute (PROTO_QUEUE_TIMEOUT);
3160 pq->sock = sock;
3161 pq->read_task = GNUNET_SCHEDULER_add_read_net (PROTO_QUEUE_TIMEOUT,
3162 pq->sock,
3163 &proto_read_kx,
3164 pq);
3165 GNUNET_CONTAINER_DLL_insert (proto_head, proto_tail, pq);
3166
3167 return pq;
3168}
3169
3170
3171/**
3172 * We have been notified that our listen socket has something to
3173 * read. Do the read and reschedule this function to be called again
3174 * once more is available.
3175 *
3176 * @param cls ListenTask with listening socket and task
3177 */
3178static void
3179listen_cb (void *cls)
3180{
3181 struct sockaddr_storage in;
3182 socklen_t addrlen;
3183 struct GNUNET_NETWORK_Handle *sock;
3184 struct ListenTask *lt;
3185 struct sockaddr *in_addr;
3186
3187 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3188 "listen_cb\n");
3189
3190 lt = cls;
3191
3192 lt->listen_task = NULL;
3193 GNUNET_assert (NULL != lt->listen_sock);
3194 addrlen = sizeof(in);
3195 memset (&in, 0, sizeof(in));
3196 sock = GNUNET_NETWORK_socket_accept (lt->listen_sock,
3197 (struct sockaddr*) &in,
3198 &addrlen);
3199 if ((NULL == sock) && ((EMFILE == errno) || (ENFILE == errno)))
3200 return; /* system limit reached, wait until connection goes down */
3201 lt->listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3202 lt->listen_sock,
3203 &listen_cb,
3204 lt);
3205 if ((NULL == sock) && ((EAGAIN == errno) || (ENOBUFS == errno)))
3206 return;
3207 if (NULL == sock)
3208 {
3209 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "accept");
3210 return;
3211 }
3212 in_addr = GNUNET_memdup (&in, addrlen);
3213 create_proto_queue (sock, in_addr, addrlen);
3214}
3215
3216
3217static void
3218try_connection_reversal (void *cls,
3219 const struct sockaddr *addr,
3220 socklen_t addrlen)
3221{
3222 (void) cls;
3223 struct TCPNATProbeMessage pm;
3224 struct ProtoQueue *pq;
3225 struct sockaddr *in_addr;
3226
3227 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3228 "addr->sa_family %d\n",
3229 addr->sa_family);
3230 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3231 "Try to connect back\n");
3232 in_addr = GNUNET_memdup (addr, addrlen);
3233 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3234 "in_addr->sa_family %d\n",
3235 in_addr->sa_family);
3236 pq = create_proto_queue (NULL, in_addr, addrlen);
3237 if (NULL != pq)
3238 {
3239 pm.header.size = htons (sizeof(struct TCPNATProbeMessage));
3240 pm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TCP_NAT_PROBE);
3241 pm.clientIdentity = my_identity;
3242 memcpy (pq->write_buf, &pm, sizeof(struct TCPNATProbeMessage));
3243 pq->write_off = sizeof(struct TCPNATProbeMessage);
3244 pq->write_task = GNUNET_SCHEDULER_add_write_net (PROTO_QUEUE_TIMEOUT,
3245 pq->sock,
3246 &proto_queue_write,
3247 pq);
3248 }
3249 else
3250 {
3251 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3252 "Couldn't create ProtoQueue for sending TCPNATProbeMessage\n");
3253 }
3254}
3255
3256
3257static void
3258pending_reversal_timeout (void *cls)
3259{
3260 struct sockaddr *in = cls;
3261 struct PendingReversal *pending_reversal;
3262 struct GNUNET_HashCode key;
3263
3264 GNUNET_CRYPTO_hash (in,
3265 sizeof(struct sockaddr),
3266 &key);
3267 pending_reversal = GNUNET_CONTAINER_multihashmap_get (pending_reversals,
3268 &key);
3269
3270 GNUNET_assert (NULL != pending_reversal);
3271
3272 if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_remove (pending_reversals,
3273 &key,
3274 pending_reversal))
3275 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3276 "No pending reversal found for address %s\n",
3277 GNUNET_a2s (in, sizeof (struct sockaddr)));
3278 GNUNET_free (pending_reversal->in);
3279 GNUNET_free (pending_reversal);
3280}
3281
3282
3283/**
3284 * Function called by the transport service to initialize a
3285 * message queue given address information about another peer.
3286 * If and when the communication channel is established, the
3287 * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
3288 * to notify the service that the channel is now up. It is
3289 * the responsibility of the communicator to manage sane
3290 * retries and timeouts for any @a peer/@a address combination
3291 * provided by the transport service. Timeouts and retries
3292 * do not need to be signalled to the transport service.
3293 *
3294 * @param cls closure
3295 * @param peer identity of the other peer
3296 * @param address where to send the message, human-readable
3297 * communicator-specific format, 0-terminated, UTF-8
3298 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is
3299 * invalid
3300 */
3301static int
3302mq_init (void *cls, const struct GNUNET_PeerIdentity *peer, const char *address)
3303{
3304 struct sockaddr *in;
3305 socklen_t in_len = 0;
3306 const char *path;
3307 struct sockaddr_in *v4;
3308 struct sockaddr_in6 *v6;
3309 unsigned int is_natd = GNUNET_NO;
3310 struct GNUNET_HashCode key;
3311 struct GNUNET_HashCode queue_map_key;
3312 struct GNUNET_HashContext *hsh;
3313 struct Queue *queue;
3314
3315 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3316 "Connecting to %s at %s\n",
3317 GNUNET_i2s (peer),
3318 address);
3319 if (0 != strncmp (address,
3320 COMMUNICATOR_ADDRESS_PREFIX "-",
3321 strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
3322 {
3323 GNUNET_break_op (0);
3324 return GNUNET_SYSERR;
3325 }
3326 path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
3327 in = tcp_address_to_sockaddr (path, &in_len);
3328
3329 if (NULL == in)
3330 {
3331 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3332 "Failed to setup TCP socket address\n");
3333 return GNUNET_SYSERR;
3334 }
3335
3336 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3337 "in %s\n",
3338 GNUNET_a2s (in, in_len));
3339
3340 hsh = GNUNET_CRYPTO_hash_context_start ();
3341 GNUNET_CRYPTO_hash_context_read (hsh, address, strlen (address));
3342 GNUNET_CRYPTO_hash_context_read (hsh, peer, sizeof (*peer));
3343 GNUNET_CRYPTO_hash_context_finish (hsh, &queue_map_key);
3344 queue = GNUNET_CONTAINER_multihashmap_get (queue_map, &queue_map_key);
3345
3346 if (NULL != queue)
3347 {
3348 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3349 "Queue for %s already exists or is in construction\n", address);
3350 GNUNET_free (in);
3351 return GNUNET_NO;
3352 }
3353 switch (in->sa_family)
3354 {
3355 case AF_INET:
3356 v4 = (struct sockaddr_in *) in;
3357 if (0 == v4->sin_port)
3358 {
3359 is_natd = GNUNET_YES;
3360 GNUNET_CRYPTO_hash (in,
3361 sizeof(struct sockaddr),
3362 &key);
3363 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (
3364 pending_reversals,
3365 &key))
3366 {
3367 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3368 "There is already a request reversal for `%s'at `%s'\n",
3369 GNUNET_i2s (peer),
3370 address);
3371 GNUNET_free (in);
3372 return GNUNET_SYSERR;
3373 }
3374 }
3375 break;
3376
3377 case AF_INET6:
3378 if (GNUNET_YES == disable_v6)
3379 {
3380 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3381 "IPv6 disabled, skipping %s\n", address);
3382 GNUNET_free (in);
3383 return GNUNET_SYSERR;
3384 }
3385 v6 = (struct sockaddr_in6 *) in;
3386 if (0 == v6->sin6_port)
3387 {
3388 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3389 "Request reversal for `%s' at `%s' not possible for an IPv6 address\n",
3390 GNUNET_i2s (peer),
3391 address);
3392 GNUNET_free (in);
3393 return GNUNET_SYSERR;
3394 }
3395 break;
3396
3397 default:
3398 GNUNET_assert (0);
3399 }
3400
3401 if (GNUNET_YES == is_natd)
3402 {
3403 struct sockaddr_in local_sa;
3404 struct PendingReversal *pending_reversal;
3405
3406 memset (&local_sa, 0, sizeof(local_sa));
3407 local_sa.sin_family = AF_INET;
3408 local_sa.sin_port = htons (bind_port);
3409 /* We leave sin_address at 0, let the kernel figure it out,
3410 even if our bind() is more specific. (May want to reconsider
3411 later.) */
3412 if (GNUNET_OK != GNUNET_NAT_request_reversal (nat, &local_sa, v4))
3413 {
3414 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3415 "request reversal for `%s' at `%s' failed\n",
3416 GNUNET_i2s (peer),
3417 address);
3418 GNUNET_free (in);
3419 return GNUNET_SYSERR;
3420 }
3421 pending_reversal = GNUNET_new (struct PendingReversal);
3422 pending_reversal->in = in;
3423 GNUNET_assert (GNUNET_OK ==
3424 GNUNET_CONTAINER_multihashmap_put (pending_reversals,
3425 &key,
3426 pending_reversal,
3427 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3428 pending_reversal->target = *peer;
3429 pending_reversal->timeout_task = GNUNET_SCHEDULER_add_delayed (NAT_TIMEOUT,
3430 &
3431 pending_reversal_timeout,
3432 in);
3433 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3434 "Created NAT WAIT connection to `%s' at `%s'\n",
3435 GNUNET_i2s (peer),
3436 GNUNET_a2s (in, sizeof (struct sockaddr)));
3437 }
3438 else
3439 {
3440 struct GNUNET_NETWORK_Handle *sock;
3441
3442 sock = GNUNET_NETWORK_socket_create (in->sa_family, SOCK_STREAM,
3443 IPPROTO_TCP);
3444 if (NULL == sock)
3445 {
3446 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3447 "socket(%d) failed: %s",
3448 in->sa_family,
3449 strerror (errno));
3450 GNUNET_free (in);
3451 return GNUNET_SYSERR;
3452 }
3453 if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (sock, in, in_len)) &&
3454 (errno != EINPROGRESS))
3455 {
3456 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3457 "connect to `%s' failed: %s",
3458 address,
3459 strerror (errno));
3460 GNUNET_NETWORK_socket_close (sock);
3461 GNUNET_free (in);
3462 return GNUNET_SYSERR;
3463 }
3464
3465 queue = GNUNET_new (struct Queue);
3466 queue->target = *peer;
3467 queue->key = queue_map_key;
3468 queue->address = in;
3469 queue->address_len = in_len;
3470 queue->sock = sock;
3471 queue->cs = GNUNET_TRANSPORT_CS_OUTBOUND;
3472 boot_queue (queue);
3473 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3474 "booted queue with target %s\n",
3475 GNUNET_i2s (&queue->target));
3476 // queue->mq_awaits_continue = GNUNET_YES;
3477 queue->read_task =
3478 GNUNET_SCHEDULER_add_read_net (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
3479 queue->sock,
3480 &queue_read_kx,
3481 queue);
3482
3483
3484 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3485 "start kx mq_init\n");
3486
3487 start_initial_kx_out (queue);
3488 queue->write_task =
3489 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
3490 queue->sock,
3491 &queue_write,
3492 queue);
3493 }
3494
3495 return GNUNET_OK;
3496}
3497
3498
3499/**
3500 * Iterator over all ListenTasks to clean up.
3501 *
3502 * @param cls NULL
3503 * @param key unused
3504 * @param value the ListenTask to cancel.
3505 * @return #GNUNET_OK to continue to iterate
3506 */
3507static int
3508get_lt_delete_it (void *cls,
3509 const struct GNUNET_HashCode *key,
3510 void *value)
3511{
3512 struct ListenTask *lt = value;
3513
3514 (void) cls;
3515 (void) key;
3516 if (NULL != lt->listen_task)
3517 {
3518 GNUNET_SCHEDULER_cancel (lt->listen_task);
3519 lt->listen_task = NULL;
3520 }
3521 if (NULL != lt->listen_sock)
3522 {
3523 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (lt->listen_sock));
3524 lt->listen_sock = NULL;
3525 }
3526 GNUNET_free (lt);
3527 return GNUNET_OK;
3528}
3529
3530
3531/**
3532 * Iterator over all message queues to clean up.
3533 *
3534 * @param cls NULL
3535 * @param target unused
3536 * @param value the queue to destroy
3537 * @return #GNUNET_OK to continue to iterate
3538 */
3539static int
3540get_queue_delete_it (void *cls,
3541 const struct GNUNET_HashCode *target,
3542 void *value)
3543{
3544 struct Queue *queue = value;
3545
3546 (void) cls;
3547 (void) target;
3548 queue_destroy (queue);
3549 return GNUNET_OK;
3550}
3551
3552
3553/**
3554 * Shutdown the UNIX communicator.
3555 *
3556 * @param cls NULL (always)
3557 */
3558static void
3559do_shutdown (void *cls)
3560{
3561 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3562 "Shutdown %s!\n",
3563 shutdown_running ? "running" : "not running");
3564
3565 if (GNUNET_YES == shutdown_running)
3566 return;
3567 else
3568 shutdown_running = GNUNET_YES;
3569
3570 while (NULL != proto_head)
3571 free_proto_queue (proto_head);
3572 if (NULL != nat)
3573 {
3574 GNUNET_NAT_unregister (nat);
3575 nat = NULL;
3576 }
3577 GNUNET_CONTAINER_multihashmap_iterate (pending_reversals,
3578 &pending_reversals_delete_it, NULL);
3579 GNUNET_CONTAINER_multihashmap_destroy (pending_reversals);
3580 GNUNET_CONTAINER_multihashmap_iterate (lt_map, &get_lt_delete_it, NULL);
3581 GNUNET_CONTAINER_multihashmap_destroy (lt_map);
3582 GNUNET_CONTAINER_multihashmap_iterate (queue_map, &get_queue_delete_it, NULL);
3583 GNUNET_CONTAINER_multihashmap_destroy (queue_map);
3584 if (NULL != ch)
3585 {
3586 GNUNET_TRANSPORT_communicator_address_remove_all (ch);
3587 GNUNET_TRANSPORT_communicator_disconnect (ch);
3588 ch = NULL;
3589 }
3590 if (NULL != stats)
3591 {
3592 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
3593 stats = NULL;
3594 }
3595 if (NULL != my_private_key)
3596 {
3597 GNUNET_free (my_private_key);
3598 my_private_key = NULL;
3599 }
3600 if (NULL != is)
3601 {
3602 GNUNET_NT_scanner_done (is);
3603 is = NULL;
3604 }
3605 if (NULL != peerstore)
3606 {
3607 GNUNET_PEERSTORE_disconnect (peerstore);
3608 peerstore = NULL;
3609 }
3610 if (NULL != resolve_request_handle)
3611 {
3612 GNUNET_RESOLVER_request_cancel (resolve_request_handle);
3613 resolve_request_handle = NULL;
3614 }
3615 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3616 "Shutdown done!\n");
3617}
3618
3619
3620/**
3621 * Function called when the transport service has received an
3622 * acknowledgement for this communicator (!) via a different return
3623 * path.
3624 *
3625 * Not applicable for TCP.
3626 *
3627 * @param cls closure
3628 * @param sender which peer sent the notification
3629 * @param msg payload
3630 */
3631static void
3632enc_notify_cb (void *cls,
3633 const struct GNUNET_PeerIdentity *sender,
3634 const struct GNUNET_MessageHeader *msg)
3635{
3636 (void) cls;
3637 (void) sender;
3638 (void) msg;
3639 GNUNET_break_op (0);
3640}
3641
3642
3643/**
3644 * Signature of the callback passed to #GNUNET_NAT_register() for
3645 * a function to call whenever our set of 'valid' addresses changes.
3646 *
3647 * @param cls closure
3648 * @param[in,out] app_ctx location where the app can store stuff
3649 * on add and retrieve it on remove
3650 * @param add_remove #GNUNET_YES to add a new public IP address,
3651 * #GNUNET_NO to remove a previous (now invalid) one
3652 * @param ac address class the address belongs to
3653 * @param addr either the previous or the new public IP address
3654 * @param addrlen actual length of the @a addr
3655 */
3656static void
3657nat_address_cb (void *cls,
3658 void **app_ctx,
3659 int add_remove,
3660 enum GNUNET_NAT_AddressClass ac,
3661 const struct sockaddr *addr,
3662 socklen_t addrlen)
3663{
3664 char *my_addr;
3665 struct GNUNET_TRANSPORT_AddressIdentifier *ai;
3666
3667 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3668 "nat address cb %s %s\n",
3669 add_remove ? "add" : "remove",
3670 GNUNET_a2s (addr, addrlen));
3671
3672 if (GNUNET_YES == add_remove)
3673 {
3674 enum GNUNET_NetworkType nt;
3675
3676 GNUNET_asprintf (&my_addr,
3677 "%s-%s",
3678 COMMUNICATOR_ADDRESS_PREFIX,
3679 GNUNET_a2s (addr, addrlen));
3680 nt = GNUNET_NT_scanner_get_type (is, addr, addrlen);
3681 ai =
3682 GNUNET_TRANSPORT_communicator_address_add (ch,
3683 my_addr,
3684 nt,
3685 GNUNET_TIME_UNIT_FOREVER_REL);
3686 GNUNET_free (my_addr);
3687 *app_ctx = ai;
3688 }
3689 else
3690 {
3691 ai = *app_ctx;
3692 GNUNET_TRANSPORT_communicator_address_remove (ai);
3693 *app_ctx = NULL;
3694 }
3695}
3696
3697
3698/**
3699 * This method adds addresses to the DLL, that are later register at the NAT service.
3700 */
3701static void
3702add_addr (struct sockaddr *in, socklen_t in_len)
3703{
3704
3705 struct Addresses *saddrs;
3706
3707 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3708 "add address %s\n",
3709 GNUNET_a2s (in, in_len));
3710
3711 saddrs = GNUNET_new (struct Addresses);
3712 saddrs->addr = in;
3713 saddrs->addr_len = in_len;
3714 GNUNET_CONTAINER_DLL_insert (addrs_head, addrs_tail, saddrs);
3715
3716 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3717 "after add address %s\n",
3718 GNUNET_a2s (in, in_len));
3719
3720 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3721 "add address %s\n",
3722 GNUNET_a2s (saddrs->addr, saddrs->addr_len));
3723
3724 addrs_lens++;
3725}
3726
3727
3728/**
3729 * This method launch network interactions for each address we like to bind to.
3730 *
3731 * @param addr The address we will listen to.
3732 * @param in_len The length of the address we will listen to.
3733 * @return GNUNET_SYSERR in case of error. GNUNET_OK in case we are successfully listen to the address.
3734 */
3735static int
3736init_socket (struct sockaddr *addr,
3737 socklen_t in_len)
3738{
3739 struct sockaddr_storage in_sto;
3740 socklen_t sto_len;
3741 struct GNUNET_NETWORK_Handle *listen_sock;
3742 struct ListenTask *lt;
3743 int sockfd;
3744 struct GNUNET_HashCode h_sock;
3745
3746 if (NULL == addr)
3747 {
3748 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3749 "Address is NULL.\n");
3750 return GNUNET_SYSERR;
3751 }
3752
3753 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3754 "address %s\n",
3755 GNUNET_a2s (addr, in_len));
3756
3757 listen_sock =
3758 GNUNET_NETWORK_socket_create (addr->sa_family, SOCK_STREAM, IPPROTO_TCP);
3759 if (NULL == listen_sock)
3760 {
3761 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
3762 return GNUNET_SYSERR;
3763 }
3764
3765 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (listen_sock, addr, in_len))
3766 {
3767 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
3768 GNUNET_NETWORK_socket_close (listen_sock);
3769 listen_sock = NULL;
3770 return GNUNET_SYSERR;
3771 }
3772
3773 if (GNUNET_OK !=
3774 GNUNET_NETWORK_socket_listen (listen_sock,
3775 5))
3776 {
3777 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
3778 "listen");
3779 GNUNET_NETWORK_socket_close (listen_sock);
3780 listen_sock = NULL;
3781 return GNUNET_SYSERR;
3782 }
3783
3784 /* We might have bound to port 0, allowing the OS to figure it out;
3785 thus, get the real IN-address from the socket */
3786 sto_len = sizeof(in_sto);
3787
3788 if (0 != getsockname (GNUNET_NETWORK_get_fd (listen_sock),
3789 (struct sockaddr *) &in_sto,
3790 &sto_len))
3791 {
3792 memcpy (&in_sto, addr, in_len);
3793 sto_len = in_len;
3794 }
3795
3796 // addr = (struct sockaddr *) &in_sto;
3797 in_len = sto_len;
3798 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3799 "Bound to `%s'\n",
3800 GNUNET_a2s ((const struct sockaddr *) &in_sto, sto_len));
3801 if (NULL == stats)
3802 stats = GNUNET_STATISTICS_create ("communicator-tcp", cfg);
3803
3804 if (NULL == is)
3805 is = GNUNET_NT_scanner_init ();
3806
3807 if (NULL == my_private_key)
3808 my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
3809 if (NULL == my_private_key)
3810 {
3811 GNUNET_log (
3812 GNUNET_ERROR_TYPE_ERROR,
3813 _ (
3814 "Transport service is lacking key configuration settings. Exiting.\n"));
3815 if (NULL != resolve_request_handle)
3816 GNUNET_RESOLVER_request_cancel (resolve_request_handle);
3817 GNUNET_SCHEDULER_shutdown ();
3818 return GNUNET_SYSERR;
3819 }
3820 GNUNET_CRYPTO_eddsa_key_get_public (my_private_key, &my_identity.public_key);
3821 /* start listening */
3822
3823 lt = GNUNET_new (struct ListenTask);
3824 lt->listen_sock = listen_sock;
3825
3826 lt->listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
3827 listen_sock,
3828 &listen_cb,
3829 lt);
3830
3831 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3832 "creating hash\n");
3833 sockfd = GNUNET_NETWORK_get_fd (lt->listen_sock);
3834 GNUNET_CRYPTO_hash (&sockfd,
3835 sizeof(int),
3836 &h_sock);
3837
3838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3839 "creating map\n");
3840 if (NULL == lt_map)
3841 lt_map = GNUNET_CONTAINER_multihashmap_create (2, GNUNET_NO);
3842
3843 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3844 "creating map entry\n");
3845 GNUNET_assert (GNUNET_OK ==
3846 GNUNET_CONTAINER_multihashmap_put (lt_map,
3847 &h_sock,
3848 lt,
3849 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3850
3851 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3852 "map entry created\n");
3853
3854 if (NULL == queue_map)
3855 queue_map = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
3856
3857 if (NULL == ch)
3858 ch = GNUNET_TRANSPORT_communicator_connect (cfg,
3859 COMMUNICATOR_CONFIG_SECTION,
3860 COMMUNICATOR_ADDRESS_PREFIX,
3861 GNUNET_TRANSPORT_CC_RELIABLE,
3862 &mq_init,
3863 NULL,
3864 &enc_notify_cb,
3865 NULL);
3866
3867 if (NULL == ch)
3868 {
3869 GNUNET_break (0);
3870 if (NULL != resolve_request_handle)
3871 GNUNET_RESOLVER_request_cancel (resolve_request_handle);
3872 GNUNET_SCHEDULER_shutdown ();
3873 return GNUNET_SYSERR;
3874 }
3875
3876 add_addr (addr, in_len);
3877 return GNUNET_OK;
3878
3879}
3880
3881
3882/**
3883 * This method reads from the DLL addrs_head to register them at the NAT service.
3884 */
3885static void
3886nat_register ()
3887{
3888 struct sockaddr **saddrs;
3889 socklen_t *saddr_lens;
3890 int i;
3891 size_t len;
3892
3893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3894 "starting nat register!\n");
3895 len = 0;
3896 i = 0;
3897 saddrs = GNUNET_malloc ((addrs_lens) * sizeof(struct sockaddr *));
3898 saddr_lens = GNUNET_malloc ((addrs_lens) * sizeof(socklen_t));
3899 for (struct Addresses *pos = addrs_head; NULL != pos; pos = pos->next)
3900 {
3901 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3902 "registering address %s\n",
3903 GNUNET_a2s (addrs_head->addr, addrs_head->addr_len));
3904
3905 saddr_lens[i] = addrs_head->addr_len;
3906 len += saddr_lens[i];
3907 saddrs[i] = GNUNET_memdup (addrs_head->addr, saddr_lens[i]);
3908 i++;
3909 }
3910
3911 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3912 "registering addresses %lu %lu %lu %lu\n",
3913 (addrs_lens) * sizeof(struct sockaddr *),
3914 (addrs_lens) * sizeof(socklen_t),
3915 len,
3916 sizeof(COMMUNICATOR_CONFIG_SECTION));
3917 nat = GNUNET_NAT_register (cfg,
3918 COMMUNICATOR_CONFIG_SECTION,
3919 IPPROTO_TCP,
3920 addrs_lens,
3921 (const struct sockaddr **) saddrs,
3922 saddr_lens,
3923 &nat_address_cb,
3924 try_connection_reversal,
3925 NULL /* closure */);
3926 for (i = addrs_lens - 1; i >= 0; i--)
3927 GNUNET_free (saddrs[i]);
3928 GNUNET_free (saddrs);
3929 GNUNET_free (saddr_lens);
3930
3931 if (NULL == nat)
3932 {
3933 GNUNET_break (0);
3934 if (NULL != resolve_request_handle)
3935 GNUNET_RESOLVER_request_cancel (resolve_request_handle);
3936 GNUNET_SCHEDULER_shutdown ();
3937 }
3938}
3939
3940
3941/**
3942 * This method is the callback called by the resolver API, and wraps method init_socket.
3943 *
3944 * @param cls The port we will bind to.
3945 * @param addr The address we will bind to.
3946 * @param in_len The length of the address we will bind to.
3947 */
3948static void
3949init_socket_resolv (void *cls,
3950 const struct sockaddr *addr,
3951 socklen_t in_len)
3952{
3953 struct sockaddr_in *v4;
3954 struct sockaddr_in6 *v6;
3955 struct sockaddr *in;
3956
3957 (void) cls;
3958 if (NULL != addr)
3959 {
3960 if (AF_INET == addr->sa_family)
3961 {
3962 v4 = (struct sockaddr_in *) addr;
3963 in = tcp_address_to_sockaddr_numeric_v4 (&in_len, *v4, bind_port);// _global);
3964 }
3965 else if (AF_INET6 == addr->sa_family)
3966 {
3967 v6 = (struct sockaddr_in6 *) addr;
3968 in = tcp_address_to_sockaddr_numeric_v6 (&in_len, *v6, bind_port);// _global);
3969 }
3970 else
3971 {
3972 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3973 "Address family %u not suitable (not AF_INET %u nor AF_INET6 %u \n",
3974 addr->sa_family,
3975 AF_INET,
3976 AF_INET6);
3977 return;
3978 }
3979 init_socket (in, in_len);
3980 }
3981 else
3982 {
3983 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
3984 "Address is NULL. This might be an error or the resolver finished resolving.\n");
3985 if (NULL == addrs_head)
3986 {
3987 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3988 "Resolver finished resolving, but we do not listen to an address!.\n");
3989 return;
3990 }
3991 nat_register ();
3992 }
3993}
3994
3995
3996/**
3997 * Setup communicator and launch network interactions.
3998 *
3999 * @param cls NULL (always)
4000 * @param args remaining command-line arguments
4001 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
4002 * @param c configuration
4003 */
4004static void
4005run (void *cls,
4006 char *const *args,
4007 const char *cfgfile,
4008 const struct GNUNET_CONFIGURATION_Handle *c)
4009{
4010 char *bindto;
4011 struct sockaddr *in;
4012 socklen_t in_len;
4013 struct sockaddr_in v4;
4014 struct sockaddr_in6 v6;
4015 char *start;
4016 unsigned int port;
4017 char dummy[2];
4018 char *rest = NULL;
4019 struct PortOnlyIpv4Ipv6 *po;
4020 socklen_t addr_len_ipv4;
4021 socklen_t addr_len_ipv6;
4022
4023 (void) cls;
4024
4025 pending_reversals = GNUNET_CONTAINER_multihashmap_create (16, GNUNET_NO);
4026 memset (&v4,0,sizeof(struct sockaddr_in));
4027 memset (&v6,0,sizeof(struct sockaddr_in6));
4028 cfg = c;
4029 if (GNUNET_OK !=
4030 GNUNET_CONFIGURATION_get_value_string (cfg,
4031 COMMUNICATOR_CONFIG_SECTION,
4032 "BINDTO",
4033 &bindto))
4034 {
4035 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
4036 COMMUNICATOR_CONFIG_SECTION,
4037 "BINDTO");
4038 return;
4039 }
4040 if (GNUNET_OK !=
4041 GNUNET_CONFIGURATION_get_value_number (cfg,
4042 COMMUNICATOR_CONFIG_SECTION,
4043 "MAX_QUEUE_LENGTH",
4044 &max_queue_length))
4045 {
4046 max_queue_length = DEFAULT_MAX_QUEUE_LENGTH;
4047 }
4048 if (GNUNET_OK !=
4049 GNUNET_CONFIGURATION_get_value_time (cfg,
4050 COMMUNICATOR_CONFIG_SECTION,
4051 "REKEY_INTERVAL",
4052 &rekey_interval))
4053 {
4054 rekey_interval = DEFAULT_REKEY_INTERVAL;
4055 }
4056 if (GNUNET_OK !=
4057 GNUNET_CONFIGURATION_get_value_number (cfg,
4058 COMMUNICATOR_CONFIG_SECTION,
4059 "REKEY_MAX_BYTES",
4060 &rekey_max_bytes))
4061 {
4062 rekey_max_bytes = REKEY_MAX_BYTES;
4063 }
4064 disable_v6 = GNUNET_NO;
4065 if ((GNUNET_NO == GNUNET_NETWORK_test_pf (PF_INET6)) ||
4066 (GNUNET_YES ==
4067 GNUNET_CONFIGURATION_get_value_yesno (cfg,
4068 COMMUNICATOR_CONFIG_SECTION,
4069 "DISABLE_V6")))
4070 {
4071 disable_v6 = GNUNET_YES;
4072 }
4073 peerstore = GNUNET_PEERSTORE_connect (cfg);
4074 if (NULL == peerstore)
4075 {
4076 GNUNET_free (bindto);
4077 GNUNET_break (0);
4078 GNUNET_SCHEDULER_shutdown ();
4079 return;
4080 }
4081
4082 GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
4083
4084 if (1 == sscanf (bindto, "%u%1s", &bind_port, dummy))
4085 {
4086 po = tcp_address_to_sockaddr_port_only (bindto, &bind_port);
4087 addr_len_ipv4 = po->addr_len_ipv4;
4088 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4089 "address po %s\n",
4090 GNUNET_a2s (po->addr_ipv4, addr_len_ipv4));
4091 if (NULL != po->addr_ipv4)
4092 {
4093 init_socket (po->addr_ipv4, addr_len_ipv4);
4094 }
4095 if (NULL != po->addr_ipv6)
4096 {
4097 addr_len_ipv6 = po->addr_len_ipv6;
4098 init_socket (po->addr_ipv6, addr_len_ipv6);
4099 }
4100 GNUNET_free (po);
4101 nat_register ();
4102 GNUNET_free (bindto);
4103 return;
4104 }
4105
4106 start = extract_address (bindto);
4107 // FIXME: check for NULL == start...
4108 if (1 == inet_pton (AF_INET, start, &v4.sin_addr))
4109 {
4110 bind_port = extract_port (bindto);
4111
4112 in = tcp_address_to_sockaddr_numeric_v4 (&in_len, v4, bind_port);
4113 init_socket (in, in_len);
4114 nat_register ();
4115 GNUNET_free (start);
4116 GNUNET_free (bindto);
4117 return;
4118 }
4119
4120 if (1 == inet_pton (AF_INET6, start, &v6.sin6_addr))
4121 {
4122 bind_port = extract_port (bindto);
4123 in = tcp_address_to_sockaddr_numeric_v6 (&in_len, v6, bind_port);
4124 init_socket (in, in_len);
4125 nat_register ();
4126 GNUNET_free (start);
4127 GNUNET_free (bindto);
4128 return;
4129 }
4130
4131 bind_port = extract_port (bindto);
4132 resolve_request_handle = GNUNET_RESOLVER_ip_get (strtok_r (bindto,
4133 ":",
4134 &rest),
4135 AF_UNSPEC,
4136 GNUNET_TIME_UNIT_MINUTES,
4137 &init_socket_resolv,
4138 &port);
4139
4140 GNUNET_free (bindto);
4141 GNUNET_free (start);
4142}
4143
4144
4145/**
4146 * The main function for the UNIX communicator.
4147 *
4148 * @param argc number of arguments from the command line
4149 * @param argv command line arguments
4150 * @return 0 ok, 1 on error
4151 */
4152int
4153main (int argc, char *const *argv)
4154{
4155 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
4156 GNUNET_GETOPT_OPTION_END
4157 };
4158 int ret;
4159
4160 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4161 "Starting tcp communicator\n");
4162 if (GNUNET_OK !=
4163 GNUNET_STRINGS_get_utf8_args (argc, argv,
4164 &argc, &argv))
4165 return 2;
4166
4167 ret = (GNUNET_OK ==
4168 GNUNET_PROGRAM_run (argc,
4169 argv,
4170 "gnunet-communicator-tcp",
4171 _ ("GNUnet TCP communicator"),
4172 options,
4173 &run,
4174 NULL))
4175 ? 0
4176 : 1;
4177 GNUNET_free_nz ((void *) argv);
4178 return ret;
4179}
4180
4181
4182/* end of gnunet-communicator-tcp.c */