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