gnunet-communicator-tcp.c 59 KB

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