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