gnunet-communicator-tcp.c 77 KB

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