gnunet-communicator-udp.c 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908
  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-udp.c
  18. * @brief Transport plugin using UDP.
  19. * @author Christian Grothoff
  20. *
  21. * TODO:
  22. * - consider imposing transmission limits in the absence
  23. * of ACKs; or: maybe this should be done at TNG service level?
  24. * (at least the receiver might want to enforce limits on
  25. * KX/DH operations per sender in here) (#5552)
  26. * - overall, we should look more into flow control support
  27. * (either in backchannel, or general solution in TNG service)
  28. * - handle addresses discovered from broadcasts (#5551)
  29. * (think: what was the story again on address validation?
  30. * where is the API for that!?!)
  31. * - support DNS names in BINDTO option (#5528)
  32. * - support NAT connection reversal method (#5529)
  33. * - support other UDP-specific NAT traversal methods (#)
  34. */
  35. #include "platform.h"
  36. #include "gnunet_util_lib.h"
  37. #include "gnunet_protocols.h"
  38. #include "gnunet_signatures.h"
  39. #include "gnunet_constants.h"
  40. #include "gnunet_nt_lib.h"
  41. #include "gnunet_nat_service.h"
  42. #include "gnunet_statistics_service.h"
  43. #include "gnunet_transport_application_service.h"
  44. #include "gnunet_transport_communication_service.h"
  45. /**
  46. * How often do we rekey based on time (at least)
  47. */
  48. #define REKEY_TIME_INTERVAL GNUNET_TIME_UNIT_DAYS
  49. /**
  50. * How long do we wait until we must have received the initial KX?
  51. */
  52. #define PROTO_QUEUE_TIMEOUT GNUNET_TIME_UNIT_MINUTES
  53. /**
  54. * How often do we broadcast our presence on the LAN?
  55. */
  56. #define BROADCAST_FREQUENCY GNUNET_TIME_UNIT_MINUTES
  57. /**
  58. * How often do we scan for changes to our network interfaces?
  59. */
  60. #define INTERFACE_SCAN_FREQUENCY \
  61. GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
  62. /**
  63. * How long do we believe our addresses to remain up (before
  64. * the other peer should revalidate).
  65. */
  66. #define ADDRESS_VALIDITY_PERIOD GNUNET_TIME_UNIT_HOURS
  67. /**
  68. * AES key size.
  69. */
  70. #define AES_KEY_SIZE (256 / 8)
  71. /**
  72. * AES (GCM) IV size.
  73. */
  74. #define AES_IV_SIZE (96 / 8)
  75. /**
  76. * Size of the GCM tag.
  77. */
  78. #define GCM_TAG_SIZE (128 / 8)
  79. /**
  80. * If we fall below this number of available KCNs,
  81. * we generate additional ACKs until we reach
  82. * #KCN_TARGET.
  83. * Should be large enough that we don't generate ACKs all
  84. * the time and still have enough time for the ACK to
  85. * arrive before the sender runs out. So really this
  86. * should ideally be based on the RTT.
  87. */
  88. #define KCN_THRESHOLD 92
  89. /**
  90. * How many KCNs do we keep around *after* we hit
  91. * the #KCN_THRESHOLD? Should be larger than
  92. * #KCN_THRESHOLD so we do not generate just one
  93. * ACK at the time.
  94. */
  95. #define KCN_TARGET 128
  96. /**
  97. * What is the maximum delta between KCN sequence numbers
  98. * that we allow. Used to expire 'ancient' KCNs that likely
  99. * were dropped by the network. Must be larger than
  100. * KCN_TARGET (otherwise we generate new KCNs all the time),
  101. * but not too large (otherwise packet loss may cause
  102. * sender to fall back to KX needlessly when sender runs
  103. * out of ACK'ed KCNs due to losses).
  104. */
  105. #define MAX_SQN_DELTA 160
  106. /**
  107. * How many shared master secrets do we keep around
  108. * at most per sender? Should be large enough so
  109. * that we generally have a chance of sending an ACK
  110. * before the sender already rotated out the master
  111. * secret. Generally values around #KCN_TARGET make
  112. * sense. Might make sense to adapt to RTT if we had
  113. * a good measurement...
  114. */
  115. #define MAX_SECRETS 128
  116. /**
  117. * How often do we rekey based on number of bytes transmitted?
  118. * (additionally randomized).
  119. */
  120. #define REKEY_MAX_BYTES (1024LLU * 1024 * 1024 * 4LLU)
  121. /**
  122. * Address prefix used by the communicator.
  123. */
  124. #define COMMUNICATOR_ADDRESS_PREFIX "udp"
  125. /**
  126. * Configuration section used by the communicator.
  127. */
  128. #define COMMUNICATOR_CONFIG_SECTION "communicator-udp"
  129. GNUNET_NETWORK_STRUCT_BEGIN
  130. /**
  131. * Signature we use to verify that the ephemeral key was really chosen by
  132. * the specified sender. If possible, the receiver should respond with
  133. * a `struct UDPAck` (possibly via backchannel).
  134. */
  135. struct UdpHandshakeSignature
  136. {
  137. /**
  138. * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
  139. */
  140. struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
  141. /**
  142. * Identity of the inititor of the UDP connection (UDP client).
  143. */
  144. struct GNUNET_PeerIdentity sender;
  145. /**
  146. * Presumed identity of the target of the UDP connection (UDP server)
  147. */
  148. struct GNUNET_PeerIdentity receiver;
  149. /**
  150. * Ephemeral key used by the @e sender.
  151. */
  152. struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
  153. /**
  154. * Monotonic time of @e sender, to possibly help detect replay attacks
  155. * (if receiver persists times by sender).
  156. */
  157. struct GNUNET_TIME_AbsoluteNBO monotonic_time;
  158. };
  159. /**
  160. * "Plaintext" header at beginning of KX message. Followed
  161. * by encrypted `struct UDPConfirmation`.
  162. */
  163. struct InitialKX
  164. {
  165. /**
  166. * Ephemeral key for KX.
  167. */
  168. struct GNUNET_CRYPTO_EcdhePublicKey ephemeral;
  169. /**
  170. * HMAC for the following encrypted message, using GCM. HMAC uses
  171. * key derived from the handshake with sequence number zero.
  172. */
  173. char gcm_tag[GCM_TAG_SIZE];
  174. };
  175. /**
  176. * Encrypted continuation of UDP initial handshake, followed
  177. * by message header with payload.
  178. */
  179. struct UDPConfirmation
  180. {
  181. /**
  182. * Sender's identity
  183. */
  184. struct GNUNET_PeerIdentity sender;
  185. /**
  186. * Sender's signature of type #GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE
  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. /* followed by messages */
  195. /* padding may follow actual messages */
  196. };
  197. /**
  198. * UDP key acknowledgement. May be sent via backchannel. Allows the
  199. * sender to use `struct UDPBox` with the acknowledge key henceforth.
  200. */
  201. struct UDPAck
  202. {
  203. /**
  204. * Type is #GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK.
  205. */
  206. struct GNUNET_MessageHeader header;
  207. /**
  208. * Sequence acknowledgement limit. Specifies current maximum sequence
  209. * number supported by receiver.
  210. */
  211. uint32_t sequence_max GNUNET_PACKED;
  212. /**
  213. * CMAC of the base key being acknowledged.
  214. */
  215. struct GNUNET_HashCode cmac;
  216. };
  217. /**
  218. * Signature we use to verify that the broadcast was really made by
  219. * the peer that claims to have made it. Basically, affirms that the
  220. * peer is really using this IP address (albeit possibly not in _our_
  221. * LAN). Makes it difficult for peers in the LAN to claim to
  222. * be just any global peer -- an attacker must have at least
  223. * shared a LAN with the peer they're pretending to be here.
  224. */
  225. struct UdpBroadcastSignature
  226. {
  227. /**
  228. * Purpose must be #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
  229. */
  230. struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
  231. /**
  232. * Identity of the inititor of the UDP broadcast.
  233. */
  234. struct GNUNET_PeerIdentity sender;
  235. /**
  236. * Hash of the sender's UDP address.
  237. */
  238. struct GNUNET_HashCode h_address;
  239. };
  240. /**
  241. * Broadcast by peer in LAN announcing its presence. Unusual in that
  242. * we don't pad these to full MTU, as we cannot prevent being
  243. * recognized in LAN as GNUnet peers if this feature is enabled
  244. * anyway. Also, the entire message is in cleartext.
  245. */
  246. struct UDPBroadcast
  247. {
  248. /**
  249. * Sender's peer identity.
  250. */
  251. struct GNUNET_PeerIdentity sender;
  252. /**
  253. * Sender's signature of type
  254. * #GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST
  255. */
  256. struct GNUNET_CRYPTO_EddsaSignature sender_sig;
  257. };
  258. /**
  259. * UDP message box. Always sent encrypted, only allowed after
  260. * the receiver sent a `struct UDPAck` for the base key!
  261. */
  262. struct UDPBox
  263. {
  264. /**
  265. * Key and IV identification code. KDF applied to an acknowledged
  266. * base key and a sequence number. Sequence numbers must be used
  267. * monotonically increasing up to the maximum specified in
  268. * `struct UDPAck`. Without further `struct UDPAck`s, the sender
  269. * must fall back to sending handshakes!
  270. */
  271. struct GNUNET_ShortHashCode kid;
  272. /**
  273. * 128-bit authentication tag for the following encrypted message,
  274. * from GCM. MAC starts at the @e body_start that follows and
  275. * extends until the end of the UDP payload. If the @e hmac is
  276. * wrong, the receiver should check if the message might be a
  277. * `struct UdpHandshakeSignature`.
  278. */
  279. char gcm_tag[GCM_TAG_SIZE];
  280. };
  281. GNUNET_NETWORK_STRUCT_END
  282. /**
  283. * Shared secret we generated for a particular sender or receiver.
  284. */
  285. struct SharedSecret;
  286. /**
  287. * Pre-generated "kid" code (key and IV identification code) to
  288. * quickly derive master key for a `struct UDPBox`.
  289. */
  290. struct KeyCacheEntry
  291. {
  292. /**
  293. * Kept in a DLL.
  294. */
  295. struct KeyCacheEntry *next;
  296. /**
  297. * Kept in a DLL.
  298. */
  299. struct KeyCacheEntry *prev;
  300. /**
  301. * Key and IV identification code. KDF applied to an acknowledged
  302. * base key and a sequence number. Sequence numbers must be used
  303. * monotonically increasing up to the maximum specified in
  304. * `struct UDPAck`. Without further `struct UDPAck`s, the sender
  305. * must fall back to sending handshakes!
  306. */
  307. struct GNUNET_ShortHashCode kid;
  308. /**
  309. * Corresponding shared secret.
  310. */
  311. struct SharedSecret *ss;
  312. /**
  313. * Sequence number used to derive this entry from master key.
  314. */
  315. uint32_t sequence_number;
  316. };
  317. /**
  318. * Information we track per sender address we have recently been
  319. * in contact with (decryption from sender).
  320. */
  321. struct SenderAddress;
  322. /**
  323. * Information we track per receiving address we have recently been
  324. * in contact with (encryption to receiver).
  325. */
  326. struct ReceiverAddress;
  327. /**
  328. * Shared secret we generated for a particular sender or receiver.
  329. */
  330. struct SharedSecret
  331. {
  332. /**
  333. * Kept in a DLL.
  334. */
  335. struct SharedSecret *next;
  336. /**
  337. * Kept in a DLL.
  338. */
  339. struct SharedSecret *prev;
  340. /**
  341. * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
  342. */
  343. struct KeyCacheEntry *kce_head;
  344. /**
  345. * Kept in a DLL, sorted by sequence number. Only if we are decrypting.
  346. */
  347. struct KeyCacheEntry *kce_tail;
  348. /**
  349. * Sender we use this shared secret with, or NULL.
  350. */
  351. struct SenderAddress *sender;
  352. /**
  353. * Receiver we use this shared secret with, or NULL.
  354. */
  355. struct ReceiverAddress *receiver;
  356. /**
  357. * Master shared secret.
  358. */
  359. struct GNUNET_HashCode master;
  360. /**
  361. * CMAC is used to identify @e master in ACKs.
  362. */
  363. struct GNUNET_HashCode cmac;
  364. /**
  365. * Up to which sequence number did we use this @e master already?
  366. * (for encrypting only)
  367. */
  368. uint32_t sequence_used;
  369. /**
  370. * Up to which sequence number did the other peer allow us to use
  371. * this key, or up to which number did we allow the other peer to
  372. * use this key?
  373. */
  374. uint32_t sequence_allowed;
  375. /**
  376. * Number of active KCN entries.
  377. */
  378. unsigned int active_kce_count;
  379. };
  380. /**
  381. * Information we track per sender address we have recently been
  382. * in contact with (we decrypt messages from the sender).
  383. */
  384. struct SenderAddress
  385. {
  386. /**
  387. * To whom are we talking to.
  388. */
  389. struct GNUNET_PeerIdentity target;
  390. /**
  391. * Entry in sender expiration heap.
  392. */
  393. struct GNUNET_CONTAINER_HeapNode *hn;
  394. /**
  395. * Shared secrets we used with @e target, first used is head.
  396. */
  397. struct SharedSecret *ss_head;
  398. /**
  399. * Shared secrets we used with @e target, last used is tail.
  400. */
  401. struct SharedSecret *ss_tail;
  402. /**
  403. * Address of the other peer.
  404. */
  405. struct sockaddr *address;
  406. /**
  407. * Length of the address.
  408. */
  409. socklen_t address_len;
  410. /**
  411. * Timeout for this sender.
  412. */
  413. struct GNUNET_TIME_Absolute timeout;
  414. /**
  415. * Length of the DLL at @a ss_head.
  416. */
  417. unsigned int num_secrets;
  418. /**
  419. * Which network type does this queue use?
  420. */
  421. enum GNUNET_NetworkType nt;
  422. };
  423. /**
  424. * Information we track per receiving address we have recently been
  425. * in contact with (encryption to receiver).
  426. */
  427. struct ReceiverAddress
  428. {
  429. /**
  430. * To whom are we talking to.
  431. */
  432. struct GNUNET_PeerIdentity target;
  433. /**
  434. * Shared secrets we received from @e target, first used is head.
  435. */
  436. struct SharedSecret *ss_head;
  437. /**
  438. * Shared secrets we received with @e target, last used is tail.
  439. */
  440. struct SharedSecret *ss_tail;
  441. /**
  442. * Address of the receiver in the human-readable format
  443. * with the #COMMUNICATOR_ADDRESS_PREFIX.
  444. */
  445. char *foreign_addr;
  446. /**
  447. * Address of the other peer.
  448. */
  449. struct sockaddr *address;
  450. /**
  451. * Length of the address.
  452. */
  453. socklen_t address_len;
  454. /**
  455. * Entry in sender expiration heap.
  456. */
  457. struct GNUNET_CONTAINER_HeapNode *hn;
  458. /**
  459. * KX message queue we are providing for the #ch.
  460. */
  461. struct GNUNET_MQ_Handle *kx_mq;
  462. /**
  463. * Default message queue we are providing for the #ch.
  464. */
  465. struct GNUNET_MQ_Handle *d_mq;
  466. /**
  467. * handle for KX queue with the #ch.
  468. */
  469. struct GNUNET_TRANSPORT_QueueHandle *kx_qh;
  470. /**
  471. * handle for default queue with the #ch.
  472. */
  473. struct GNUNET_TRANSPORT_QueueHandle *d_qh;
  474. /**
  475. * Timeout for this receiver address.
  476. */
  477. struct GNUNET_TIME_Absolute timeout;
  478. /**
  479. * MTU we allowed transport for this receiver's KX queue.
  480. */
  481. size_t kx_mtu;
  482. /**
  483. * MTU we allowed transport for this receiver's default queue.
  484. */
  485. size_t d_mtu;
  486. /**
  487. * Length of the DLL at @a ss_head.
  488. */
  489. unsigned int num_secrets;
  490. /**
  491. * Number of BOX keys from ACKs we have currently
  492. * available for this receiver.
  493. */
  494. unsigned int acks_available;
  495. /**
  496. * Which network type does this queue use?
  497. */
  498. enum GNUNET_NetworkType nt;
  499. };
  500. /**
  501. * Interface we broadcast our presence on.
  502. */
  503. struct BroadcastInterface
  504. {
  505. /**
  506. * Kept in a DLL.
  507. */
  508. struct BroadcastInterface *next;
  509. /**
  510. * Kept in a DLL.
  511. */
  512. struct BroadcastInterface *prev;
  513. /**
  514. * Task for this broadcast interface.
  515. */
  516. struct GNUNET_SCHEDULER_Task *broadcast_task;
  517. /**
  518. * Sender's address of the interface.
  519. */
  520. struct sockaddr *sa;
  521. /**
  522. * Broadcast address to use on the interface.
  523. */
  524. struct sockaddr *ba;
  525. /**
  526. * Message we broadcast on this interface.
  527. */
  528. struct UDPBroadcast bcm;
  529. /**
  530. * If this is an IPv6 interface, this is the request
  531. * we use to join/leave the group.
  532. */
  533. struct ipv6_mreq mcreq;
  534. /**
  535. * Number of bytes in @e sa.
  536. */
  537. socklen_t salen;
  538. /**
  539. * Was this interface found in the last #iface_proc() scan?
  540. */
  541. int found;
  542. };
  543. /**
  544. * Cache of pre-generated key IDs.
  545. */
  546. static struct GNUNET_CONTAINER_MultiShortmap *key_cache;
  547. /**
  548. * ID of read task
  549. */
  550. static struct GNUNET_SCHEDULER_Task *read_task;
  551. /**
  552. * ID of timeout task
  553. */
  554. static struct GNUNET_SCHEDULER_Task *timeout_task;
  555. /**
  556. * ID of master broadcast task
  557. */
  558. static struct GNUNET_SCHEDULER_Task *broadcast_task;
  559. /**
  560. * For logging statistics.
  561. */
  562. static struct GNUNET_STATISTICS_Handle *stats;
  563. /**
  564. * Our environment.
  565. */
  566. static struct GNUNET_TRANSPORT_CommunicatorHandle *ch;
  567. /**
  568. * Receivers (map from peer identity to `struct ReceiverAddress`)
  569. */
  570. static struct GNUNET_CONTAINER_MultiPeerMap *receivers;
  571. /**
  572. * Senders (map from peer identity to `struct SenderAddress`)
  573. */
  574. static struct GNUNET_CONTAINER_MultiPeerMap *senders;
  575. /**
  576. * Expiration heap for senders (contains `struct SenderAddress`)
  577. */
  578. static struct GNUNET_CONTAINER_Heap *senders_heap;
  579. /**
  580. * Expiration heap for receivers (contains `struct ReceiverAddress`)
  581. */
  582. static struct GNUNET_CONTAINER_Heap *receivers_heap;
  583. /**
  584. * Broadcast interface tasks. Kept in a DLL.
  585. */
  586. static struct BroadcastInterface *bi_head;
  587. /**
  588. * Broadcast interface tasks. Kept in a DLL.
  589. */
  590. static struct BroadcastInterface *bi_tail;
  591. /**
  592. * Our socket.
  593. */
  594. static struct GNUNET_NETWORK_Handle *udp_sock;
  595. /**
  596. * #GNUNET_YES if #udp_sock supports IPv6.
  597. */
  598. static int have_v6_socket;
  599. /**
  600. * Our public key.
  601. */
  602. static struct GNUNET_PeerIdentity my_identity;
  603. /**
  604. * Our private key.
  605. */
  606. static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
  607. /**
  608. * Our configuration.
  609. */
  610. static const struct GNUNET_CONFIGURATION_Handle *cfg;
  611. /**
  612. * Our handle to report addresses for validation to TRANSPORT.
  613. */
  614. static struct GNUNET_TRANSPORT_ApplicationHandle *ah;
  615. /**
  616. * Network scanner to determine network types.
  617. */
  618. static struct GNUNET_NT_InterfaceScanner *is;
  619. /**
  620. * Connection to NAT service.
  621. */
  622. static struct GNUNET_NAT_Handle *nat;
  623. /**
  624. * Port number to which we are actually bound.
  625. */
  626. static uint16_t my_port;
  627. /**
  628. * An interface went away, stop broadcasting on it.
  629. *
  630. * @param bi entity to close down
  631. */
  632. static void
  633. bi_destroy (struct BroadcastInterface *bi)
  634. {
  635. if (AF_INET6 == bi->sa->sa_family)
  636. {
  637. /* Leave the multicast group */
  638. if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt (udp_sock,
  639. IPPROTO_IPV6,
  640. IPV6_LEAVE_GROUP,
  641. &bi->mcreq,
  642. sizeof(bi->mcreq)))
  643. {
  644. GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
  645. }
  646. }
  647. GNUNET_CONTAINER_DLL_remove (bi_head, bi_tail, bi);
  648. GNUNET_SCHEDULER_cancel (bi->broadcast_task);
  649. GNUNET_free (bi->sa);
  650. GNUNET_free_non_null (bi->ba);
  651. GNUNET_free (bi);
  652. }
  653. /**
  654. * Destroys a receiving state due to timeout or shutdown.
  655. *
  656. * @param receiver entity to close down
  657. */
  658. static void
  659. receiver_destroy (struct ReceiverAddress *receiver)
  660. {
  661. struct GNUNET_MQ_Handle *mq;
  662. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  663. "Disconnecting receiver for peer `%s'\n",
  664. GNUNET_i2s (&receiver->target));
  665. if (NULL != (mq = receiver->kx_mq))
  666. {
  667. receiver->kx_mq = NULL;
  668. GNUNET_MQ_destroy (mq);
  669. }
  670. if (NULL != receiver->kx_qh)
  671. {
  672. GNUNET_TRANSPORT_communicator_mq_del (receiver->kx_qh);
  673. receiver->kx_qh = NULL;
  674. }
  675. if (NULL != (mq = receiver->d_mq))
  676. {
  677. receiver->d_mq = NULL;
  678. GNUNET_MQ_destroy (mq);
  679. }
  680. if (NULL != receiver->d_qh)
  681. {
  682. GNUNET_TRANSPORT_communicator_mq_del (receiver->d_qh);
  683. receiver->d_qh = NULL;
  684. }
  685. GNUNET_assert (GNUNET_YES ==
  686. GNUNET_CONTAINER_multipeermap_remove (receivers,
  687. &receiver->target,
  688. receiver));
  689. GNUNET_assert (receiver == GNUNET_CONTAINER_heap_remove_node (receiver->hn));
  690. GNUNET_STATISTICS_set (stats,
  691. "# receivers active",
  692. GNUNET_CONTAINER_multipeermap_size (receivers),
  693. GNUNET_NO);
  694. GNUNET_free (receiver->address);
  695. GNUNET_free (receiver->foreign_addr);
  696. GNUNET_free (receiver);
  697. }
  698. /**
  699. * Free memory used by key cache entry.
  700. *
  701. * @param kce the key cache entry
  702. */
  703. static void
  704. kce_destroy (struct KeyCacheEntry *kce)
  705. {
  706. struct SharedSecret *ss = kce->ss;
  707. ss->active_kce_count--;
  708. GNUNET_CONTAINER_DLL_remove (ss->kce_head, ss->kce_tail, kce);
  709. GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multishortmap_remove (key_cache,
  710. &kce->kid,
  711. kce));
  712. GNUNET_free (kce);
  713. }
  714. /**
  715. * Compute @a kid.
  716. *
  717. * @param msec master secret for HMAC calculation
  718. * @param serial number for the @a smac calculation
  719. * @param kid[out] where to write the key ID
  720. */
  721. static void
  722. get_kid (const struct GNUNET_HashCode *msec,
  723. uint32_t serial,
  724. struct GNUNET_ShortHashCode *kid)
  725. {
  726. uint32_t sid = htonl (serial);
  727. GNUNET_CRYPTO_hkdf (kid,
  728. sizeof(*kid),
  729. GCRY_MD_SHA512,
  730. GCRY_MD_SHA256,
  731. &sid,
  732. sizeof(sid),
  733. msec,
  734. sizeof(*msec),
  735. "UDP-KID",
  736. strlen ("UDP-KID"),
  737. NULL,
  738. 0);
  739. }
  740. /**
  741. * Setup key cache entry for sequence number @a seq and shared secret @a ss.
  742. *
  743. * @param ss shared secret
  744. * @param seq sequence number for the key cache entry
  745. */
  746. static void
  747. kce_generate (struct SharedSecret *ss, uint32_t seq)
  748. {
  749. struct KeyCacheEntry *kce;
  750. GNUNET_assert (0 < seq);
  751. kce = GNUNET_new (struct KeyCacheEntry);
  752. kce->ss = ss;
  753. kce->sequence_number = seq;
  754. get_kid (&ss->master, seq, &kce->kid);
  755. GNUNET_CONTAINER_DLL_insert (ss->kce_head, ss->kce_tail, kce);
  756. ss->active_kce_count++;
  757. (void) GNUNET_CONTAINER_multishortmap_put (
  758. key_cache,
  759. &kce->kid,
  760. kce,
  761. GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
  762. GNUNET_STATISTICS_set (stats,
  763. "# KIDs active",
  764. GNUNET_CONTAINER_multishortmap_size (key_cache),
  765. GNUNET_NO);
  766. }
  767. /**
  768. * Destroy @a ss and associated key cache entries.
  769. *
  770. * @param ss shared secret to destroy
  771. */
  772. static void
  773. secret_destroy (struct SharedSecret *ss)
  774. {
  775. struct SenderAddress *sender;
  776. struct ReceiverAddress *receiver;
  777. struct KeyCacheEntry *kce;
  778. if (NULL != (sender = ss->sender))
  779. {
  780. GNUNET_CONTAINER_DLL_remove (sender->ss_head, sender->ss_tail, ss);
  781. sender->num_secrets--;
  782. }
  783. if (NULL != (receiver = ss->receiver))
  784. {
  785. GNUNET_CONTAINER_DLL_remove (receiver->ss_head, receiver->ss_tail, ss);
  786. receiver->num_secrets--;
  787. receiver->acks_available -= (ss->sequence_allowed - ss->sequence_used);
  788. }
  789. while (NULL != (kce = ss->kce_head))
  790. kce_destroy (kce);
  791. GNUNET_STATISTICS_update (stats, "# Secrets active", -1, GNUNET_NO);
  792. GNUNET_STATISTICS_set (stats,
  793. "# KIDs active",
  794. GNUNET_CONTAINER_multishortmap_size (key_cache),
  795. GNUNET_NO);
  796. GNUNET_free (ss);
  797. }
  798. /**
  799. * Functions with this signature are called whenever we need
  800. * to close a sender's state due to timeout.
  801. *
  802. * @param sender entity to close down
  803. */
  804. static void
  805. sender_destroy (struct SenderAddress *sender)
  806. {
  807. GNUNET_assert (
  808. GNUNET_YES ==
  809. GNUNET_CONTAINER_multipeermap_remove (senders, &sender->target, sender));
  810. GNUNET_assert (sender == GNUNET_CONTAINER_heap_remove_node (sender->hn));
  811. GNUNET_STATISTICS_set (stats,
  812. "# senders active",
  813. GNUNET_CONTAINER_multipeermap_size (senders),
  814. GNUNET_NO);
  815. GNUNET_free (sender->address);
  816. GNUNET_free (sender);
  817. }
  818. /**
  819. * Compute @a key and @a iv.
  820. *
  821. * @param msec master secret for calculation
  822. * @param serial number for the @a smac calculation
  823. * @param key[out] where to write the decrption key
  824. * @param iv[out] where to write the IV
  825. */
  826. static void
  827. get_iv_key (const struct GNUNET_HashCode *msec,
  828. uint32_t serial,
  829. char key[AES_KEY_SIZE],
  830. char iv[AES_IV_SIZE])
  831. {
  832. uint32_t sid = htonl (serial);
  833. char res[AES_KEY_SIZE + AES_IV_SIZE];
  834. GNUNET_CRYPTO_hkdf (res,
  835. sizeof(res),
  836. GCRY_MD_SHA512,
  837. GCRY_MD_SHA256,
  838. &sid,
  839. sizeof(sid),
  840. msec,
  841. sizeof(*msec),
  842. "UDP-IV-KEY",
  843. strlen ("UDP-IV-KEY"),
  844. NULL,
  845. 0);
  846. memcpy (key, res, AES_KEY_SIZE);
  847. memcpy (iv, &res[AES_KEY_SIZE], AES_IV_SIZE);
  848. }
  849. /**
  850. * Increment sender timeout due to activity.
  851. *
  852. * @param sender address for which the timeout should be rescheduled
  853. */
  854. static void
  855. reschedule_sender_timeout (struct SenderAddress *sender)
  856. {
  857. sender->timeout =
  858. GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
  859. GNUNET_CONTAINER_heap_update_cost (sender->hn, sender->timeout.abs_value_us);
  860. }
  861. /**
  862. * Increment receiver timeout due to activity.
  863. *
  864. * @param receiver address for which the timeout should be rescheduled
  865. */
  866. static void
  867. reschedule_receiver_timeout (struct ReceiverAddress *receiver)
  868. {
  869. receiver->timeout =
  870. GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
  871. GNUNET_CONTAINER_heap_update_cost (receiver->hn,
  872. receiver->timeout.abs_value_us);
  873. }
  874. /**
  875. * Task run to check #receiver_heap and #sender_heap for timeouts.
  876. *
  877. * @param cls unused, NULL
  878. */
  879. static void
  880. check_timeouts (void *cls)
  881. {
  882. struct GNUNET_TIME_Relative st;
  883. struct GNUNET_TIME_Relative rt;
  884. struct GNUNET_TIME_Relative delay;
  885. struct ReceiverAddress *receiver;
  886. struct SenderAddress *sender;
  887. (void) cls;
  888. timeout_task = NULL;
  889. rt = GNUNET_TIME_UNIT_FOREVER_REL;
  890. while (NULL != (receiver = GNUNET_CONTAINER_heap_peek (receivers_heap)))
  891. {
  892. rt = GNUNET_TIME_absolute_get_remaining (receiver->timeout);
  893. if (0 != rt.rel_value_us)
  894. break;
  895. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  896. "Receiver timed out\n");
  897. receiver_destroy (receiver);
  898. }
  899. st = GNUNET_TIME_UNIT_FOREVER_REL;
  900. while (NULL != (sender = GNUNET_CONTAINER_heap_peek (senders_heap)))
  901. {
  902. st = GNUNET_TIME_absolute_get_remaining (sender->timeout);
  903. if (0 != st.rel_value_us)
  904. break;
  905. sender_destroy (sender);
  906. }
  907. delay = GNUNET_TIME_relative_min (rt, st);
  908. if (delay.rel_value_us < GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
  909. timeout_task = GNUNET_SCHEDULER_add_delayed (delay, &check_timeouts, NULL);
  910. }
  911. /**
  912. * Calcualte cmac from master in @a ss.
  913. *
  914. * @param ss[in,out] data structure to complete
  915. */
  916. static void
  917. calculate_cmac (struct SharedSecret *ss)
  918. {
  919. GNUNET_CRYPTO_hkdf (&ss->cmac,
  920. sizeof(ss->cmac),
  921. GCRY_MD_SHA512,
  922. GCRY_MD_SHA256,
  923. "CMAC",
  924. strlen ("CMAC"),
  925. &ss->master,
  926. sizeof(ss->master),
  927. "UDP-CMAC",
  928. strlen ("UDP-CMAC"),
  929. NULL,
  930. 0);
  931. }
  932. /**
  933. * We received @a plaintext_len bytes of @a plaintext from a @a sender.
  934. * Pass it on to CORE.
  935. *
  936. * @param queue the queue that received the plaintext
  937. * @param plaintext the plaintext that was received
  938. * @param plaintext_len number of bytes of plaintext received
  939. */
  940. static void
  941. pass_plaintext_to_core (struct SenderAddress *sender,
  942. const void *plaintext,
  943. size_t plaintext_len)
  944. {
  945. const struct GNUNET_MessageHeader *hdr = plaintext;
  946. const char *pos = plaintext;
  947. while (ntohs (hdr->size) < plaintext_len)
  948. {
  949. GNUNET_STATISTICS_update (stats,
  950. "# bytes given to core",
  951. ntohs (hdr->size),
  952. GNUNET_NO);
  953. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  954. "Giving %u bytes to TNG\n", ntohs (hdr->size));
  955. GNUNET_assert (GNUNET_SYSERR !=
  956. GNUNET_TRANSPORT_communicator_receive (ch,
  957. &sender->target,
  958. hdr,
  959. ADDRESS_VALIDITY_PERIOD,
  960. NULL /* no flow control possible */
  961. ,
  962. NULL));
  963. /* move on to next message, if any */
  964. plaintext_len -= ntohs (hdr->size);
  965. if (plaintext_len < sizeof(*hdr))
  966. break;
  967. pos += ntohs (hdr->size);
  968. hdr = (const struct GNUNET_MessageHeader *) pos;
  969. // TODO for now..., we do not actually sen >1msg or have a way of telling
  970. // if we are done
  971. break;
  972. }
  973. GNUNET_STATISTICS_update (stats,
  974. "# bytes padding discarded",
  975. plaintext_len,
  976. GNUNET_NO);
  977. }
  978. /**
  979. * Setup @a cipher based on shared secret @a msec and
  980. * serial number @a serial.
  981. *
  982. * @param msec master shared secret
  983. * @param serial serial number of cipher to set up
  984. * @param cipher[out] cipher to initialize
  985. */
  986. static void
  987. setup_cipher (const struct GNUNET_HashCode *msec,
  988. uint32_t serial,
  989. gcry_cipher_hd_t *cipher)
  990. {
  991. char key[AES_KEY_SIZE];
  992. char iv[AES_IV_SIZE];
  993. int rc;
  994. GNUNET_assert (0 ==
  995. gcry_cipher_open (cipher,
  996. GCRY_CIPHER_AES256 /* low level: go for speed */,
  997. GCRY_CIPHER_MODE_GCM,
  998. 0 /* flags */));
  999. get_iv_key (msec, serial, key, iv);
  1000. rc = gcry_cipher_setkey (*cipher, key, sizeof(key));
  1001. GNUNET_assert ((0 == rc) || ((char) rc == GPG_ERR_WEAK_KEY));
  1002. rc = gcry_cipher_setiv (*cipher, iv, sizeof(iv));
  1003. GNUNET_assert ((0 == rc) || ((char) rc == GPG_ERR_WEAK_KEY));
  1004. }
  1005. /**
  1006. * Try to decrypt @a buf using shared secret @a ss and key/iv
  1007. * derived using @a serial.
  1008. *
  1009. * @param ss shared secret
  1010. * @param tag GCM authentication tag
  1011. * @param serial serial number to use
  1012. * @param in_buf input buffer to decrypt
  1013. * @param in_buf_size number of bytes in @a in_buf and available in @a out_buf
  1014. * @param out_buf where to write the result
  1015. * @return #GNUNET_OK on success
  1016. */
  1017. static int
  1018. try_decrypt (const struct SharedSecret *ss,
  1019. const char tag[GCM_TAG_SIZE],
  1020. uint32_t serial,
  1021. const char *in_buf,
  1022. size_t in_buf_size,
  1023. char *out_buf)
  1024. {
  1025. gcry_cipher_hd_t cipher;
  1026. setup_cipher (&ss->master, serial, &cipher);
  1027. GNUNET_assert (
  1028. 0 ==
  1029. gcry_cipher_decrypt (cipher, out_buf, in_buf_size, in_buf, in_buf_size));
  1030. if (0 != gcry_cipher_checktag (cipher, tag, GCM_TAG_SIZE))
  1031. {
  1032. gcry_cipher_close (cipher);
  1033. GNUNET_STATISTICS_update (stats,
  1034. "# AEAD authentication failures",
  1035. 1,
  1036. GNUNET_NO);
  1037. return GNUNET_SYSERR;
  1038. }
  1039. gcry_cipher_close (cipher);
  1040. return GNUNET_OK;
  1041. }
  1042. /**
  1043. * Setup shared secret for decryption.
  1044. *
  1045. * @param ephemeral ephemeral key we received from the other peer
  1046. * @return new shared secret
  1047. */
  1048. static struct SharedSecret *
  1049. setup_shared_secret_dec (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral)
  1050. {
  1051. struct SharedSecret *ss;
  1052. ss = GNUNET_new (struct SharedSecret);
  1053. GNUNET_CRYPTO_eddsa_ecdh (my_private_key, ephemeral, &ss->master);
  1054. return ss;
  1055. }
  1056. /**
  1057. * Setup shared secret for encryption.
  1058. *
  1059. * @param ephemeral ephemeral key we are sending to the other peer
  1060. * @param receiver[in,out] queue to initialize encryption key for
  1061. * @return new shared secret
  1062. */
  1063. static struct SharedSecret *
  1064. setup_shared_secret_enc (const struct GNUNET_CRYPTO_EcdhePrivateKey *ephemeral,
  1065. struct ReceiverAddress *receiver)
  1066. {
  1067. struct SharedSecret *ss;
  1068. ss = GNUNET_new (struct SharedSecret);
  1069. GNUNET_CRYPTO_ecdh_eddsa (ephemeral,
  1070. &receiver->target.public_key,
  1071. &ss->master);
  1072. calculate_cmac (ss);
  1073. ss->receiver = receiver;
  1074. GNUNET_CONTAINER_DLL_insert (receiver->ss_head, receiver->ss_tail, ss);
  1075. receiver->num_secrets++;
  1076. GNUNET_STATISTICS_update (stats, "# Secrets active", 1, GNUNET_NO);
  1077. return ss;
  1078. }
  1079. /**
  1080. * Setup the MQ for the @a receiver. If a queue exists,
  1081. * the existing one is destroyed. Then the MTU is
  1082. * recalculated and a fresh queue is initialized.
  1083. *
  1084. * @param receiver receiver to setup MQ for
  1085. */
  1086. static void
  1087. setup_receiver_mq (struct ReceiverAddress *receiver);
  1088. /**
  1089. * We received an ACK for @a pid. Check if it is for
  1090. * the receiver in @a value and if so, handle it and
  1091. * return #GNUNET_NO. Otherwise, return #GNUNET_YES.
  1092. *
  1093. * @param cls a `const struct UDPAck`
  1094. * @param pid peer the ACK is from
  1095. * @param value a `struct ReceiverAddress`
  1096. * @return #GNUNET_YES to continue to iterate
  1097. */
  1098. static int
  1099. handle_ack (void *cls, const struct GNUNET_PeerIdentity *pid, void *value)
  1100. {
  1101. const struct UDPAck *ack = cls;
  1102. struct ReceiverAddress *receiver = value;
  1103. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  1104. "in handle ack\n");
  1105. (void) pid;
  1106. for (struct SharedSecret *ss = receiver->ss_head; NULL != ss; ss = ss->next)
  1107. {
  1108. if (0 == memcmp (&ack->cmac, &ss->cmac, sizeof(struct GNUNET_HashCode)))
  1109. {
  1110. uint32_t allowed;
  1111. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  1112. "Found matching mac\n");
  1113. allowed = ntohl (ack->sequence_max);
  1114. if (allowed > ss->sequence_allowed)
  1115. {
  1116. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  1117. "%u > %u (%u)\n", allowed, ss->sequence_allowed,
  1118. receiver->acks_available);
  1119. receiver->acks_available += (allowed - ss->sequence_allowed);
  1120. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  1121. "Tell transport we have more acks!\n");
  1122. GNUNET_TRANSPORT_communicator_mq_update (ch,
  1123. receiver->d_qh,
  1124. (allowed - ss->sequence_allowed),
  1125. 1);
  1126. ss->sequence_allowed = allowed;
  1127. /* move ss to head to avoid discarding it anytime soon! */
  1128. GNUNET_CONTAINER_DLL_remove (receiver->ss_head, receiver->ss_tail, ss);
  1129. GNUNET_CONTAINER_DLL_insert (receiver->ss_head, receiver->ss_tail, ss);
  1130. }
  1131. return GNUNET_NO;
  1132. }
  1133. }
  1134. return GNUNET_YES;
  1135. }
  1136. /**
  1137. * Test if we have received a valid message in plaintext.
  1138. * If so, handle it.
  1139. *
  1140. * @param sender peer to process inbound plaintext for
  1141. * @param buf buffer we received
  1142. * @param buf_size number of bytes in @a buf
  1143. */
  1144. static void
  1145. try_handle_plaintext (struct SenderAddress *sender,
  1146. const void *buf,
  1147. size_t buf_size)
  1148. {
  1149. const struct GNUNET_MessageHeader *hdr =
  1150. (const struct GNUNET_MessageHeader *) buf;
  1151. const struct UDPAck *ack = (const struct UDPAck *) buf;
  1152. uint16_t type;
  1153. if (sizeof(*hdr) > buf_size)
  1154. return; /* not even a header */
  1155. if (ntohs (hdr->size) > buf_size)
  1156. return; /* not even a header */
  1157. type = ntohs (hdr->type);
  1158. switch (type)
  1159. {
  1160. case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK:
  1161. /* lookup master secret by 'cmac', then update sequence_max */
  1162. GNUNET_CONTAINER_multipeermap_get_multiple (receivers,
  1163. &sender->target,
  1164. &handle_ack,
  1165. (void *) ack);
  1166. /* There could be more messages after the ACK, handle those as well */
  1167. buf += ntohs (hdr->size);
  1168. buf_size -= ntohs (hdr->size);
  1169. pass_plaintext_to_core (sender, buf, buf_size);
  1170. break;
  1171. case GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD:
  1172. /* skip padding */
  1173. break;
  1174. default:
  1175. pass_plaintext_to_core (sender, buf, buf_size);
  1176. }
  1177. }
  1178. /**
  1179. * We established a shared secret with a sender. We should try to send
  1180. * the sender an `struct UDPAck` at the next opportunity to allow the
  1181. * sender to use @a ss longer (assuming we did not yet already
  1182. * recently).
  1183. *
  1184. * @param ss shared secret to generate ACKs for
  1185. */
  1186. static void
  1187. consider_ss_ack (struct SharedSecret *ss)
  1188. {
  1189. GNUNET_assert (NULL != ss->sender);
  1190. /* drop ancient KeyCacheEntries */
  1191. while ((NULL != ss->kce_head) &&
  1192. (MAX_SQN_DELTA <
  1193. ss->kce_head->sequence_number - ss->kce_tail->sequence_number))
  1194. kce_destroy (ss->kce_tail);
  1195. if (ss->active_kce_count < KCN_THRESHOLD)
  1196. {
  1197. struct UDPAck ack;
  1198. while (ss->active_kce_count < KCN_TARGET)
  1199. kce_generate (ss, ++ss->sequence_allowed);
  1200. ack.header.type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK);
  1201. ack.header.size = htons (sizeof(ack));
  1202. ack.sequence_max = htonl (ss->sequence_allowed);
  1203. ack.cmac = ss->cmac;
  1204. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  1205. "Notifying transport of UDPAck %s\n",
  1206. GNUNET_i2s_full (&ss->sender->target));
  1207. GNUNET_TRANSPORT_communicator_notify (ch,
  1208. &ss->sender->target,
  1209. COMMUNICATOR_ADDRESS_PREFIX,
  1210. &ack.header);
  1211. }
  1212. }
  1213. /**
  1214. * We received a @a box with matching @a kce. Decrypt and process it.
  1215. *
  1216. * @param box the data we received
  1217. * @param box_len number of bytes in @a box
  1218. * @param kce key index to decrypt @a box
  1219. */
  1220. static void
  1221. decrypt_box (const struct UDPBox *box,
  1222. size_t box_len,
  1223. struct KeyCacheEntry *kce)
  1224. {
  1225. struct SharedSecret *ss = kce->ss;
  1226. char out_buf[box_len - sizeof(*box)];
  1227. GNUNET_assert (NULL != ss->sender);
  1228. if (GNUNET_OK != try_decrypt (ss,
  1229. box->gcm_tag,
  1230. kce->sequence_number,
  1231. (const char *) &box[1],
  1232. sizeof(out_buf),
  1233. out_buf))
  1234. {
  1235. GNUNET_STATISTICS_update (stats,
  1236. "# Decryption failures with valid KCE",
  1237. 1,
  1238. GNUNET_NO);
  1239. kce_destroy (kce);
  1240. return;
  1241. }
  1242. kce_destroy (kce);
  1243. GNUNET_STATISTICS_update (stats,
  1244. "# bytes decrypted with BOX",
  1245. sizeof(out_buf),
  1246. GNUNET_NO);
  1247. try_handle_plaintext (ss->sender, out_buf, sizeof(out_buf));
  1248. consider_ss_ack (ss);
  1249. }
  1250. /**
  1251. * Closure for #find_sender_by_address()
  1252. */
  1253. struct SearchContext
  1254. {
  1255. /**
  1256. * Address we are looking for.
  1257. */
  1258. const struct sockaddr *address;
  1259. /**
  1260. * Number of bytes in @e address.
  1261. */
  1262. socklen_t address_len;
  1263. /**
  1264. * Return value to set if we found a match.
  1265. */
  1266. struct SenderAddress *sender;
  1267. };
  1268. /**
  1269. * Find existing `struct SenderAddress` by matching addresses.
  1270. *
  1271. * @param cls a `struct SearchContext`
  1272. * @param key ignored, must match already
  1273. * @param value a `struct SenderAddress`
  1274. * @return #GNUNET_YES if not found (continue to search), #GNUNET_NO if found
  1275. */
  1276. static int
  1277. find_sender_by_address (void *cls,
  1278. const struct GNUNET_PeerIdentity *key,
  1279. void *value)
  1280. {
  1281. struct SearchContext *sc = cls;
  1282. struct SenderAddress *sender = value;
  1283. if ((sender->address_len == sc->address_len) &&
  1284. (0 == memcmp (sender->address, sc->address, sender->address_len)))
  1285. {
  1286. sc->sender = sender;
  1287. return GNUNET_NO; /* stop iterating! */
  1288. }
  1289. return GNUNET_YES;
  1290. }
  1291. /**
  1292. * Create sender address for @a target. Note that we
  1293. * might already have one, so a fresh one is only allocated
  1294. * if one does not yet exist for @a address.
  1295. *
  1296. * @param target peer to generate address for
  1297. * @param address target address
  1298. * @param address_len number of bytes in @a address
  1299. * @return data structure to keep track of key material for
  1300. * decrypting data from @a target
  1301. */
  1302. static struct SenderAddress *
  1303. setup_sender (const struct GNUNET_PeerIdentity *target,
  1304. const struct sockaddr *address,
  1305. socklen_t address_len)
  1306. {
  1307. struct SenderAddress *sender;
  1308. struct SearchContext sc = { .address = address,
  1309. .address_len = address_len,
  1310. .sender = NULL };
  1311. GNUNET_CONTAINER_multipeermap_get_multiple (senders,
  1312. target,
  1313. &find_sender_by_address,
  1314. &sc);
  1315. if (NULL != sc.sender)
  1316. {
  1317. reschedule_sender_timeout (sc.sender);
  1318. return sc.sender;
  1319. }
  1320. sender = GNUNET_new (struct SenderAddress);
  1321. sender->target = *target;
  1322. sender->address = GNUNET_memdup (address, address_len);
  1323. sender->address_len = address_len;
  1324. (void) GNUNET_CONTAINER_multipeermap_put (
  1325. senders,
  1326. &sender->target,
  1327. sender,
  1328. GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
  1329. GNUNET_STATISTICS_set (stats,
  1330. "# senders active",
  1331. GNUNET_CONTAINER_multipeermap_size (receivers),
  1332. GNUNET_NO);
  1333. sender->timeout =
  1334. GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
  1335. sender->hn = GNUNET_CONTAINER_heap_insert (senders_heap,
  1336. sender,
  1337. sender->timeout.abs_value_us);
  1338. sender->nt = GNUNET_NT_scanner_get_type (is, address, address_len);
  1339. if (NULL == timeout_task)
  1340. timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts, NULL);
  1341. return sender;
  1342. }
  1343. /**
  1344. * Check signature from @a uc against @a ephemeral.
  1345. *
  1346. * @param ephermal key that is signed
  1347. * @param uc signature of claimant
  1348. * @return #GNUNET_OK if signature is valid
  1349. */
  1350. static int
  1351. verify_confirmation (const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral,
  1352. const struct UDPConfirmation *uc)
  1353. {
  1354. struct UdpHandshakeSignature uhs;
  1355. uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
  1356. uhs.purpose.size = htonl (sizeof(uhs));
  1357. uhs.sender = uc->sender;
  1358. uhs.receiver = my_identity;
  1359. uhs.ephemeral = *ephemeral;
  1360. uhs.monotonic_time = uc->monotonic_time;
  1361. return GNUNET_CRYPTO_eddsa_verify (
  1362. GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE,
  1363. &uhs,
  1364. &uc->sender_sig,
  1365. &uc->sender.public_key);
  1366. }
  1367. /**
  1368. * Converts @a address to the address string format used by this
  1369. * communicator in HELLOs.
  1370. *
  1371. * @param address the address to convert, must be AF_INET or AF_INET6.
  1372. * @param address_len number of bytes in @a address
  1373. * @return string representation of @a address
  1374. */
  1375. static char *
  1376. sockaddr_to_udpaddr_string (const struct sockaddr *address,
  1377. socklen_t address_len)
  1378. {
  1379. char *ret;
  1380. switch (address->sa_family)
  1381. {
  1382. case AF_INET:
  1383. GNUNET_asprintf (&ret,
  1384. "%s-%s",
  1385. COMMUNICATOR_ADDRESS_PREFIX,
  1386. GNUNET_a2s (address, address_len));
  1387. break;
  1388. case AF_INET6:
  1389. GNUNET_asprintf (&ret,
  1390. "%s-%s",
  1391. COMMUNICATOR_ADDRESS_PREFIX,
  1392. GNUNET_a2s (address, address_len));
  1393. break;
  1394. default:
  1395. GNUNET_assert (0);
  1396. }
  1397. return ret;
  1398. }
  1399. /**
  1400. * Socket read task.
  1401. *
  1402. * @param cls NULL
  1403. */
  1404. static void
  1405. sock_read (void *cls)
  1406. {
  1407. struct sockaddr_storage sa;
  1408. socklen_t salen = sizeof(sa);
  1409. char buf[UINT16_MAX];
  1410. ssize_t rcvd;
  1411. (void) cls;
  1412. read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
  1413. udp_sock,
  1414. &sock_read,
  1415. NULL);
  1416. rcvd = GNUNET_NETWORK_socket_recvfrom (udp_sock,
  1417. buf,
  1418. sizeof(buf),
  1419. (struct sockaddr *) &sa,
  1420. &salen);
  1421. if (-1 == rcvd)
  1422. {
  1423. GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "recv");
  1424. return;
  1425. }
  1426. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  1427. "Read %lu bytes\n", rcvd);
  1428. /* first, see if it is a UDPBox */
  1429. if (rcvd > sizeof(struct UDPBox))
  1430. {
  1431. const struct UDPBox *box;
  1432. struct KeyCacheEntry *kce;
  1433. box = (const struct UDPBox *) buf;
  1434. kce = GNUNET_CONTAINER_multishortmap_get (key_cache, &box->kid);
  1435. if (NULL != kce)
  1436. {
  1437. decrypt_box (box, (size_t) rcvd, kce);
  1438. return;
  1439. }
  1440. }
  1441. /* next, check if it is a broadcast */
  1442. if (sizeof(struct UDPBroadcast) == rcvd)
  1443. {
  1444. const struct UDPBroadcast *ub;
  1445. struct UdpBroadcastSignature uhs;
  1446. ub = (const struct UDPBroadcast *) buf;
  1447. uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
  1448. uhs.purpose.size = htonl (sizeof(uhs));
  1449. uhs.sender = ub->sender;
  1450. GNUNET_CRYPTO_hash (&sa, salen, &uhs.h_address);
  1451. if (GNUNET_OK ==
  1452. GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST,
  1453. &uhs,
  1454. &ub->sender_sig,
  1455. &ub->sender.public_key))
  1456. {
  1457. char *addr_s;
  1458. enum GNUNET_NetworkType nt;
  1459. addr_s =
  1460. sockaddr_to_udpaddr_string ((const struct sockaddr *) &sa, salen);
  1461. GNUNET_STATISTICS_update (stats, "# broadcasts received", 1, GNUNET_NO);
  1462. /* use our own mechanism to determine network type */
  1463. nt =
  1464. GNUNET_NT_scanner_get_type (is, (const struct sockaddr *) &sa, salen);
  1465. GNUNET_TRANSPORT_application_validate (ah, &ub->sender, nt, addr_s);
  1466. GNUNET_free (addr_s);
  1467. return;
  1468. }
  1469. /* continue with KX, mostly for statistics... */
  1470. }
  1471. /* finally, test if it is a KX */
  1472. if (rcvd < sizeof(struct UDPConfirmation) + sizeof(struct InitialKX))
  1473. {
  1474. GNUNET_STATISTICS_update (stats,
  1475. "# messages dropped (no kid, too small for KX)",
  1476. 1,
  1477. GNUNET_NO);
  1478. return;
  1479. }
  1480. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  1481. "Got KX\n");
  1482. {
  1483. const struct InitialKX *kx;
  1484. struct SharedSecret *ss;
  1485. char pbuf[rcvd - sizeof(struct InitialKX)];
  1486. const struct UDPConfirmation *uc;
  1487. struct SenderAddress *sender;
  1488. kx = (const struct InitialKX *) buf;
  1489. ss = setup_shared_secret_dec (&kx->ephemeral);
  1490. if (GNUNET_OK != try_decrypt (ss,
  1491. kx->gcm_tag,
  1492. 0,
  1493. &buf[sizeof(*kx)],
  1494. sizeof(pbuf),
  1495. pbuf))
  1496. {
  1497. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  1498. "Unable to decrypt tag, dropping...\n");
  1499. GNUNET_free (ss);
  1500. GNUNET_STATISTICS_update (
  1501. stats,
  1502. "# messages dropped (no kid, AEAD decryption failed)",
  1503. 1,
  1504. GNUNET_NO);
  1505. return;
  1506. }
  1507. uc = (const struct UDPConfirmation *) pbuf;
  1508. if (GNUNET_OK != verify_confirmation (&kx->ephemeral, uc))
  1509. {
  1510. GNUNET_break_op (0);
  1511. GNUNET_free (ss);
  1512. GNUNET_STATISTICS_update (stats,
  1513. "# messages dropped (sender signature invalid)",
  1514. 1,
  1515. GNUNET_NO);
  1516. return;
  1517. }
  1518. calculate_cmac (ss);
  1519. sender = setup_sender (&uc->sender, (const struct sockaddr *) &sa, salen);
  1520. ss->sender = sender;
  1521. GNUNET_CONTAINER_DLL_insert (sender->ss_head, sender->ss_tail, ss);
  1522. sender->num_secrets++;
  1523. GNUNET_STATISTICS_update (stats, "# Secrets active", 1, GNUNET_NO);
  1524. GNUNET_STATISTICS_update (stats,
  1525. "# messages decrypted without BOX",
  1526. 1,
  1527. GNUNET_NO);
  1528. try_handle_plaintext (sender, &uc[1], sizeof(pbuf) - sizeof(*uc));
  1529. consider_ss_ack (ss);
  1530. if (sender->num_secrets > MAX_SECRETS)
  1531. secret_destroy (sender->ss_tail);
  1532. }
  1533. }
  1534. /**
  1535. * Convert UDP bind specification to a `struct sockaddr *`
  1536. *
  1537. * @param bindto bind specification to convert
  1538. * @param[out] sock_len set to the length of the address
  1539. * @return converted bindto specification
  1540. */
  1541. static struct sockaddr *
  1542. udp_address_to_sockaddr (const char *bindto, socklen_t *sock_len)
  1543. {
  1544. struct sockaddr *in;
  1545. unsigned int port;
  1546. char dummy[2];
  1547. char *colon;
  1548. char *cp;
  1549. if (1 == sscanf (bindto, "%u%1s", &port, dummy))
  1550. {
  1551. /* interpreting value as just a PORT number */
  1552. if (port > UINT16_MAX)
  1553. {
  1554. GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
  1555. "BINDTO specification `%s' invalid: value too large for port\n",
  1556. bindto);
  1557. return NULL;
  1558. }
  1559. if ((GNUNET_NO == GNUNET_NETWORK_test_pf (PF_INET6)) ||
  1560. (GNUNET_YES ==
  1561. GNUNET_CONFIGURATION_get_value_yesno (cfg,
  1562. COMMUNICATOR_CONFIG_SECTION,
  1563. "DISABLE_V6")))
  1564. {
  1565. struct sockaddr_in *i4;
  1566. i4 = GNUNET_malloc (sizeof(struct sockaddr_in));
  1567. i4->sin_family = AF_INET;
  1568. i4->sin_port = htons ((uint16_t) port);
  1569. *sock_len = sizeof(struct sockaddr_in);
  1570. in = (struct sockaddr *) i4;
  1571. }
  1572. else
  1573. {
  1574. struct sockaddr_in6 *i6;
  1575. i6 = GNUNET_malloc (sizeof(struct sockaddr_in6));
  1576. i6->sin6_family = AF_INET6;
  1577. i6->sin6_port = htons ((uint16_t) port);
  1578. *sock_len = sizeof(struct sockaddr_in6);
  1579. in = (struct sockaddr *) i6;
  1580. }
  1581. return in;
  1582. }
  1583. cp = GNUNET_strdup (bindto);
  1584. colon = strrchr (cp, ':');
  1585. if (NULL != colon)
  1586. {
  1587. /* interpet value after colon as port */
  1588. *colon = '\0';
  1589. colon++;
  1590. if (1 == sscanf (colon, "%u%1s", &port, dummy))
  1591. {
  1592. /* interpreting value as just a PORT number */
  1593. if (port > UINT16_MAX)
  1594. {
  1595. GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
  1596. "BINDTO specification `%s' invalid: value too large for port\n",
  1597. bindto);
  1598. GNUNET_free (cp);
  1599. return NULL;
  1600. }
  1601. }
  1602. else
  1603. {
  1604. GNUNET_log (
  1605. GNUNET_ERROR_TYPE_ERROR,
  1606. "BINDTO specification `%s' invalid: last ':' not followed by number\n",
  1607. bindto);
  1608. GNUNET_free (cp);
  1609. return NULL;
  1610. }
  1611. }
  1612. else
  1613. {
  1614. /* interpret missing port as 0, aka pick any free one */
  1615. port = 0;
  1616. }
  1617. {
  1618. /* try IPv4 */
  1619. struct sockaddr_in v4;
  1620. if (1 == inet_pton (AF_INET, cp, &v4.sin_addr))
  1621. {
  1622. v4.sin_family = AF_INET;
  1623. v4.sin_port = htons ((uint16_t) port);
  1624. #if HAVE_SOCKADDR_IN_SIN_LEN
  1625. v4.sin_len = sizeof(struct sockaddr_in);
  1626. #endif
  1627. in = GNUNET_memdup (&v4, sizeof(struct sockaddr_in));
  1628. *sock_len = sizeof(struct sockaddr_in);
  1629. GNUNET_free (cp);
  1630. return in;
  1631. }
  1632. }
  1633. {
  1634. /* try IPv6 */
  1635. struct sockaddr_in6 v6;
  1636. const char *start;
  1637. start = cp;
  1638. if (('[' == *cp) && (']' == cp[strlen (cp) - 1]))
  1639. {
  1640. start++; /* skip over '[' */
  1641. cp[strlen (cp) - 1] = '\0'; /* eat ']' */
  1642. }
  1643. if (1 == inet_pton (AF_INET6, start, &v6.sin6_addr))
  1644. {
  1645. v6.sin6_family = AF_INET6;
  1646. v6.sin6_port = htons ((uint16_t) port);
  1647. #if HAVE_SOCKADDR_IN_SIN_LEN
  1648. v6.sin6_len = sizeof(sizeof(struct sockaddr_in6));
  1649. #endif
  1650. in = GNUNET_memdup (&v6, sizeof(v6));
  1651. *sock_len = sizeof(v6);
  1652. GNUNET_free (cp);
  1653. return in;
  1654. }
  1655. }
  1656. /* #5528 FIXME (feature!): maybe also try getnameinfo()? */
  1657. GNUNET_free (cp);
  1658. return NULL;
  1659. }
  1660. /**
  1661. * Pad @a dgram by @a pad_size using @a out_cipher.
  1662. *
  1663. * @param out_cipher cipher to use
  1664. * @param dgram datagram to pad
  1665. * @param pad_size number of bytes of padding to append
  1666. */
  1667. static void
  1668. do_pad (gcry_cipher_hd_t out_cipher, char *dgram, size_t pad_size)
  1669. {
  1670. char pad[pad_size];
  1671. GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, pad, sizeof(pad));
  1672. if (sizeof(pad) > sizeof(struct GNUNET_MessageHeader))
  1673. {
  1674. struct GNUNET_MessageHeader hdr =
  1675. { .size = htons (sizeof(pad)),
  1676. .type = htons (GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_PAD) };
  1677. memcpy (pad, &hdr, sizeof(hdr));
  1678. }
  1679. GNUNET_assert (
  1680. 0 ==
  1681. gcry_cipher_encrypt (out_cipher, dgram, sizeof(pad), pad, sizeof(pad)));
  1682. }
  1683. /**
  1684. * Signature of functions implementing the sending functionality of a
  1685. * message queue.
  1686. *
  1687. * @param mq the message queue
  1688. * @param msg the message to send
  1689. * @param impl_state our `struct ReceiverAddress`
  1690. */
  1691. static void
  1692. mq_send_kx (struct GNUNET_MQ_Handle *mq,
  1693. const struct GNUNET_MessageHeader *msg,
  1694. void *impl_state)
  1695. {
  1696. struct ReceiverAddress *receiver = impl_state;
  1697. uint16_t msize = ntohs (msg->size);
  1698. struct UdpHandshakeSignature uhs;
  1699. struct UDPConfirmation uc;
  1700. struct InitialKX kx;
  1701. struct GNUNET_CRYPTO_EcdhePrivateKey epriv;
  1702. char dgram[receiver->kx_mtu + sizeof(uc) + sizeof(kx)];
  1703. size_t dpos;
  1704. gcry_cipher_hd_t out_cipher;
  1705. struct SharedSecret *ss;
  1706. GNUNET_assert (mq == receiver->kx_mq);
  1707. if (msize > receiver->kx_mtu)
  1708. {
  1709. GNUNET_break (0);
  1710. receiver_destroy (receiver);
  1711. return;
  1712. }
  1713. reschedule_receiver_timeout (receiver);
  1714. /* setup key material */
  1715. GNUNET_CRYPTO_ecdhe_key_create (&epriv);
  1716. ss = setup_shared_secret_enc (&epriv, receiver);
  1717. setup_cipher (&ss->master, 0, &out_cipher);
  1718. /* compute 'uc' */
  1719. uc.sender = my_identity;
  1720. uc.monotonic_time =
  1721. GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_monotonic (cfg));
  1722. uhs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_HANDSHAKE);
  1723. uhs.purpose.size = htonl (sizeof(uhs));
  1724. uhs.sender = my_identity;
  1725. uhs.receiver = receiver->target;
  1726. GNUNET_CRYPTO_ecdhe_key_get_public (&epriv, &uhs.ephemeral);
  1727. uhs.monotonic_time = uc.monotonic_time;
  1728. GNUNET_CRYPTO_eddsa_sign (my_private_key,
  1729. &uhs,
  1730. &uc.sender_sig);
  1731. /* Leave space for kx */
  1732. dpos = sizeof(kx);
  1733. /* Append encrypted uc to dgram */
  1734. GNUNET_assert (0 == gcry_cipher_encrypt (out_cipher,
  1735. &dgram[dpos],
  1736. sizeof(uc),
  1737. &uc,
  1738. sizeof(uc)));
  1739. dpos += sizeof(uc);
  1740. /* Append encrypted payload to dgram */
  1741. GNUNET_assert (
  1742. 0 == gcry_cipher_encrypt (out_cipher, &dgram[dpos], msize, msg, msize));
  1743. dpos += msize;
  1744. do_pad (out_cipher, &dgram[dpos], sizeof(dgram) - dpos);
  1745. /* Datagram starts with kx */
  1746. kx.ephemeral = uhs.ephemeral;
  1747. GNUNET_assert (
  1748. 0 == gcry_cipher_gettag (out_cipher, kx.gcm_tag, sizeof(kx.gcm_tag)));
  1749. gcry_cipher_close (out_cipher);
  1750. memcpy (dgram, &kx, sizeof(kx));
  1751. if (-1 == GNUNET_NETWORK_socket_sendto (udp_sock,
  1752. dgram,
  1753. sizeof(dgram),
  1754. receiver->address,
  1755. receiver->address_len))
  1756. GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "send");
  1757. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  1758. "Sending KX to %s\n", GNUNET_a2s (receiver->address,
  1759. receiver->address_len));
  1760. GNUNET_MQ_impl_send_continue (mq);
  1761. }
  1762. /**
  1763. * Signature of functions implementing the sending functionality of a
  1764. * message queue.
  1765. *
  1766. * @param mq the message queue
  1767. * @param msg the message to send
  1768. * @param impl_state our `struct ReceiverAddress`
  1769. */
  1770. static void
  1771. mq_send_d (struct GNUNET_MQ_Handle *mq,
  1772. const struct GNUNET_MessageHeader *msg,
  1773. void *impl_state)
  1774. {
  1775. struct ReceiverAddress *receiver = impl_state;
  1776. uint16_t msize = ntohs (msg->size);
  1777. GNUNET_assert (mq == receiver->d_mq);
  1778. if ((msize > receiver->d_mtu) ||
  1779. (0 == receiver->acks_available))
  1780. {
  1781. GNUNET_break (0);
  1782. receiver_destroy (receiver);
  1783. return;
  1784. }
  1785. reschedule_receiver_timeout (receiver);
  1786. /* begin "BOX" encryption method, scan for ACKs from tail! */
  1787. for (struct SharedSecret *ss = receiver->ss_tail; NULL != ss; ss = ss->prev)
  1788. {
  1789. if (ss->sequence_used >= ss->sequence_allowed)
  1790. {
  1791. continue;
  1792. }
  1793. char dgram[sizeof(struct UDPBox) + receiver->d_mtu];
  1794. struct UDPBox *box;
  1795. gcry_cipher_hd_t out_cipher;
  1796. size_t dpos;
  1797. box = (struct UDPBox *) dgram;
  1798. ss->sequence_used++;
  1799. get_kid (&ss->master, ss->sequence_used, &box->kid);
  1800. setup_cipher (&ss->master, ss->sequence_used, &out_cipher);
  1801. /* Append encrypted payload to dgram */
  1802. dpos = sizeof(struct UDPBox);
  1803. GNUNET_assert (
  1804. 0 == gcry_cipher_encrypt (out_cipher, &dgram[dpos], msize, msg, msize));
  1805. dpos += msize;
  1806. do_pad (out_cipher, &dgram[dpos], sizeof(dgram) - dpos);
  1807. GNUNET_assert (0 == gcry_cipher_gettag (out_cipher,
  1808. box->gcm_tag,
  1809. sizeof(box->gcm_tag)));
  1810. gcry_cipher_close (out_cipher);
  1811. if (-1 == GNUNET_NETWORK_socket_sendto (udp_sock,
  1812. dgram,
  1813. sizeof(dgram),
  1814. receiver->address,
  1815. receiver->address_len))
  1816. GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "send");
  1817. GNUNET_MQ_impl_send_continue (mq);
  1818. receiver->acks_available--;
  1819. if (0 == receiver->acks_available)
  1820. {
  1821. /* We have no more ACKs */
  1822. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  1823. "No more acks\n");
  1824. }
  1825. return;
  1826. }
  1827. }
  1828. /**
  1829. * Signature of functions implementing the destruction of a message
  1830. * queue. Implementations must not free @a mq, but should take care
  1831. * of @a impl_state.
  1832. *
  1833. * @param mq the message queue to destroy
  1834. * @param impl_state our `struct ReceiverAddress`
  1835. */
  1836. static void
  1837. mq_destroy_d (struct GNUNET_MQ_Handle *mq, void *impl_state)
  1838. {
  1839. struct ReceiverAddress *receiver = impl_state;
  1840. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  1841. "Default MQ destroyed\n");
  1842. if (mq == receiver->d_mq)
  1843. {
  1844. receiver->d_mq = NULL;
  1845. receiver_destroy (receiver);
  1846. }
  1847. }
  1848. /**
  1849. * Signature of functions implementing the destruction of a message
  1850. * queue. Implementations must not free @a mq, but should take care
  1851. * of @a impl_state.
  1852. *
  1853. * @param mq the message queue to destroy
  1854. * @param impl_state our `struct ReceiverAddress`
  1855. */
  1856. static void
  1857. mq_destroy_kx (struct GNUNET_MQ_Handle *mq, void *impl_state)
  1858. {
  1859. struct ReceiverAddress *receiver = impl_state;
  1860. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  1861. "KX MQ destroyed\n");
  1862. if (mq == receiver->kx_mq)
  1863. {
  1864. receiver->kx_mq = NULL;
  1865. receiver_destroy (receiver);
  1866. }
  1867. }
  1868. /**
  1869. * Implementation function that cancels the currently sent message.
  1870. *
  1871. * @param mq message queue
  1872. * @param impl_state our `struct RecvierAddress`
  1873. */
  1874. static void
  1875. mq_cancel (struct GNUNET_MQ_Handle *mq, void *impl_state)
  1876. {
  1877. /* Cancellation is impossible with UDP; bail */
  1878. GNUNET_assert (0);
  1879. }
  1880. /**
  1881. * Generic error handler, called with the appropriate
  1882. * error code and the same closure specified at the creation of
  1883. * the message queue.
  1884. * Not every message queue implementation supports an error handler.
  1885. *
  1886. * @param cls our `struct ReceiverAddress`
  1887. * @param error error code
  1888. */
  1889. static void
  1890. mq_error (void *cls, enum GNUNET_MQ_Error error)
  1891. {
  1892. struct ReceiverAddress *receiver = cls;
  1893. GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
  1894. "MQ error in queue to %s: %d\n",
  1895. GNUNET_i2s (&receiver->target),
  1896. (int) error);
  1897. receiver_destroy (receiver);
  1898. }
  1899. /**
  1900. * Setup the MQ for the @a receiver. If a queue exists,
  1901. * the existing one is destroyed. Then the MTU is
  1902. * recalculated and a fresh queue is initialized.
  1903. *
  1904. * @param receiver receiver to setup MQ for
  1905. */
  1906. static void
  1907. setup_receiver_mq (struct ReceiverAddress *receiver)
  1908. {
  1909. size_t base_mtu;
  1910. /*if (NULL != receiver->kx_qh)
  1911. {
  1912. GNUNET_TRANSPORT_communicator_mq_del (receiver->kx_qh);
  1913. receiver->kx_qh = NULL;
  1914. }
  1915. if (NULL != receiver->d_qh)
  1916. {
  1917. GNUNET_TRANSPORT_communicator_mq_del (receiver->d_qh);
  1918. receiver->d_qh = NULL;
  1919. }*/
  1920. // GNUNET_assert (NULL == receiver->mq);
  1921. switch (receiver->address->sa_family)
  1922. {
  1923. case AF_INET:
  1924. base_mtu = 1480 /* Ethernet MTU, 1500 - Ethernet header - VLAN tag */
  1925. - sizeof(struct GNUNET_TUN_IPv4Header) /* 20 */
  1926. - sizeof(struct GNUNET_TUN_UdpHeader) /* 8 */;
  1927. break;
  1928. case AF_INET6:
  1929. base_mtu = 1280 /* Minimum MTU required by IPv6 */
  1930. - sizeof(struct GNUNET_TUN_IPv6Header) /* 40 */
  1931. - sizeof(struct GNUNET_TUN_UdpHeader) /* 8 */;
  1932. break;
  1933. default:
  1934. GNUNET_assert (0);
  1935. break;
  1936. }
  1937. /* MTU based on full KX messages */
  1938. receiver->kx_mtu = base_mtu - sizeof(struct InitialKX) /* 48 */
  1939. - sizeof(struct UDPConfirmation); /* 104 */
  1940. /* MTU based on BOXed messages */
  1941. receiver->d_mtu = base_mtu - sizeof(struct UDPBox);
  1942. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  1943. "Setting up MQs and QHs\n");
  1944. /* => Effective MTU for CORE will range from 1080 (IPv6 + KX) to
  1945. 1404 (IPv4 + Box) bytes, depending on circumstances... */
  1946. if (NULL == receiver->kx_mq)
  1947. receiver->kx_mq = GNUNET_MQ_queue_for_callbacks (&mq_send_kx,
  1948. &mq_destroy_kx,
  1949. &mq_cancel,
  1950. receiver,
  1951. NULL,
  1952. &mq_error,
  1953. receiver);
  1954. if (NULL == receiver->d_mq)
  1955. receiver->d_mq = GNUNET_MQ_queue_for_callbacks (&mq_send_d,
  1956. &mq_destroy_d,
  1957. &mq_cancel,
  1958. receiver,
  1959. NULL,
  1960. &mq_error,
  1961. receiver);
  1962. receiver->kx_qh =
  1963. GNUNET_TRANSPORT_communicator_mq_add (ch,
  1964. &receiver->target,
  1965. receiver->foreign_addr,
  1966. receiver->kx_mtu,
  1967. GNUNET_TRANSPORT_QUEUE_LENGTH_UNLIMITED,
  1968. 0, /* Priority */
  1969. receiver->nt,
  1970. GNUNET_TRANSPORT_CS_OUTBOUND,
  1971. receiver->kx_mq);
  1972. receiver->d_qh =
  1973. GNUNET_TRANSPORT_communicator_mq_add (ch,
  1974. &receiver->target,
  1975. receiver->foreign_addr,
  1976. receiver->d_mtu,
  1977. 0, /* Initialize with 0 acks */
  1978. 1, /* Priority */
  1979. receiver->nt,
  1980. GNUNET_TRANSPORT_CS_OUTBOUND,
  1981. receiver->d_mq);
  1982. }
  1983. /**
  1984. * Function called by the transport service to initialize a
  1985. * message queue given address information about another peer.
  1986. * If and when the communication channel is established, the
  1987. * communicator must call #GNUNET_TRANSPORT_communicator_mq_add()
  1988. * to notify the service that the channel is now up. It is
  1989. * the responsibility of the communicator to manage sane
  1990. * retries and timeouts for any @a peer/@a address combination
  1991. * provided by the transport service. Timeouts and retries
  1992. * do not need to be signalled to the transport service.
  1993. *
  1994. * @param cls closure
  1995. * @param peer identity of the other peer
  1996. * @param address where to send the message, human-readable
  1997. * communicator-specific format, 0-terminated, UTF-8
  1998. * @return #GNUNET_OK on success, #GNUNET_SYSERR if the provided address is
  1999. * invalid
  2000. */
  2001. static int
  2002. mq_init (void *cls, const struct GNUNET_PeerIdentity *peer, const char *address)
  2003. {
  2004. struct ReceiverAddress *receiver;
  2005. const char *path;
  2006. struct sockaddr *in;
  2007. socklen_t in_len;
  2008. if (0 != strncmp (address,
  2009. COMMUNICATOR_ADDRESS_PREFIX "-",
  2010. strlen (COMMUNICATOR_ADDRESS_PREFIX "-")))
  2011. {
  2012. GNUNET_break_op (0);
  2013. return GNUNET_SYSERR;
  2014. }
  2015. path = &address[strlen (COMMUNICATOR_ADDRESS_PREFIX "-")];
  2016. in = udp_address_to_sockaddr (path, &in_len);
  2017. receiver = GNUNET_new (struct ReceiverAddress);
  2018. receiver->address = in;
  2019. receiver->address_len = in_len;
  2020. receiver->target = *peer;
  2021. receiver->nt = GNUNET_NT_scanner_get_type (is, in, in_len);
  2022. (void) GNUNET_CONTAINER_multipeermap_put (
  2023. receivers,
  2024. &receiver->target,
  2025. receiver,
  2026. GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
  2027. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  2028. "Added %s to receivers\n",
  2029. GNUNET_i2s_full (&receiver->target));
  2030. receiver->timeout =
  2031. GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
  2032. receiver->hn = GNUNET_CONTAINER_heap_insert (receivers_heap,
  2033. receiver,
  2034. receiver->timeout.abs_value_us);
  2035. GNUNET_STATISTICS_set (stats,
  2036. "# receivers active",
  2037. GNUNET_CONTAINER_multipeermap_size (receivers),
  2038. GNUNET_NO);
  2039. receiver->foreign_addr =
  2040. sockaddr_to_udpaddr_string (receiver->address, receiver->address_len);
  2041. setup_receiver_mq (receiver);
  2042. if (NULL == timeout_task)
  2043. timeout_task = GNUNET_SCHEDULER_add_now (&check_timeouts, NULL);
  2044. return GNUNET_OK;
  2045. }
  2046. /**
  2047. * Iterator over all receivers to clean up.
  2048. *
  2049. * @param cls NULL
  2050. * @param target unused
  2051. * @param value the queue to destroy
  2052. * @return #GNUNET_OK to continue to iterate
  2053. */
  2054. static int
  2055. get_receiver_delete_it (void *cls,
  2056. const struct GNUNET_PeerIdentity *target,
  2057. void *value)
  2058. {
  2059. struct ReceiverAddress *receiver = value;
  2060. (void) cls;
  2061. (void) target;
  2062. receiver_destroy (receiver);
  2063. return GNUNET_OK;
  2064. }
  2065. /**
  2066. * Iterator over all senders to clean up.
  2067. *
  2068. * @param cls NULL
  2069. * @param target unused
  2070. * @param value the queue to destroy
  2071. * @return #GNUNET_OK to continue to iterate
  2072. */
  2073. static int
  2074. get_sender_delete_it (void *cls,
  2075. const struct GNUNET_PeerIdentity *target,
  2076. void *value)
  2077. {
  2078. struct SenderAddress *sender = value;
  2079. (void) cls;
  2080. (void) target;
  2081. sender_destroy (sender);
  2082. return GNUNET_OK;
  2083. }
  2084. /**
  2085. * Shutdown the UNIX communicator.
  2086. *
  2087. * @param cls NULL (always)
  2088. */
  2089. static void
  2090. do_shutdown (void *cls)
  2091. {
  2092. if (NULL != nat)
  2093. {
  2094. GNUNET_NAT_unregister (nat);
  2095. nat = NULL;
  2096. }
  2097. while (NULL != bi_head)
  2098. bi_destroy (bi_head);
  2099. if (NULL != broadcast_task)
  2100. {
  2101. GNUNET_SCHEDULER_cancel (broadcast_task);
  2102. broadcast_task = NULL;
  2103. }
  2104. if (NULL != read_task)
  2105. {
  2106. GNUNET_SCHEDULER_cancel (read_task);
  2107. read_task = NULL;
  2108. }
  2109. if (NULL != udp_sock)
  2110. {
  2111. GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (udp_sock));
  2112. udp_sock = NULL;
  2113. }
  2114. GNUNET_CONTAINER_multipeermap_iterate (receivers,
  2115. &get_receiver_delete_it,
  2116. NULL);
  2117. GNUNET_CONTAINER_multipeermap_destroy (receivers);
  2118. GNUNET_CONTAINER_multipeermap_iterate (senders, &get_sender_delete_it, NULL);
  2119. GNUNET_CONTAINER_multipeermap_destroy (senders);
  2120. GNUNET_CONTAINER_multishortmap_destroy (key_cache);
  2121. GNUNET_CONTAINER_heap_destroy (senders_heap);
  2122. GNUNET_CONTAINER_heap_destroy (receivers_heap);
  2123. if (NULL != ch)
  2124. {
  2125. GNUNET_TRANSPORT_communicator_disconnect (ch);
  2126. ch = NULL;
  2127. }
  2128. if (NULL != ah)
  2129. {
  2130. GNUNET_TRANSPORT_application_done (ah);
  2131. ah = NULL;
  2132. }
  2133. if (NULL != stats)
  2134. {
  2135. GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
  2136. stats = NULL;
  2137. }
  2138. if (NULL != my_private_key)
  2139. {
  2140. GNUNET_free (my_private_key);
  2141. my_private_key = NULL;
  2142. }
  2143. if (NULL != is)
  2144. {
  2145. GNUNET_NT_scanner_done (is);
  2146. is = NULL;
  2147. }
  2148. }
  2149. /**
  2150. * Function called when the transport service has received a
  2151. * backchannel message for this communicator (!) via a different return
  2152. * path. Should be an acknowledgement.
  2153. *
  2154. * @param cls closure, NULL
  2155. * @param sender which peer sent the notification
  2156. * @param msg payload
  2157. */
  2158. static void
  2159. enc_notify_cb (void *cls,
  2160. const struct GNUNET_PeerIdentity *sender,
  2161. const struct GNUNET_MessageHeader *msg)
  2162. {
  2163. const struct UDPAck *ack;
  2164. (void) cls;
  2165. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  2166. "Storing UDPAck received from backchannel from %s\n",
  2167. GNUNET_i2s_full (sender));
  2168. if ((ntohs (msg->type) != GNUNET_MESSAGE_TYPE_COMMUNICATOR_UDP_ACK) ||
  2169. (ntohs (msg->size) != sizeof(struct UDPAck)))
  2170. {
  2171. GNUNET_break_op (0);
  2172. return;
  2173. }
  2174. ack = (const struct UDPAck *) msg;
  2175. GNUNET_CONTAINER_multipeermap_get_multiple (receivers,
  2176. sender,
  2177. &handle_ack,
  2178. (void *) ack);
  2179. }
  2180. /**
  2181. * Signature of the callback passed to #GNUNET_NAT_register() for
  2182. * a function to call whenever our set of 'valid' addresses changes.
  2183. *
  2184. * @param cls closure
  2185. * @param app_ctx[in,out] location where the app can store stuff
  2186. * on add and retrieve it on remove
  2187. * @param add_remove #GNUNET_YES to add a new public IP address,
  2188. * #GNUNET_NO to remove a previous (now invalid) one
  2189. * @param ac address class the address belongs to
  2190. * @param addr either the previous or the new public IP address
  2191. * @param addrlen actual length of the @a addr
  2192. */
  2193. static void
  2194. nat_address_cb (void *cls,
  2195. void **app_ctx,
  2196. int add_remove,
  2197. enum GNUNET_NAT_AddressClass ac,
  2198. const struct sockaddr *addr,
  2199. socklen_t addrlen)
  2200. {
  2201. char *my_addr;
  2202. struct GNUNET_TRANSPORT_AddressIdentifier *ai;
  2203. if (GNUNET_YES == add_remove)
  2204. {
  2205. enum GNUNET_NetworkType nt;
  2206. GNUNET_asprintf (&my_addr,
  2207. "%s-%s",
  2208. COMMUNICATOR_ADDRESS_PREFIX,
  2209. GNUNET_a2s (addr, addrlen));
  2210. nt = GNUNET_NT_scanner_get_type (is, addr, addrlen);
  2211. ai =
  2212. GNUNET_TRANSPORT_communicator_address_add (ch,
  2213. my_addr,
  2214. nt,
  2215. GNUNET_TIME_UNIT_FOREVER_REL);
  2216. GNUNET_free (my_addr);
  2217. *app_ctx = ai;
  2218. }
  2219. else
  2220. {
  2221. ai = *app_ctx;
  2222. GNUNET_TRANSPORT_communicator_address_remove (ai);
  2223. *app_ctx = NULL;
  2224. }
  2225. }
  2226. /**
  2227. * Broadcast our presence on one of our interfaces.
  2228. *
  2229. * @param cls a `struct BroadcastInterface`
  2230. */
  2231. static void
  2232. ifc_broadcast (void *cls)
  2233. {
  2234. struct BroadcastInterface *bi = cls;
  2235. struct GNUNET_TIME_Relative delay;
  2236. delay = BROADCAST_FREQUENCY;
  2237. delay.rel_value_us =
  2238. GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, delay.rel_value_us);
  2239. bi->broadcast_task =
  2240. GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY, &ifc_broadcast, bi);
  2241. switch (bi->sa->sa_family)
  2242. {
  2243. case AF_INET: {
  2244. static int yes = 1;
  2245. static int no = 0;
  2246. ssize_t sent;
  2247. if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt (udp_sock,
  2248. SOL_SOCKET,
  2249. SO_BROADCAST,
  2250. &yes,
  2251. sizeof(int)))
  2252. GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
  2253. sent = GNUNET_NETWORK_socket_sendto (udp_sock,
  2254. &bi->bcm,
  2255. sizeof(bi->bcm),
  2256. bi->ba,
  2257. bi->salen);
  2258. if (-1 == sent)
  2259. GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "sendto");
  2260. if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt (udp_sock,
  2261. SOL_SOCKET,
  2262. SO_BROADCAST,
  2263. &no,
  2264. sizeof(int)))
  2265. GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
  2266. break;
  2267. }
  2268. case AF_INET6: {
  2269. ssize_t sent;
  2270. struct sockaddr_in6 dst;
  2271. dst.sin6_family = AF_INET6;
  2272. dst.sin6_port = htons (my_port);
  2273. dst.sin6_addr = bi->mcreq.ipv6mr_multiaddr;
  2274. dst.sin6_scope_id = ((struct sockaddr_in6 *) bi->ba)->sin6_scope_id;
  2275. sent = GNUNET_NETWORK_socket_sendto (udp_sock,
  2276. &bi->bcm,
  2277. sizeof(bi->bcm),
  2278. (const struct sockaddr *) &dst,
  2279. sizeof(dst));
  2280. if (-1 == sent)
  2281. GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "sendto");
  2282. break;
  2283. }
  2284. default:
  2285. GNUNET_break (0);
  2286. break;
  2287. }
  2288. }
  2289. /**
  2290. * Callback function invoked for each interface found.
  2291. * Activates/deactivates broadcast interfaces.
  2292. *
  2293. * @param cls NULL
  2294. * @param name name of the interface (can be NULL for unknown)
  2295. * @param isDefault is this presumably the default interface
  2296. * @param addr address of this interface (can be NULL for unknown or unassigned)
  2297. * @param broadcast_addr the broadcast address (can be NULL for unknown or
  2298. * unassigned)
  2299. * @param netmask the network mask (can be NULL for unknown or unassigned)
  2300. * @param addrlen length of the address
  2301. * @return #GNUNET_OK to continue iteration, #GNUNET_SYSERR to abort
  2302. */
  2303. static int
  2304. iface_proc (void *cls,
  2305. const char *name,
  2306. int isDefault,
  2307. const struct sockaddr *addr,
  2308. const struct sockaddr *broadcast_addr,
  2309. const struct sockaddr *netmask,
  2310. socklen_t addrlen)
  2311. {
  2312. struct BroadcastInterface *bi;
  2313. enum GNUNET_NetworkType network;
  2314. struct UdpBroadcastSignature ubs;
  2315. (void) cls;
  2316. (void) netmask;
  2317. if (NULL == addr)
  2318. return GNUNET_YES; /* need to know our address! */
  2319. network = GNUNET_NT_scanner_get_type (is, addr, addrlen);
  2320. if (GNUNET_NT_LOOPBACK == network)
  2321. {
  2322. /* Broadcasting on loopback does not make sense */
  2323. return GNUNET_YES;
  2324. }
  2325. for (bi = bi_head; NULL != bi; bi = bi->next)
  2326. {
  2327. if ((bi->salen == addrlen) && (0 == memcmp (addr, bi->sa, addrlen)))
  2328. {
  2329. bi->found = GNUNET_YES;
  2330. return GNUNET_OK;
  2331. }
  2332. }
  2333. if ((AF_INET6 == addr->sa_family) && (NULL == broadcast_addr))
  2334. return GNUNET_OK; /* broadcast_addr is required for IPv6! */
  2335. if ((AF_INET6 == addr->sa_family) && (GNUNET_YES != have_v6_socket))
  2336. return GNUNET_OK; /* not using IPv6 */
  2337. bi = GNUNET_new (struct BroadcastInterface);
  2338. bi->sa = GNUNET_memdup (addr, addrlen);
  2339. if (NULL != broadcast_addr)
  2340. bi->ba = GNUNET_memdup (broadcast_addr, addrlen);
  2341. bi->salen = addrlen;
  2342. bi->found = GNUNET_YES;
  2343. bi->bcm.sender = my_identity;
  2344. ubs.purpose.purpose = htonl (GNUNET_SIGNATURE_COMMUNICATOR_UDP_BROADCAST);
  2345. ubs.purpose.size = htonl (sizeof(ubs));
  2346. ubs.sender = my_identity;
  2347. GNUNET_CRYPTO_hash (addr, addrlen, &ubs.h_address);
  2348. GNUNET_CRYPTO_eddsa_sign (my_private_key,
  2349. &ubs,
  2350. &bi->bcm.sender_sig);
  2351. if (NULL != broadcast_addr)
  2352. {
  2353. bi->broadcast_task = GNUNET_SCHEDULER_add_now (&ifc_broadcast, bi);
  2354. GNUNET_CONTAINER_DLL_insert (bi_head, bi_tail, bi);
  2355. }
  2356. if ((AF_INET6 == addr->sa_family) && (NULL != broadcast_addr))
  2357. {
  2358. /* Create IPv6 multicast request */
  2359. const struct sockaddr_in6 *s6 =
  2360. (const struct sockaddr_in6 *) broadcast_addr;
  2361. GNUNET_assert (
  2362. 1 == inet_pton (AF_INET6, "FF05::13B", &bi->mcreq.ipv6mr_multiaddr));
  2363. /* http://tools.ietf.org/html/rfc2553#section-5.2:
  2364. *
  2365. * IPV6_JOIN_GROUP
  2366. *
  2367. * Join a multicast group on a specified local interface. If the
  2368. * interface index is specified as 0, the kernel chooses the local
  2369. * interface. For example, some kernels look up the multicast
  2370. * group in the normal IPv6 routing table and using the resulting
  2371. * interface; we do this for each interface, so no need to use
  2372. * zero (anymore...).
  2373. */bi->mcreq.ipv6mr_interface = s6->sin6_scope_id;
  2374. /* Join the multicast group */
  2375. if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt (udp_sock,
  2376. IPPROTO_IPV6,
  2377. IPV6_JOIN_GROUP,
  2378. &bi->mcreq,
  2379. sizeof(bi->mcreq)))
  2380. {
  2381. GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "setsockopt");
  2382. }
  2383. }
  2384. return GNUNET_OK;
  2385. }
  2386. /**
  2387. * Scan interfaces to broadcast our presence on the LAN.
  2388. *
  2389. * @param cls NULL, unused
  2390. */
  2391. static void
  2392. do_broadcast (void *cls)
  2393. {
  2394. struct BroadcastInterface *bin;
  2395. (void) cls;
  2396. for (struct BroadcastInterface *bi = bi_head; NULL != bi; bi = bi->next)
  2397. bi->found = GNUNET_NO;
  2398. GNUNET_OS_network_interfaces_list (&iface_proc, NULL);
  2399. for (struct BroadcastInterface *bi = bi_head; NULL != bi; bi = bin)
  2400. {
  2401. bin = bi->next;
  2402. if (GNUNET_NO == bi->found)
  2403. bi_destroy (bi);
  2404. }
  2405. broadcast_task = GNUNET_SCHEDULER_add_delayed (INTERFACE_SCAN_FREQUENCY,
  2406. &do_broadcast,
  2407. NULL);
  2408. }
  2409. /**
  2410. * Setup communicator and launch network interactions.
  2411. *
  2412. * @param cls NULL (always)
  2413. * @param args remaining command-line arguments
  2414. * @param cfgfile name of the configuration file used (for saving, can be NULL!)
  2415. * @param c configuration
  2416. */
  2417. static void
  2418. run (void *cls,
  2419. char *const *args,
  2420. const char *cfgfile,
  2421. const struct GNUNET_CONFIGURATION_Handle *c)
  2422. {
  2423. char *bindto;
  2424. struct sockaddr *in;
  2425. socklen_t in_len;
  2426. struct sockaddr_storage in_sto;
  2427. socklen_t sto_len;
  2428. (void) cls;
  2429. cfg = c;
  2430. if (GNUNET_OK !=
  2431. GNUNET_CONFIGURATION_get_value_string (cfg,
  2432. COMMUNICATOR_CONFIG_SECTION,
  2433. "BINDTO",
  2434. &bindto))
  2435. {
  2436. GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
  2437. COMMUNICATOR_CONFIG_SECTION,
  2438. "BINDTO");
  2439. return;
  2440. }
  2441. in = udp_address_to_sockaddr (bindto, &in_len);
  2442. if (NULL == in)
  2443. {
  2444. GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
  2445. "Failed to setup UDP socket address with path `%s'\n",
  2446. bindto);
  2447. GNUNET_free (bindto);
  2448. return;
  2449. }
  2450. udp_sock =
  2451. GNUNET_NETWORK_socket_create (in->sa_family, SOCK_DGRAM, IPPROTO_UDP);
  2452. if (NULL == udp_sock)
  2453. {
  2454. GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
  2455. GNUNET_free (in);
  2456. GNUNET_free (bindto);
  2457. return;
  2458. }
  2459. if (AF_INET6 == in->sa_family)
  2460. have_v6_socket = GNUNET_YES;
  2461. if (GNUNET_OK != GNUNET_NETWORK_socket_bind (udp_sock, in, in_len))
  2462. {
  2463. GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "bind", bindto);
  2464. GNUNET_NETWORK_socket_close (udp_sock);
  2465. udp_sock = NULL;
  2466. GNUNET_free (in);
  2467. GNUNET_free (bindto);
  2468. return;
  2469. }
  2470. /* We might have bound to port 0, allowing the OS to figure it out;
  2471. thus, get the real IN-address from the socket */
  2472. sto_len = sizeof(in_sto);
  2473. if (0 != getsockname (GNUNET_NETWORK_get_fd (udp_sock),
  2474. (struct sockaddr *) &in_sto,
  2475. &sto_len))
  2476. {
  2477. memcpy (&in_sto, in, in_len);
  2478. sto_len = in_len;
  2479. }
  2480. GNUNET_free (in);
  2481. GNUNET_free (bindto);
  2482. in = (struct sockaddr *) &in_sto;
  2483. in_len = sto_len;
  2484. GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
  2485. "Bound to `%s'\n",
  2486. GNUNET_a2s ((const struct sockaddr *) &in_sto, sto_len));
  2487. switch (in->sa_family)
  2488. {
  2489. case AF_INET:
  2490. my_port = ntohs (((struct sockaddr_in *) in)->sin_port);
  2491. break;
  2492. case AF_INET6:
  2493. my_port = ntohs (((struct sockaddr_in6 *) in)->sin6_port);
  2494. break;
  2495. default:
  2496. GNUNET_break (0);
  2497. my_port = 0;
  2498. }
  2499. stats = GNUNET_STATISTICS_create ("C-UDP", cfg);
  2500. senders = GNUNET_CONTAINER_multipeermap_create (32, GNUNET_YES);
  2501. receivers = GNUNET_CONTAINER_multipeermap_create (32, GNUNET_YES);
  2502. senders_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
  2503. receivers_heap =
  2504. GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
  2505. key_cache = GNUNET_CONTAINER_multishortmap_create (1024, GNUNET_YES);
  2506. GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL);
  2507. is = GNUNET_NT_scanner_init ();
  2508. my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg);
  2509. if (NULL == my_private_key)
  2510. {
  2511. GNUNET_log (
  2512. GNUNET_ERROR_TYPE_ERROR,
  2513. _ (
  2514. "Transport service is lacking key configuration settings. Exiting.\n"));
  2515. GNUNET_SCHEDULER_shutdown ();
  2516. return;
  2517. }
  2518. GNUNET_CRYPTO_eddsa_key_get_public (my_private_key, &my_identity.public_key);
  2519. /* start reading */
  2520. read_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
  2521. udp_sock,
  2522. &sock_read,
  2523. NULL);
  2524. ch = GNUNET_TRANSPORT_communicator_connect (cfg,
  2525. COMMUNICATOR_CONFIG_SECTION,
  2526. COMMUNICATOR_ADDRESS_PREFIX,
  2527. GNUNET_TRANSPORT_CC_UNRELIABLE,
  2528. &mq_init,
  2529. NULL,
  2530. &enc_notify_cb,
  2531. NULL);
  2532. if (NULL == ch)
  2533. {
  2534. GNUNET_break (0);
  2535. GNUNET_SCHEDULER_shutdown ();
  2536. return;
  2537. }
  2538. ah = GNUNET_TRANSPORT_application_init (cfg);
  2539. if (NULL == ah)
  2540. {
  2541. GNUNET_break (0);
  2542. GNUNET_SCHEDULER_shutdown ();
  2543. return;
  2544. }
  2545. /* start broadcasting */
  2546. if (GNUNET_YES !=
  2547. GNUNET_CONFIGURATION_get_value_yesno (cfg,
  2548. COMMUNICATOR_CONFIG_SECTION,
  2549. "DISABLE_BROADCAST"))
  2550. {
  2551. broadcast_task = GNUNET_SCHEDULER_add_now (&do_broadcast, NULL);
  2552. }
  2553. nat = GNUNET_NAT_register (cfg,
  2554. COMMUNICATOR_CONFIG_SECTION,
  2555. IPPROTO_UDP,
  2556. 1 /* one address */,
  2557. (const struct sockaddr **) &in,
  2558. &in_len,
  2559. &nat_address_cb,
  2560. NULL /* FIXME: support reversal: #5529 */,
  2561. NULL /* closure */);
  2562. }
  2563. /**
  2564. * The main function for the UNIX communicator.
  2565. *
  2566. * @param argc number of arguments from the command line
  2567. * @param argv command line arguments
  2568. * @return 0 ok, 1 on error
  2569. */
  2570. int
  2571. main (int argc, char *const *argv)
  2572. {
  2573. static const struct GNUNET_GETOPT_CommandLineOption options[] = {
  2574. GNUNET_GETOPT_OPTION_END
  2575. };
  2576. int ret;
  2577. if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
  2578. return 2;
  2579. ret = (GNUNET_OK == GNUNET_PROGRAM_run (argc,
  2580. argv,
  2581. "gnunet-communicator-udp",
  2582. _ ("GNUnet UDP communicator"),
  2583. options,
  2584. &run,
  2585. NULL))
  2586. ? 0
  2587. : 1;
  2588. GNUNET_free_nz ((void *) argv);
  2589. return ret;
  2590. }
  2591. /* end of gnunet-communicator-udp.c */