also config files
[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 DEFAULT_REKEY_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  * The rekey interval
526  */
527 static struct GNUNET_TIME_Relative rekey_interval;
528
529 /**
530  * Our private key.
531  */
532 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
533
534 /**
535  * Our configuration.
536  */
537 static const struct GNUNET_CONFIGURATION_Handle *cfg;
538
539 /**
540  * Network scanner to determine network types.
541  */
542 static struct GNUNET_NT_InterfaceScanner *is;
543
544 /**
545  * Connection to NAT service.
546  */
547 static struct GNUNET_NAT_Handle *nat;
548
549 /**
550  * Protoqueues DLL head.
551  */
552 static struct ProtoQueue *proto_head;
553
554 /**
555  * Protoqueues DLL tail.
556  */
557 static struct ProtoQueue *proto_tail;
558
559
560 /**
561  * We have been notified that our listen socket has something to
562  * read. Do the read and reschedule this function to be called again
563  * once more is available.
564  *
565  * @param cls NULL
566  */
567 static void
568 listen_cb (void *cls);
569
570
571 /**
572  * Functions with this signature are called whenever we need
573  * to close a queue due to a disconnect or failure to
574  * establish a connection.
575  *
576  * @param queue queue to close down
577  */
578 static void
579 queue_destroy (struct Queue *queue)
580 {
581   struct GNUNET_MQ_Handle *mq;
582
583   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
584               "Disconnecting queue for peer `%s'\n",
585               GNUNET_i2s (&queue->target));
586   if (NULL != (mq = queue->mq))
587   {
588     queue->mq = NULL;
589     GNUNET_MQ_destroy (mq);
590   }
591   if (NULL != queue->qh)
592   {
593     GNUNET_TRANSPORT_communicator_mq_del (queue->qh);
594     queue->qh = NULL;
595   }
596   GNUNET_assert (
597     GNUNET_YES ==
598     GNUNET_CONTAINER_multipeermap_remove (queue_map, &queue->target, queue));
599   GNUNET_STATISTICS_set (stats,
600                          "# queues active",
601                          GNUNET_CONTAINER_multipeermap_size (queue_map),
602                          GNUNET_NO);
603   if (NULL != queue->read_task)
604   {
605     GNUNET_SCHEDULER_cancel (queue->read_task);
606     queue->read_task = NULL;
607   }
608   if (NULL != queue->write_task)
609   {
610     GNUNET_SCHEDULER_cancel (queue->write_task);
611     queue->write_task = NULL;
612   }
613   GNUNET_NETWORK_socket_close (queue->sock);
614   gcry_cipher_close (queue->in_cipher);
615   gcry_cipher_close (queue->out_cipher);
616   GNUNET_free (queue->address);
617   if (0 != queue->backpressure)
618     queue->destroyed = GNUNET_YES;
619   else
620     GNUNET_free (queue);
621   if (NULL == listen_task)
622     listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
623                                                  listen_sock,
624                                                  &listen_cb,
625                                                  NULL);
626 }
627
628
629 /**
630  * Compute @a mac over @a buf, and ratched the @a hmac_secret.
631  *
632  * @param[in,out] hmac_secret secret for HMAC calculation
633  * @param buf buffer to MAC
634  * @param buf_size number of bytes in @a buf
635  * @param smac[out] where to write the HMAC
636  */
637 static void
638 calculate_hmac (struct GNUNET_HashCode *hmac_secret,
639                 const void *buf,
640                 size_t buf_size,
641                 struct GNUNET_ShortHashCode *smac)
642 {
643   struct GNUNET_HashCode mac;
644
645   GNUNET_CRYPTO_hmac_raw (hmac_secret,
646                           sizeof(struct GNUNET_HashCode),
647                           buf,
648                           buf_size,
649                           &mac);
650   /* truncate to `struct GNUNET_ShortHashCode` */
651   memcpy (smac, &mac, sizeof(struct GNUNET_ShortHashCode));
652   /* ratchet hmac key */
653   GNUNET_CRYPTO_hash (hmac_secret,
654                       sizeof(struct GNUNET_HashCode),
655                       hmac_secret);
656 }
657
658
659 /**
660  * Append a 'finish' message to the outgoing transmission. Once the
661  * finish has been transmitted, destroy the queue.
662  *
663  * @param queue queue to shut down nicely
664  */
665 static void
666 queue_finish (struct Queue *queue)
667 {
668   struct TCPFinish fin;
669
670   memset (&fin, 0, sizeof(fin));
671   fin.header.size = htons (sizeof(fin));
672   fin.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH);
673   calculate_hmac (&queue->out_hmac, &fin, sizeof(fin), &fin.hmac);
674   /* if there is any message left in pwrite_buf, we
675      overwrite it (possibly dropping the last message
676      from CORE hard here) */
677   memcpy (queue->pwrite_buf, &fin, sizeof(fin));
678   queue->pwrite_off = sizeof(fin);
679   /* This flag will ensure that #queue_write() no longer
680      notifies CORE about the possibility of sending
681      more data, and that #queue_write() will call
682   #queue_destroy() once the @c fin was fully written. */
683   queue->finishing = GNUNET_YES;
684 }
685
686
687 /**
688  * Increment queue timeout due to activity.  We do not immediately
689  * notify the monitor here as that might generate excessive
690  * signalling.
691  *
692  * @param queue queue for which the timeout should be rescheduled
693  */
694 static void
695 reschedule_queue_timeout (struct Queue *queue)
696 {
697   queue->timeout =
698     GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
699 }
700
701
702 /**
703  * Queue read task. If we hit the timeout, disconnect it
704  *
705  * @param cls the `struct Queue *` to disconnect
706  */
707 static void
708 queue_read (void *cls);
709
710
711 /**
712  * Core tells us it is done processing a message that transport
713  * received on a queue with status @a success.
714  *
715  * @param cls a `struct Queue *` where the message originally came from
716  * @param success #GNUNET_OK on success
717  */
718 static void
719 core_read_finished_cb (void *cls, int success)
720 {
721   struct Queue *queue = cls;
722   if (GNUNET_OK != success)
723     GNUNET_STATISTICS_update (stats,
724                               "# messages lost in communicator API towards CORE",
725                               1,
726                               GNUNET_NO);
727   queue->backpressure--;
728   /* handle deferred queue destruction */
729   if ((queue->destroyed) && (0 == queue->backpressure))
730   {
731     GNUNET_free (queue);
732     return;
733   }
734   reschedule_queue_timeout (queue);
735   /* possibly unchoke reading, now that CORE made progress */
736   if (NULL == queue->read_task)
737     queue->read_task =
738       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining (
739                                        queue->timeout),
740                                      queue->sock,
741                                      &queue_read,
742                                      queue);
743 }
744
745
746 /**
747  * We received @a plaintext_len bytes of @a plaintext on @a queue.
748  * Pass it on to CORE.  If transmission is actually happening,
749  * increase backpressure counter.
750  *
751  * @param queue the queue that received the plaintext
752  * @param plaintext the plaintext that was received
753  * @param plaintext_len number of bytes of plaintext received
754  */
755 static void
756 pass_plaintext_to_core (struct Queue *queue,
757                         const void *plaintext,
758                         size_t plaintext_len)
759 {
760   const struct GNUNET_MessageHeader *hdr = plaintext;
761   int ret;
762
763   if (ntohs (hdr->size) != plaintext_len)
764   {
765     /* NOTE: If we ever allow multiple CORE messages in one
766        BOX, this will have to change! */
767     GNUNET_break (0);
768     return;
769   }
770   ret = GNUNET_TRANSPORT_communicator_receive (ch,
771                                                &queue->target,
772                                                hdr,
773                                                ADDRESS_VALIDITY_PERIOD,
774                                                &core_read_finished_cb,
775                                                queue);
776   if (GNUNET_OK == ret)
777     queue->backpressure++;
778   GNUNET_break (GNUNET_NO != ret);  /* backpressure not working!? */
779   if (GNUNET_SYSERR == ret)
780     GNUNET_STATISTICS_update (stats,
781                               "# bytes lost due to CORE not running",
782                               plaintext_len,
783                               GNUNET_NO);
784 }
785
786
787 /**
788  * Setup @a cipher based on shared secret @a dh and decrypting
789  * peer @a pid.
790  *
791  * @param dh shared secret
792  * @param pid decrypting peer's identity
793  * @param cipher[out] cipher to initialize
794  * @param hmac_key[out] HMAC key to initialize
795  */
796 static void
797 setup_cipher (const struct GNUNET_HashCode *dh,
798               const struct GNUNET_PeerIdentity *pid,
799               gcry_cipher_hd_t *cipher,
800               struct GNUNET_HashCode *hmac_key)
801 {
802   char key[256 / 8];
803   char ctr[128 / 8];
804
805   gcry_cipher_open (cipher,
806                     GCRY_CIPHER_AES256 /* low level: go for speed */,
807                     GCRY_CIPHER_MODE_CTR,
808                     0 /* flags */);
809   GNUNET_assert (GNUNET_YES == GNUNET_CRYPTO_kdf (key,
810                                                   sizeof(key),
811                                                   "TCP-key",
812                                                   strlen ("TCP-key"),
813                                                   dh,
814                                                   sizeof(*dh),
815                                                   pid,
816                                                   sizeof(*pid),
817                                                   NULL,
818                                                   0));
819   gcry_cipher_setkey (*cipher, key, sizeof(key));
820   GNUNET_assert (GNUNET_YES == GNUNET_CRYPTO_kdf (ctr,
821                                                   sizeof(ctr),
822                                                   "TCP-ctr",
823                                                   strlen ("TCP-ctr"),
824                                                   dh,
825                                                   sizeof(*dh),
826                                                   pid,
827                                                   sizeof(*pid),
828                                                   NULL,
829                                                   0));
830   gcry_cipher_setctr (*cipher, ctr, sizeof(ctr));
831   GNUNET_assert (GNUNET_YES ==
832                  GNUNET_CRYPTO_kdf (hmac_key,
833                                     sizeof(struct GNUNET_HashCode),
834                                     "TCP-hmac",
835                                     strlen ("TCP-hmac"),
836                                     dh,
837                                     sizeof(*dh),
838                                     pid,
839                                     sizeof(*pid),
840                                     NULL,
841                                     0));
842 }
843
844
845 /**
846  * Setup cipher of @a queue for decryption.
847  *
848  * @param ephemeral ephemeral key we received from the other peer
849  * @param queue[in,out] queue to initialize decryption cipher for
850  */
851 static void
852 setup_in_cipher (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
853                  struct Queue *queue)
854 {
855   struct GNUNET_HashCode dh;
856
857   GNUNET_CRYPTO_eddsa_ecdh (my_private_key, ephemeral, &dh);
858   setup_cipher (&dh, &my_identity, &queue->in_cipher, &queue->in_hmac);
859 }
860
861
862 /**
863  * Handle @a rekey message on @a queue. The message was already
864  * HMAC'ed, but we should additionally still check the signature.
865  * Then we need to stop the old cipher and start afresh.
866  *
867  * @param queue the queue @a rekey was received on
868  * @param rekey the rekey message
869  */
870 static void
871 do_rekey (struct Queue *queue, const struct TCPRekey *rekey)
872 {
873   struct TcpHandshakeSignature thp;
874   thp.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY);
875   thp.purpose.size = htonl (sizeof(thp));
876   thp.sender = queue->target;
877   thp.receiver = my_identity;
878   thp.ephemeral = rekey->ephemeral;
879   thp.monotonic_time = rekey->monotonic_time;
880   /* FIXME: check monotonic time is monotonic... */
881   if (GNUNET_OK !=
882       GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY,
883                                   &thp.purpose,
884                                   &rekey->sender_sig,
885                                   &queue->target.public_key))
886   {
887     GNUNET_break (0);
888     queue_finish (queue);
889     return;
890   }
891   gcry_cipher_close (queue->in_cipher);
892   queue->rekeyed = GNUNET_YES;
893   setup_in_cipher (&rekey->ephemeral, queue);
894 }
895
896
897 /**
898  * Test if we have received a full message in plaintext.
899  * If so, handle it.
900  *
901  * @param queue queue to process inbound plaintext for
902  * @return number of bytes of plaintext handled, 0 for none
903  */
904 static size_t
905 try_handle_plaintext (struct Queue *queue)
906 {
907   const struct GNUNET_MessageHeader *hdr =
908     (const struct GNUNET_MessageHeader *) queue->pread_buf;
909   const struct TCPBox *box = (const struct TCPBox *) queue->pread_buf;
910   const struct TCPRekey *rekey = (const struct TCPRekey *) queue->pread_buf;
911   const struct TCPFinish *fin = (const struct TCPFinish *) queue->pread_buf;
912   struct TCPRekey rekeyz;
913   struct TCPFinish finz;
914   struct GNUNET_ShortHashCode tmac;
915   uint16_t type;
916   size_t size = 0; /* make compiler happy */
917
918   if (sizeof(*hdr) > queue->pread_off)
919     return 0; /* not even a header */
920   type = ntohs (hdr->type);
921   switch (type)
922   {
923   case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX:
924     /* Special case: header size excludes box itself! */
925     if (ntohs (hdr->size) + sizeof(struct TCPBox) > queue->pread_off)
926       return 0;
927     calculate_hmac (&queue->in_hmac, &box[1], ntohs (hdr->size), &tmac);
928     if (0 != memcmp (&tmac, &box->hmac, sizeof(tmac)))
929     {
930       GNUNET_break_op (0);
931       queue_finish (queue);
932       return 0;
933     }
934     pass_plaintext_to_core (queue, (const void *) &box[1], ntohs (hdr->size));
935     size = ntohs (hdr->size) + sizeof(*box);
936     break;
937
938   case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY:
939     if (sizeof(*rekey) > queue->pread_off)
940       return 0;
941     if (ntohs (hdr->size) != sizeof(*rekey))
942     {
943       GNUNET_break_op (0);
944       queue_finish (queue);
945       return 0;
946     }
947     rekeyz = *rekey;
948     memset (&rekeyz.hmac, 0, sizeof(rekeyz.hmac));
949     calculate_hmac (&queue->in_hmac, &rekeyz, sizeof(rekeyz), &tmac);
950     if (0 != memcmp (&tmac, &rekey->hmac, sizeof(tmac)))
951     {
952       GNUNET_break_op (0);
953       queue_finish (queue);
954       return 0;
955     }
956     do_rekey (queue, rekey);
957     size = ntohs (hdr->size);
958     break;
959
960   case GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_FINISH:
961     if (sizeof(*fin) > queue->pread_off)
962       return 0;
963     if (ntohs (hdr->size) != sizeof(*fin))
964     {
965       GNUNET_break_op (0);
966       queue_finish (queue);
967       return 0;
968     }
969     finz = *fin;
970     memset (&finz.hmac, 0, sizeof(finz.hmac));
971     calculate_hmac (&queue->in_hmac, &rekeyz, sizeof(rekeyz), &tmac);
972     if (0 != memcmp (&tmac, &fin->hmac, sizeof(tmac)))
973     {
974       GNUNET_break_op (0);
975       queue_finish (queue);
976       return 0;
977     }
978     /* handle FINISH by destroying queue */
979     queue_destroy (queue);
980     break;
981
982   default:
983     GNUNET_break_op (0);
984     queue_finish (queue);
985     return 0;
986   }
987   GNUNET_assert (0 != size);
988   return size;
989 }
990
991
992 /**
993  * Queue read task. If we hit the timeout, disconnect it
994  *
995  * @param cls the `struct Queue *` to disconnect
996  */
997 static void
998 queue_read (void *cls)
999 {
1000   struct Queue *queue = cls;
1001   struct GNUNET_TIME_Relative left;
1002   ssize_t rcvd;
1003
1004   queue->read_task = NULL;
1005   rcvd = GNUNET_NETWORK_socket_recv (queue->sock,
1006                                      &queue->cread_buf[queue->cread_off],
1007                                      BUF_SIZE - queue->cread_off);
1008   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1009               "Received %lu bytes from TCP queue\n", rcvd);
1010   if (-1 == rcvd)
1011   {
1012     if ((EAGAIN != errno) && (EINTR != errno))
1013     {
1014       GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "recv");
1015       queue_finish (queue);
1016       return;
1017     }
1018     /* try again */
1019     left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
1020     queue->read_task =
1021       GNUNET_SCHEDULER_add_read_net (left, queue->sock, &queue_read, queue);
1022     return;
1023   }
1024   if (0 != rcvd)
1025     reschedule_queue_timeout (queue);
1026   queue->cread_off += rcvd;
1027   while ((queue->pread_off < sizeof(queue->pread_buf)) &&
1028          (queue->cread_off > 0))
1029   {
1030     size_t max = GNUNET_MIN (sizeof(queue->pread_buf) - queue->pread_off,
1031                              queue->cread_off);
1032     size_t done;
1033     size_t total;
1034     size_t old_pread_off = queue->pread_off;
1035
1036     GNUNET_assert (0 ==
1037                    gcry_cipher_decrypt (queue->in_cipher,
1038                                         &queue->pread_buf[queue->pread_off],
1039                                         max,
1040                                         queue->cread_buf,
1041                                         max));
1042     queue->pread_off += max;
1043     total = 0;
1044     while (0 != (done = try_handle_plaintext (queue)))
1045     {
1046       /* 'done' bytes of plaintext were used, shift buffer */
1047       GNUNET_assert (done <= queue->pread_off);
1048       /* NOTE: this memmove() could possibly sometimes be
1049          avoided if we pass 'total' into try_handle_plaintext()
1050          and use it at an offset into the buffer there! */
1051       memmove (queue->pread_buf,
1052                &queue->pread_buf[done],
1053                queue->pread_off - done);
1054       queue->pread_off -= done;
1055       total += done;
1056       /* The last plaintext was a rekey, abort for now */
1057       if (GNUNET_YES == queue->rekeyed)
1058         break;
1059     }
1060     /* when we encounter a rekey message, the decryption above uses the
1061        wrong key for everything after the rekey; in that case, we have
1062        to re-do the decryption at 'total' instead of at 'max'.
1063        However, we have to take into account that the plaintext buffer may have
1064        already contained data and not jumpt too far ahead in the ciphertext.
1065        If there is no rekey and the last message is incomplete (max > total),
1066        it is safe to keep the decryption so we shift by 'max' */
1067     if (GNUNET_YES == queue->rekeyed)
1068     {
1069       max = total - old_pread_off;
1070       queue->rekeyed = GNUNET_NO;
1071       queue->pread_off = 0;
1072     }
1073     memmove (queue->cread_buf, &queue->cread_buf[max], queue->cread_off - max);
1074     queue->cread_off -= max;
1075   }
1076   if (BUF_SIZE == queue->cread_off)
1077     return; /* buffer full, suspend reading */
1078   left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
1079   if (0 != left.rel_value_us)
1080   {
1081     if (max_queue_length > queue->backpressure)
1082     {
1083       /* continue reading */
1084       left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
1085       queue->read_task =
1086         GNUNET_SCHEDULER_add_read_net (left, queue->sock, &queue_read, queue);
1087     }
1088     return;
1089   }
1090   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1091               "Queue %p was idle for %s, disconnecting\n",
1092               queue,
1093               GNUNET_STRINGS_relative_time_to_string (
1094                 GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1095                 GNUNET_YES));
1096   queue_finish (queue);
1097 }
1098
1099
1100 /**
1101  * Convert TCP bind specification to a `struct sockaddr *`
1102  *
1103  * @param bindto bind specification to convert
1104  * @param[out] sock_len set to the length of the address
1105  * @return converted bindto specification
1106  */
1107 static struct sockaddr *
1108 tcp_address_to_sockaddr (const char *bindto, socklen_t *sock_len)
1109 {
1110   struct sockaddr *in;
1111   unsigned int port;
1112   char dummy[2];
1113   char *colon;
1114   char *cp;
1115
1116   if (1 == sscanf (bindto, "%u%1s", &port, dummy))
1117   {
1118     /* interpreting value as just a PORT number */
1119     if (port > UINT16_MAX)
1120     {
1121       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1122                   "BINDTO specification `%s' invalid: value too large for port\n",
1123                   bindto);
1124       return NULL;
1125     }
1126     if ((GNUNET_NO == GNUNET_NETWORK_test_pf (PF_INET6)) ||
1127         (GNUNET_YES ==
1128          GNUNET_CONFIGURATION_get_value_yesno (cfg,
1129                                                COMMUNICATOR_CONFIG_SECTION,
1130                                                "DISABLE_V6")))
1131     {
1132       struct sockaddr_in *i4;
1133
1134       i4 = GNUNET_malloc (sizeof(struct sockaddr_in));
1135       i4->sin_family = AF_INET;
1136       i4->sin_port = htons ((uint16_t) port);
1137 #if HAVE_SOCKADDR_IN_SIN_LEN
1138       i4->sin_len = sizeof(sizeof(struct sockaddr_in));
1139 #endif
1140       *sock_len = sizeof(struct sockaddr_in);
1141       in = (struct sockaddr *) i4;
1142     }
1143     else
1144     {
1145       struct sockaddr_in6 *i6;
1146
1147       i6 = GNUNET_malloc (sizeof(struct sockaddr_in6));
1148       i6->sin6_family = AF_INET6;
1149       i6->sin6_port = htons ((uint16_t) port);
1150 #if HAVE_SOCKADDR_IN_SIN_LEN
1151       i6->sin6_len = sizeof(sizeof(struct sockaddr_in6));
1152 #endif
1153       *sock_len = sizeof(struct sockaddr_in6);
1154       in = (struct sockaddr *) i6;
1155     }
1156     return in;
1157   }
1158   cp = GNUNET_strdup (bindto);
1159   colon = strrchr (cp, ':');
1160   if (NULL != colon)
1161   {
1162     /* interpet value after colon as port */
1163     *colon = '\0';
1164     colon++;
1165     if (1 == sscanf (colon, "%u%1s", &port, dummy))
1166     {
1167       /* interpreting value as just a PORT number */
1168       if (port > UINT16_MAX)
1169       {
1170         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1171                     "BINDTO specification `%s' invalid: value too large for port\n",
1172                     bindto);
1173         GNUNET_free (cp);
1174         return NULL;
1175       }
1176     }
1177     else
1178     {
1179       GNUNET_log (
1180         GNUNET_ERROR_TYPE_ERROR,
1181         "BINDTO specification `%s' invalid: last ':' not followed by number\n",
1182         bindto);
1183       GNUNET_free (cp);
1184       return NULL;
1185     }
1186   }
1187   else
1188   {
1189     /* interpret missing port as 0, aka pick any free one */
1190     port = 0;
1191   }
1192   {
1193     /* try IPv4 */
1194     struct sockaddr_in v4;
1195
1196     if (1 == inet_pton (AF_INET, cp, &v4.sin_addr))
1197     {
1198       v4.sin_family = AF_INET;
1199       v4.sin_port = htons ((uint16_t) port);
1200 #if HAVE_SOCKADDR_IN_SIN_LEN
1201       v4.sin_len = sizeof(struct sockaddr_in);
1202 #endif
1203       in = GNUNET_memdup (&v4, sizeof(v4));
1204       *sock_len = sizeof(v4);
1205       GNUNET_free (cp);
1206       return in;
1207     }
1208   }
1209   {
1210     /* try IPv6 */
1211     struct sockaddr_in6 v6;
1212     const char *start;
1213
1214     start = cp;
1215     if (('[' == *cp) && (']' == cp[strlen (cp) - 1]))
1216     {
1217       start++;   /* skip over '[' */
1218       cp[strlen (cp) - 1] = '\0';  /* eat ']' */
1219     }
1220     if (1 == inet_pton (AF_INET6, start, &v6.sin6_addr))
1221     {
1222       v6.sin6_family = AF_INET6;
1223       v6.sin6_port = htons ((uint16_t) port);
1224 #if HAVE_SOCKADDR_IN_SIN_LEN
1225       v6.sin6_len = sizeof(sizeof(struct sockaddr_in6));
1226 #endif
1227       in = GNUNET_memdup (&v6, sizeof(v6));
1228       *sock_len = sizeof(v6);
1229       GNUNET_free (cp);
1230       return in;
1231     }
1232   }
1233   /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
1234   GNUNET_free (cp);
1235   return NULL;
1236 }
1237
1238
1239 /**
1240  * Setup cipher for outgoing data stream based on target and
1241  * our ephemeral private key.
1242  *
1243  * @param queue queue to setup outgoing (encryption) cipher for
1244  */
1245 static void
1246 setup_out_cipher (struct Queue *queue)
1247 {
1248   struct GNUNET_HashCode dh;
1249
1250   GNUNET_CRYPTO_ecdh_eddsa (&queue->ephemeral, &queue->target.public_key, &dh);
1251   /* we don't need the private key anymore, drop it! */
1252   memset (&queue->ephemeral, 0, sizeof(queue->ephemeral));
1253   setup_cipher (&dh, &queue->target, &queue->out_cipher, &queue->out_hmac);
1254   queue->rekey_time = GNUNET_TIME_relative_to_absolute (rekey_interval);
1255   queue->rekey_left_bytes =
1256     GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, REKEY_MAX_BYTES);
1257 }
1258
1259
1260 /**
1261  * Inject a `struct TCPRekey` message into the queue's plaintext
1262  * buffer.
1263  *
1264  * @param queue queue to perform rekeying on
1265  */
1266 static void
1267 inject_rekey (struct Queue *queue)
1268 {
1269   struct TCPRekey rekey;
1270   struct TcpHandshakeSignature thp;
1271
1272   GNUNET_assert (0 == queue->pwrite_off);
1273   memset (&rekey, 0, sizeof(rekey));
1274   GNUNET_assert (GNUNET_OK ==
1275                  GNUNET_CRYPTO_ecdhe_key_create2 (&queue->ephemeral));
1276   rekey.header.type = ntohs (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_REKEY);
1277   rekey.header.size = ntohs (sizeof(rekey));
1278   GNUNET_CRYPTO_ecdhe_key_get_public (&queue->ephemeral, &rekey.ephemeral);
1279   rekey.monotonic_time =
1280     GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1281   thp.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_REKEY);
1282   thp.purpose.size = htonl (sizeof(thp));
1283   thp.sender = my_identity;
1284   thp.receiver = queue->target;
1285   thp.ephemeral = rekey.ephemeral;
1286   thp.monotonic_time = rekey.monotonic_time;
1287   GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_private_key,
1288                                                         &thp.purpose,
1289                                                         &rekey.sender_sig));
1290   calculate_hmac (&queue->out_hmac, &rekey, sizeof(rekey), &rekey.hmac);
1291   /* Encrypt rekey message with 'old' cipher */
1292   GNUNET_assert (0 ==
1293                  gcry_cipher_encrypt (queue->out_cipher,
1294                                       &queue->cwrite_buf[queue->cwrite_off],
1295                                       sizeof(rekey),
1296                                       &rekey,
1297                                       sizeof(rekey)));
1298   queue->cwrite_off += sizeof(rekey);
1299   /* Setup new cipher for successive messages */
1300   gcry_cipher_close (queue->out_cipher);
1301   setup_out_cipher (queue);
1302 }
1303
1304
1305 /**
1306  * We have been notified that our socket is ready to write.
1307  * Then reschedule this function to be called again once more is available.
1308  *
1309  * @param cls a `struct Queue`
1310  */
1311 static void
1312 queue_write (void *cls)
1313 {
1314   struct Queue *queue = cls;
1315   ssize_t sent;
1316   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "In queue write\n");
1317   queue->write_task = NULL;
1318   if (0 != queue->cwrite_off)
1319   {
1320     sent = GNUNET_NETWORK_socket_send (queue->sock,
1321                                        queue->cwrite_buf,
1322                                        queue->cwrite_off);
1323     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1324                 "Sent %lu bytes to TCP queue\n", sent);
1325     if ((-1 == sent) && (EAGAIN != errno) && (EINTR != errno))
1326     {
1327       GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "send");
1328       queue_destroy (queue);
1329       return;
1330     }
1331     if (sent > 0)
1332     {
1333       size_t usent = (size_t) sent;
1334       queue->cwrite_off -= usent;
1335       memmove (queue->cwrite_buf,
1336                &queue->cwrite_buf[usent],
1337                queue->cwrite_off);
1338       reschedule_queue_timeout (queue);
1339     }
1340   }
1341   /* can we encrypt more? (always encrypt full messages, needed
1342      such that #mq_cancel() can work!) */
1343   if ((0 < queue->rekey_left_bytes) &&
1344       (queue->pwrite_off > 0) &&
1345       (queue->cwrite_off + queue->pwrite_off <= BUF_SIZE))
1346   {
1347     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1348                 "Encrypting %lu bytes\n", queue->pwrite_off);
1349     GNUNET_assert (0 ==
1350                    gcry_cipher_encrypt (queue->out_cipher,
1351                                         &queue->cwrite_buf[queue->cwrite_off],
1352                                         queue->pwrite_off,
1353                                         queue->pwrite_buf,
1354                                         queue->pwrite_off));
1355     if (queue->rekey_left_bytes > queue->pwrite_off)
1356       queue->rekey_left_bytes -= queue->pwrite_off;
1357     else
1358       queue->rekey_left_bytes = 0;
1359     queue->cwrite_off += queue->pwrite_off;
1360     queue->pwrite_off = 0;
1361   }
1362   if ((0 == queue->pwrite_off) &&
1363       ((0 == queue->rekey_left_bytes) ||
1364        (0 ==
1365         GNUNET_TIME_absolute_get_remaining (queue->rekey_time).rel_value_us)))
1366   {
1367     inject_rekey (queue);
1368   }
1369   if ((0 == queue->pwrite_off) && (! queue->finishing) &&
1370       (GNUNET_YES == queue->mq_awaits_continue))
1371   {
1372     queue->mq_awaits_continue = GNUNET_NO;
1373     GNUNET_MQ_impl_send_continue (queue->mq);
1374   }
1375   /* did we just finish writing 'finish'? */
1376   if ((0 == queue->cwrite_off) && (GNUNET_YES == queue->finishing))
1377   {
1378     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1379                 "Finishing queue\n");
1380     queue_destroy (queue);
1381     return;
1382   }
1383   /* do we care to write more? */
1384   if ((0 < queue->cwrite_off) || (0 < queue->pwrite_off))
1385     queue->write_task =
1386       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1387                                       queue->sock,
1388                                       &queue_write,
1389                                       queue);
1390 }
1391
1392
1393 /**
1394  * Signature of functions implementing the sending functionality of a
1395  * message queue.
1396  *
1397  * @param mq the message queue
1398  * @param msg the message to send
1399  * @param impl_state our `struct Queue`
1400  */
1401 static void
1402 mq_send (struct GNUNET_MQ_Handle *mq,
1403          const struct GNUNET_MessageHeader *msg,
1404          void *impl_state)
1405 {
1406   struct Queue *queue = impl_state;
1407   uint16_t msize = ntohs (msg->size);
1408   struct TCPBox box;
1409   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1410               "In MQ send. Queue finishing: %s; write task running: %s\n",
1411               (GNUNET_YES == queue->finishing) ? "yes" : "no",
1412               (NULL == queue->write_task) ? "yes" : "no");
1413   GNUNET_assert (mq == queue->mq);
1414   queue->mq_awaits_continue = GNUNET_YES;
1415   if (GNUNET_YES == queue->finishing)
1416     return; /* this queue is dying, drop msg */
1417   GNUNET_assert (0 == queue->pwrite_off);
1418   box.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_TCP_BOX);
1419   box.header.size = htons (msize);
1420   calculate_hmac (&queue->out_hmac, msg, msize, &box.hmac);
1421   memcpy (&queue->pwrite_buf[queue->pwrite_off], &box, sizeof(box));
1422   queue->pwrite_off += sizeof(box);
1423   memcpy (&queue->pwrite_buf[queue->pwrite_off], msg, msize);
1424   queue->pwrite_off += msize;
1425   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1426               "%lu bytes of plaintext to send\n", queue->pwrite_off);
1427   GNUNET_assert (NULL != queue->sock);
1428   if (NULL == queue->write_task)
1429     queue->write_task =
1430       GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1431                                       queue->sock,
1432                                       &queue_write,
1433                                       queue);
1434 }
1435
1436
1437 /**
1438  * Signature of functions implementing the destruction of a message
1439  * queue.  Implementations must not free @a mq, but should take care
1440  * of @a impl_state.
1441  *
1442  * @param mq the message queue to destroy
1443  * @param impl_state our `struct Queue`
1444  */
1445 static void
1446 mq_destroy (struct GNUNET_MQ_Handle *mq, void *impl_state)
1447 {
1448   struct Queue *queue = impl_state;
1449
1450   if (mq == queue->mq)
1451   {
1452     queue->mq = NULL;
1453     queue_finish (queue);
1454   }
1455 }
1456
1457
1458 /**
1459  * Implementation function that cancels the currently sent message.
1460  *
1461  * @param mq message queue
1462  * @param impl_state our `struct Queue`
1463  */
1464 static void
1465 mq_cancel (struct GNUNET_MQ_Handle *mq, void *impl_state)
1466 {
1467   struct Queue *queue = impl_state;
1468
1469   GNUNET_assert (0 != queue->pwrite_off);
1470   queue->pwrite_off = 0;
1471 }
1472
1473
1474 /**
1475  * Generic error handler, called with the appropriate
1476  * error code and the same closure specified at the creation of
1477  * the message queue.
1478  * Not every message queue implementation supports an error handler.
1479  *
1480  * @param cls our `struct Queue`
1481  * @param error error code
1482  */
1483 static void
1484 mq_error (void *cls, enum GNUNET_MQ_Error error)
1485 {
1486   struct Queue *queue = cls;
1487
1488   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1489               "MQ error in queue to %s: %d\n",
1490               GNUNET_i2s (&queue->target),
1491               (int) error);
1492   queue_finish (queue);
1493 }
1494
1495
1496 /**
1497  * Add the given @a queue to our internal data structure.  Setup the
1498  * MQ processing and inform transport that the queue is ready.  Must
1499  * be called after the KX for outgoing messages has been bootstrapped.
1500  *
1501  * @param queue queue to boot
1502  */
1503 static void
1504 boot_queue (struct Queue *queue, enum GNUNET_TRANSPORT_ConnectionStatus cs)
1505 {
1506   queue->nt =
1507     GNUNET_NT_scanner_get_type (is, queue->address, queue->address_len);
1508   (void) GNUNET_CONTAINER_multipeermap_put (
1509     queue_map,
1510     &queue->target,
1511     queue,
1512     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1513   GNUNET_STATISTICS_set (stats,
1514                          "# queues active",
1515                          GNUNET_CONTAINER_multipeermap_size (queue_map),
1516                          GNUNET_NO);
1517   queue->timeout =
1518     GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1519   queue->mq = GNUNET_MQ_queue_for_callbacks (&mq_send,
1520                                              &mq_destroy,
1521                                              &mq_cancel,
1522                                              queue,
1523                                              NULL,
1524                                              &mq_error,
1525                                              queue);
1526   {
1527     char *foreign_addr;
1528
1529     switch (queue->address->sa_family)
1530     {
1531     case AF_INET:
1532       GNUNET_asprintf (&foreign_addr,
1533                        "%s-%s",
1534                        COMMUNICATOR_ADDRESS_PREFIX,
1535                        GNUNET_a2s (queue->address, queue->address_len));
1536       break;
1537
1538     case AF_INET6:
1539       GNUNET_asprintf (&foreign_addr,
1540                        "%s-%s",
1541                        COMMUNICATOR_ADDRESS_PREFIX,
1542                        GNUNET_a2s (queue->address, queue->address_len));
1543       break;
1544
1545     default:
1546       GNUNET_assert (0);
1547     }
1548     queue->qh = GNUNET_TRANSPORT_communicator_mq_add (ch,
1549                                                       &queue->target,
1550                                                       foreign_addr,
1551                                                       0 /* no MTU */,
1552                                                       queue->nt,
1553                                                       cs,
1554                                                       queue->mq);
1555     GNUNET_free (foreign_addr);
1556   }
1557 }
1558
1559
1560 /**
1561  * Generate and transmit our ephemeral key and the signature for
1562  * the initial KX with the other peer.  Must be called first, before
1563  * any other bytes are ever written to the output buffer.  Note that
1564  * our cipher must already be initialized when calling this function.
1565  * Helper function for #start_initial_kx_out().
1566  *
1567  * @param queue queue to do KX for
1568  * @param epub our public key for the KX
1569  */
1570 static void
1571 transmit_kx (struct Queue *queue,
1572              const struct GNUNET_CRYPTO_EcdhePublicKey *epub)
1573 {
1574   struct TcpHandshakeSignature ths;
1575   struct TCPConfirmation tc;
1576
1577   memcpy (queue->cwrite_buf, epub, sizeof(*epub));
1578   queue->cwrite_off = sizeof(*epub);
1579   /* compute 'tc' and append in encrypted format to cwrite_buf */
1580   tc.sender = my_identity;
1581   tc.monotonic_time =
1582     GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
1583   ths.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE);
1584   ths.purpose.size = htonl (sizeof(ths));
1585   ths.sender = my_identity;
1586   ths.receiver = queue->target;
1587   ths.ephemeral = *epub;
1588   ths.monotonic_time = tc.monotonic_time;
1589   GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_private_key,
1590                                                         &ths.purpose,
1591                                                         &tc.sender_sig));
1592   GNUNET_assert (0 ==
1593                  gcry_cipher_encrypt (queue->out_cipher,
1594                                       &queue->cwrite_buf[queue->cwrite_off],
1595                                       sizeof(tc),
1596                                       &tc,
1597                                       sizeof(tc)));
1598   queue->cwrite_off += sizeof(tc);
1599 }
1600
1601
1602 /**
1603  * Initialize our key material for outgoing transmissions and
1604  * inform the other peer about it. Must be called first before
1605  * any data is sent.
1606  *
1607  * @param queue the queue to setup
1608  */
1609 static void
1610 start_initial_kx_out (struct Queue *queue)
1611 {
1612   struct GNUNET_CRYPTO_EcdhePublicKey epub;
1613
1614   GNUNET_assert (GNUNET_OK ==
1615                  GNUNET_CRYPTO_ecdhe_key_create2 (&queue->ephemeral));
1616   GNUNET_CRYPTO_ecdhe_key_get_public (&queue->ephemeral, &epub);
1617   setup_out_cipher (queue);
1618   transmit_kx (queue, &epub);
1619 }
1620
1621
1622 /**
1623  * We have received the first bytes from the other side on a @a queue.
1624  * Decrypt the @a tc contained in @a ibuf and check the signature.
1625  * Note that #setup_in_cipher() must have already been called.
1626  *
1627  * @param queue queue to decrypt initial bytes from other peer for
1628  * @param tc[out] where to store the result
1629  * @param ibuf incoming data, of size
1630  *        `INITIAL_KX_SIZE`
1631  * @return #GNUNET_OK if the signature was OK, #GNUNET_SYSERR if not
1632  */
1633 static int
1634 decrypt_and_check_tc (struct Queue *queue,
1635                       struct TCPConfirmation *tc,
1636                       char *ibuf)
1637 {
1638   struct TcpHandshakeSignature ths;
1639
1640   GNUNET_assert (
1641     0 ==
1642     gcry_cipher_decrypt (queue->in_cipher,
1643                          tc,
1644                          sizeof(*tc),
1645                          &ibuf[sizeof(struct GNUNET_CRYPTO_EcdhePublicKey)],
1646                          sizeof(*tc)));
1647   ths.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE);
1648   ths.purpose.size = htonl (sizeof(ths));
1649   ths.sender = tc->sender;
1650   ths.receiver = my_identity;
1651   memcpy (&ths.ephemeral, ibuf, sizeof(struct GNUNET_CRYPTO_EcdhePublicKey));
1652   ths.monotonic_time = tc->monotonic_time;
1653   /* FIXME: check monotonic time against previous mono times
1654      from this sender! */
1655   return GNUNET_CRYPTO_eddsa_verify (
1656     GNUNET_SIGNATURE_COMMUNICATOR_TCP_HANDSHAKE,
1657     &ths.purpose,
1658     &tc->sender_sig,
1659     &tc->sender.public_key);
1660 }
1661
1662
1663 /**
1664  * Closes socket and frees memory associated with @a pq.
1665  *
1666  * @param pq proto queue to free
1667  */
1668 static void
1669 free_proto_queue (struct ProtoQueue *pq)
1670 {
1671   GNUNET_NETWORK_socket_close (pq->sock);
1672   GNUNET_free (pq->address);
1673   GNUNET_CONTAINER_DLL_remove (proto_head, proto_tail, pq);
1674   GNUNET_free (pq);
1675 }
1676
1677
1678 /**
1679  * Read from the socket of the proto queue until we have enough data
1680  * to upgrade to full queue.
1681  *
1682  * @param cls a `struct ProtoQueue`
1683  */
1684 static void
1685 proto_read_kx (void *cls)
1686 {
1687   struct ProtoQueue *pq = cls;
1688   ssize_t rcvd;
1689   struct GNUNET_TIME_Relative left;
1690   struct Queue *queue;
1691   struct TCPConfirmation tc;
1692
1693   pq->read_task = NULL;
1694   left = GNUNET_TIME_absolute_get_remaining (pq->timeout);
1695   if (0 == left.rel_value_us)
1696   {
1697     free_proto_queue (pq);
1698     return;
1699   }
1700   rcvd = GNUNET_NETWORK_socket_recv (pq->sock,
1701                                      &pq->ibuf[pq->ibuf_off],
1702                                      sizeof(pq->ibuf) - pq->ibuf_off);
1703   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1704               "Received %lu bytes for KX\n", rcvd);
1705   if (-1 == rcvd)
1706   {
1707     if ((EAGAIN != errno) && (EINTR != errno))
1708     {
1709       GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "recv");
1710       free_proto_queue (pq);
1711       return;
1712     }
1713     /* try again */
1714     pq->read_task =
1715       GNUNET_SCHEDULER_add_read_net (left, pq->sock, &proto_read_kx, pq);
1716     return;
1717   }
1718   pq->ibuf_off += rcvd;
1719   if (pq->ibuf_off > sizeof(pq->ibuf))
1720   {
1721     /* read more */
1722     pq->read_task =
1723       GNUNET_SCHEDULER_add_read_net (left, pq->sock, &proto_read_kx, pq);
1724     return;
1725   }
1726   /* we got all the data, let's find out who we are talking to! */
1727   queue = GNUNET_new (struct Queue);
1728   setup_in_cipher ((const struct GNUNET_CRYPTO_EcdhePublicKey *) pq->ibuf,
1729                    queue);
1730   if (GNUNET_OK != decrypt_and_check_tc (queue, &tc, pq->ibuf))
1731   {
1732     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1733                 "Invalid TCP KX received from %s\n",
1734                 GNUNET_a2s (queue->address, queue->address_len));
1735     gcry_cipher_close (queue->in_cipher);
1736     GNUNET_free (queue);
1737     free_proto_queue (pq);
1738     return;
1739   }
1740   queue->address = pq->address; /* steals reference */
1741   queue->address_len = pq->address_len;
1742   queue->target = tc.sender;
1743   queue->sock = pq->sock;
1744   start_initial_kx_out (queue);
1745   boot_queue (queue, GNUNET_TRANSPORT_CS_INBOUND);
1746   queue->read_task =
1747     GNUNET_SCHEDULER_add_read_net (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1748                                    queue->sock,
1749                                    &queue_read,
1750                                    queue);
1751   queue->write_task =
1752     GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1753                                     queue->sock,
1754                                     &queue_write,
1755                                     queue);
1756   GNUNET_CONTAINER_DLL_remove (proto_head, proto_tail, pq);
1757   GNUNET_free (pq);
1758 }
1759
1760
1761 /**
1762  * We have been notified that our listen socket has something to
1763  * read. Do the read and reschedule this function to be called again
1764  * once more is available.
1765  *
1766  * @param cls NULL
1767  */
1768 static void
1769 listen_cb (void *cls)
1770 {
1771   struct sockaddr_storage in;
1772   socklen_t addrlen;
1773   struct GNUNET_NETWORK_Handle *sock;
1774   struct ProtoQueue *pq;
1775
1776   listen_task = NULL;
1777   GNUNET_assert (NULL != listen_sock);
1778   addrlen = sizeof(in);
1779   memset (&in, 0, sizeof(in));
1780   sock = GNUNET_NETWORK_socket_accept (listen_sock,
1781                                        (struct sockaddr*) &in,
1782                                        &addrlen);
1783   if ((NULL == sock) && ((EMFILE == errno) || (ENFILE == errno)))
1784     return; /* system limit reached, wait until connection goes down */
1785   listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1786                                                listen_sock,
1787                                                &listen_cb,
1788                                                NULL);
1789   if ((NULL == sock) && ((EAGAIN == errno) || (ENOBUFS == errno)))
1790     return;
1791   if (NULL == sock)
1792   {
1793     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "accept");
1794     return;
1795   }
1796   pq = GNUNET_new (struct ProtoQueue);
1797   pq->address_len = addrlen;
1798   pq->address = GNUNET_memdup (&in, addrlen);
1799   pq->timeout = GNUNET_TIME_relative_to_absolute (PROTO_QUEUE_TIMEOUT);
1800   pq->sock = sock;
1801   pq->read_task = GNUNET_SCHEDULER_add_read_net (PROTO_QUEUE_TIMEOUT,
1802                                                  pq->sock,
1803                                                  &proto_read_kx,
1804                                                  pq);
1805   GNUNET_CONTAINER_DLL_insert (proto_head, proto_tail, pq);
1806 }
1807
1808
1809 /**
1810  * Read from the socket of the queue until we have enough data
1811  * to initialize the decryption logic and can switch to regular
1812  * reading.
1813  *
1814  * @param cls a `struct Queue`
1815  */
1816 static void
1817 queue_read_kx (void *cls)
1818 {
1819   struct Queue *queue = cls;
1820   ssize_t rcvd;
1821   struct GNUNET_TIME_Relative left;
1822   struct TCPConfirmation tc;
1823
1824   queue->read_task = NULL;
1825   left = GNUNET_TIME_absolute_get_remaining (queue->timeout);
1826   if (0 == left.rel_value_us)
1827   {
1828     queue_destroy (queue);
1829     return;
1830   }
1831   rcvd = GNUNET_NETWORK_socket_recv (queue->sock,
1832                                      &queue->cread_buf[queue->cread_off],
1833                                      BUF_SIZE - queue->cread_off);
1834   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received %lu bytes for KX\n", rcvd);
1835   if (-1 == rcvd)
1836   {
1837     if ((EAGAIN != errno) && (EINTR != errno))
1838     {
1839       GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "recv");
1840       queue_destroy (queue);
1841       return;
1842     }
1843     queue->read_task =
1844       GNUNET_SCHEDULER_add_read_net (left, queue->sock, &queue_read_kx, queue);
1845     return;
1846   }
1847   queue->cread_off += rcvd;
1848   if (queue->cread_off < INITIAL_KX_SIZE)
1849   {
1850     /* read more */
1851     queue->read_task =
1852       GNUNET_SCHEDULER_add_read_net (left, queue->sock, &queue_read_kx, queue);
1853     return;
1854   }
1855   /* we got all the data, let's find out who we are talking to! */
1856   setup_in_cipher ((const struct GNUNET_CRYPTO_EcdhePublicKey *)
1857                    queue->cread_buf,
1858                    queue);
1859   if (GNUNET_OK != decrypt_and_check_tc (queue, &tc, queue->cread_buf))
1860   {
1861     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1862                 "Invalid TCP KX received from %s\n",
1863                 GNUNET_a2s (queue->address, queue->address_len));
1864     queue_destroy (queue);
1865     return;
1866   }
1867   if (0 !=
1868       memcmp (&tc.sender, &queue->target, sizeof(struct GNUNET_PeerIdentity)))
1869   {
1870     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1871                 "Invalid sender in TCP KX received from %s\n",
1872                 GNUNET_a2s (queue->address, queue->address_len));
1873     queue_destroy (queue);
1874     return;
1875   }
1876
1877   /* update queue timeout */
1878   reschedule_queue_timeout (queue);
1879   /* prepare to continue with regular read task immediately */
1880   memmove (queue->cread_buf,
1881            &queue->cread_buf[INITIAL_KX_SIZE],
1882            queue->cread_off - (INITIAL_KX_SIZE));
1883   queue->cread_off -= INITIAL_KX_SIZE;
1884   if (0 < queue->cread_off)
1885     queue->read_task = GNUNET_SCHEDULER_add_now (&queue_read, queue);
1886 }
1887
1888
1889 /**
1890  * Function called by the transport service to initialize a
1891  * message queue given address information about another peer.
1892  * If and when the communication channel is established, the
1893  * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
1894  * to notify the service that the channel is now up.  It is
1895  * the responsibility of the communicator to manage sane
1896  * retries and timeouts for any @a peer/@a address combination
1897  * provided by the transport service.  Timeouts and retries
1898  * do not need to be signalled to the transport service.
1899  *
1900  * @param cls closure
1901  * @param peer identity of the other peer
1902  * @param address where to send the message, human-readable
1903  *        communicator-specific format, 0-terminated, UTF-8
1904  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is
1905  * invalid
1906  */
1907 static int
1908 mq_init (void *cls, const struct GNUNET_PeerIdentity *peer, const char *address)
1909 {
1910   struct Queue *queue;
1911   const char *path;
1912   struct sockaddr *in;
1913   socklen_t in_len;
1914   struct GNUNET_NETWORK_Handle *sock;
1915
1916   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1917               "Connecting to %s\n", address);
1918   if (0 != strncmp (address,
1919                     COMMUNICATOR_ADDRESS_PREFIX "-",
1920                     strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
1921   {
1922     GNUNET_break_op (0);
1923     return GNUNET_SYSERR;
1924   }
1925   path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
1926   in = tcp_address_to_sockaddr (path, &in_len);
1927
1928   sock = GNUNET_NETWORK_socket_create (in->sa_family, SOCK_STREAM, IPPROTO_TCP);
1929   if (NULL == sock)
1930   {
1931     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1932                 "socket(%d) failed: %s",
1933                 in->sa_family,
1934                 strerror (errno));
1935     GNUNET_free (in);
1936     return GNUNET_SYSERR;
1937   }
1938   if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (sock, in, in_len)) &&
1939       (errno != EINPROGRESS))
1940   {
1941     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1942                 "connect to `%s' failed: %s",
1943                 address,
1944                 strerror (errno));
1945     GNUNET_NETWORK_socket_close (sock);
1946     GNUNET_free (in);
1947     return GNUNET_SYSERR;
1948   }
1949
1950   queue = GNUNET_new (struct Queue);
1951   queue->target = *peer;
1952   queue->address = in;
1953   queue->address_len = in_len;
1954   queue->sock = sock;
1955   boot_queue (queue, GNUNET_TRANSPORT_CS_OUTBOUND);
1956   //queue->mq_awaits_continue = GNUNET_YES;
1957   queue->read_task =
1958     GNUNET_SCHEDULER_add_read_net (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1959                                    queue->sock,
1960                                    &queue_read_kx,
1961                                    queue);
1962   start_initial_kx_out (queue);
1963   queue->write_task =
1964     GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL,
1965                                     queue->sock,
1966                                     &queue_write,
1967                                     queue);
1968   return GNUNET_OK;
1969 }
1970
1971
1972 /**
1973  * Iterator over all message queues to clean up.
1974  *
1975  * @param cls NULL
1976  * @param target unused
1977  * @param value the queue to destroy
1978  * @return #GNUNET_OK to continue to iterate
1979  */
1980 static int
1981 get_queue_delete_it (void *cls,
1982                      const struct GNUNET_PeerIdentity *target,
1983                      void *value)
1984 {
1985   struct Queue *queue = value;
1986
1987   (void) cls;
1988   (void) target;
1989   queue_destroy (queue);
1990   return GNUNET_OK;
1991 }
1992
1993
1994 /**
1995  * Shutdown the UNIX communicator.
1996  *
1997  * @param cls NULL (always)
1998  */
1999 static void
2000 do_shutdown (void *cls)
2001 {
2002   while (NULL != proto_head)
2003     free_proto_queue (proto_head);
2004   if (NULL != nat)
2005   {
2006     GNUNET_NAT_unregister (nat);
2007     nat = NULL;
2008   }
2009   if (NULL != listen_task)
2010   {
2011     GNUNET_SCHEDULER_cancel (listen_task);
2012     listen_task = NULL;
2013   }
2014   if (NULL != listen_sock)
2015   {
2016     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (listen_sock));
2017     listen_sock = NULL;
2018   }
2019   GNUNET_CONTAINER_multipeermap_iterate (queue_map, &get_queue_delete_it, NULL);
2020   GNUNET_CONTAINER_multipeermap_destroy (queue_map);
2021   if (NULL != ch)
2022   {
2023     GNUNET_TRANSPORT_communicator_disconnect (ch);
2024     ch = NULL;
2025   }
2026   if (NULL != stats)
2027   {
2028     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
2029     stats = NULL;
2030   }
2031   if (NULL != my_private_key)
2032   {
2033     GNUNET_free (my_private_key);
2034     my_private_key = NULL;
2035   }
2036   if (NULL != is)
2037   {
2038     GNUNET_NT_scanner_done (is);
2039     is = NULL;
2040   }
2041 }
2042
2043
2044 /**
2045  * Function called when the transport service has received an
2046  * acknowledgement for this communicator (!) via a different return
2047  * path.
2048  *
2049  * Not applicable for TCP.
2050  *
2051  * @param cls closure
2052  * @param sender which peer sent the notification
2053  * @param msg payload
2054  */
2055 static void
2056 enc_notify_cb (void *cls,
2057                const struct GNUNET_PeerIdentity *sender,
2058                const struct GNUNET_MessageHeader *msg)
2059 {
2060   (void) cls;
2061   (void) sender;
2062   (void) msg;
2063   GNUNET_break_op (0);
2064 }
2065
2066
2067 /**
2068  * Signature of the callback passed to #GNUNET_NAT_register() for
2069  * a function to call whenever our set of 'valid' addresses changes.
2070  *
2071  * @param cls closure
2072  * @param app_ctx[in,out] location where the app can store stuff
2073  *                  on add and retrieve it on remove
2074  * @param add_remove #GNUNET_YES to add a new public IP address,
2075  *                   #GNUNET_NO to remove a previous (now invalid) one
2076  * @param ac address class the address belongs to
2077  * @param addr either the previous or the new public IP address
2078  * @param addrlen actual length of the @a addr
2079  */
2080 static void
2081 nat_address_cb (void *cls,
2082                 void **app_ctx,
2083                 int add_remove,
2084                 enum GNUNET_NAT_AddressClass ac,
2085                 const struct sockaddr *addr,
2086                 socklen_t addrlen)
2087 {
2088   char *my_addr;
2089   struct GNUNET_TRANSPORT_AddressIdentifier *ai;
2090
2091   if (GNUNET_YES == add_remove)
2092   {
2093     enum GNUNET_NetworkType nt;
2094
2095     GNUNET_asprintf (&my_addr,
2096                      "%s-%s",
2097                      COMMUNICATOR_ADDRESS_PREFIX,
2098                      GNUNET_a2s (addr, addrlen));
2099     nt = GNUNET_NT_scanner_get_type (is, addr, addrlen);
2100     ai =
2101       GNUNET_TRANSPORT_communicator_address_add (ch,
2102                                                  my_addr,
2103                                                  nt,
2104                                                  GNUNET_TIME_UNIT_FOREVER_REL);
2105     GNUNET_free (my_addr);
2106     *app_ctx = ai;
2107   }
2108   else
2109   {
2110     ai = *app_ctx;
2111     GNUNET_TRANSPORT_communicator_address_remove (ai);
2112     *app_ctx = NULL;
2113   }
2114 }
2115
2116
2117 /**
2118  * Setup communicator and launch network interactions.
2119  *
2120  * @param cls NULL (always)
2121  * @param args remaining command-line arguments
2122  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
2123  * @param c configuration
2124  */
2125 static void
2126 run (void *cls,
2127      char *const *args,
2128      const char *cfgfile,
2129      const struct GNUNET_CONFIGURATION_Handle *c)
2130 {
2131   char *bindto;
2132   struct sockaddr *in;
2133   socklen_t in_len;
2134   struct sockaddr_storage in_sto;
2135   socklen_t sto_len;
2136
2137   (void) cls;
2138   cfg = c;
2139   if (GNUNET_OK !=
2140       GNUNET_CONFIGURATION_get_value_string (cfg,
2141                                              COMMUNICATOR_CONFIG_SECTION,
2142                                              "BINDTO",
2143                                              &bindto))
2144   {
2145     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2146                                COMMUNICATOR_CONFIG_SECTION,
2147                                "BINDTO");
2148     return;
2149   }
2150   if (GNUNET_OK !=
2151       GNUNET_CONFIGURATION_get_value_number (cfg,
2152                                              COMMUNICATOR_CONFIG_SECTION,
2153                                              "MAX_QUEUE_LENGTH",
2154                                              &max_queue_length))
2155     max_queue_length = DEFAULT_MAX_QUEUE_LENGTH;
2156   if (GNUNET_OK !=
2157       GNUNET_CONFIGURATION_get_value_time (cfg,
2158                                              COMMUNICATOR_CONFIG_SECTION,
2159                                              "REKEY_INTERVAL",
2160                                              &rekey_interval))
2161     rekey_interval = DEFAULT_REKEY_INTERVAL;
2162
2163   in = tcp_address_to_sockaddr (bindto, &in_len);
2164   if (NULL == in)
2165   {
2166     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2167                 "Failed to setup TCP socket address with path `%s'\n",
2168                 bindto);
2169     GNUNET_free (bindto);
2170     return;
2171   }
2172   listen_sock =
2173     GNUNET_NETWORK_socket_create (in->sa_family, SOCK_STREAM, IPPROTO_TCP);
2174   if (NULL == listen_sock)
2175   {
2176     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
2177     GNUNET_free (in);
2178     GNUNET_free (bindto);
2179     return;
2180   }
2181   if (GNUNET_OK != GNUNET_NETWORK_socket_bind (listen_sock, in, in_len))
2182   {
2183     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "bind", bindto);
2184     GNUNET_NETWORK_socket_close (listen_sock);
2185     listen_sock = NULL;
2186     GNUNET_free (in);
2187     GNUNET_free (bindto);
2188     return;
2189   }
2190   if (GNUNET_OK !=
2191       GNUNET_NETWORK_socket_listen (listen_sock,
2192                                     5))
2193   {
2194     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
2195                          "listen");
2196     GNUNET_NETWORK_socket_close (listen_sock);
2197     listen_sock = NULL;
2198     GNUNET_free (in);
2199     GNUNET_free (bindto);
2200   }
2201   /* We might have bound to port 0, allowing the OS to figure it out;
2202      thus, get the real IN-address from the socket */
2203   sto_len = sizeof(in_sto);
2204   if (0 != getsockname (GNUNET_NETWORK_get_fd (listen_sock),
2205                         (struct sockaddr *) &in_sto,
2206                         &sto_len))
2207   {
2208     memcpy (&in_sto, in, in_len);
2209     sto_len = in_len;
2210   }
2211   GNUNET_free (in);
2212   GNUNET_free (bindto);
2213   in = (struct sockaddr *) &in_sto;
2214   in_len = sto_len;
2215   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2216               "Bound to `%s'\n",
2217               GNUNET_a2s ((const struct sockaddr *) &in_sto, sto_len));
2218   stats = GNUNET_STATISTICS_create ("C-TCP", cfg);
2219   GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
2220   is = GNUNET_NT_scanner_init ();
2221   my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
2222   if (NULL == my_private_key)
2223   {
2224     GNUNET_log (
2225       GNUNET_ERROR_TYPE_ERROR,
2226       _ (
2227         "Transport service is lacking key configuration settings. Exiting.\n"));
2228     GNUNET_SCHEDULER_shutdown ();
2229     return;
2230   }
2231   GNUNET_CRYPTO_eddsa_key_get_public (my_private_key, &my_identity.public_key);
2232   /* start listening */
2233   listen_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
2234                                                listen_sock,
2235                                                &listen_cb,
2236                                                NULL);
2237   queue_map = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
2238   ch = GNUNET_TRANSPORT_communicator_connect (cfg,
2239                                               COMMUNICATOR_CONFIG_SECTION,
2240                                               COMMUNICATOR_ADDRESS_PREFIX,
2241                                               GNUNET_TRANSPORT_CC_RELIABLE,
2242                                               &mq_init,
2243                                               NULL,
2244                                               &enc_notify_cb,
2245                                               NULL);
2246   if (NULL == ch)
2247   {
2248     GNUNET_break (0);
2249     GNUNET_SCHEDULER_shutdown ();
2250     return;
2251   }
2252   nat = GNUNET_NAT_register (cfg,
2253                              COMMUNICATOR_CONFIG_SECTION,
2254                              IPPROTO_TCP,
2255                              1 /* one address */,
2256                              (const struct sockaddr **) &in,
2257                              &in_len,
2258                              &nat_address_cb,
2259                              NULL /* FIXME: support reversal: #5529 */,
2260                              NULL /* closure */);
2261 }
2262
2263
2264 /**
2265  * The main function for the UNIX communicator.
2266  *
2267  * @param argc number of arguments from the command line
2268  * @param argv command line arguments
2269  * @return 0 ok, 1 on error
2270  */
2271 int
2272 main (int argc, char *const *argv)
2273 {
2274   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
2275     GNUNET_GETOPT_OPTION_END
2276   };
2277   int ret;
2278
2279   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
2280     return 2;
2281
2282   ret = (GNUNET_OK == GNUNET_PROGRAM_run (argc,
2283                                           argv,
2284                                           "gnunet-communicator-tcp",
2285                                           _ ("GNUnet TCP communicator"),
2286                                           options,
2287                                           &run,
2288                                           NULL))
2289     ? 0
2290     : 1;
2291   GNUNET_free ((void *) argv);
2292   return ret;
2293 }
2294
2295
2296 /* end of gnunet-communicator-tcp.c */