circuitpadding.c 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467
  1. /* Copyright (c) 2017 The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. #include <math.h>
  4. #include "lib/math/fp.h"
  5. #include "core/or/or.h"
  6. #include "core/or/circuitpadding.h"
  7. #include "core/or/circuitlist.h"
  8. #include "core/or/circuituse.h"
  9. #include "core/or/relay.h"
  10. #include "feature/stats/rephist.h"
  11. #include "feature/nodelist/networkstatus.h"
  12. #include "core/or/channel.h"
  13. #include "lib/time/compat_time.h"
  14. #include "lib/crypt_ops/crypto_rand.h"
  15. #include "core/or/crypt_path_st.h"
  16. #include "core/or/circuit_st.h"
  17. #include "core/or/origin_circuit_st.h"
  18. #include "feature/nodelist/routerstatus_st.h"
  19. #include "feature/nodelist/node_st.h"
  20. #include "core/or/cell_st.h"
  21. #include "core/or/extend_info_st.h"
  22. #include "core/crypto/relay_crypto.h"
  23. #include "feature/nodelist/nodelist.h"
  24. #include "app/config/config.h"
  25. /* XXX: This is a dup of the constant in ./src/lib/time/tvdiff.c.
  26. * Should/Do we have a header for time constants like this? */
  27. #define TOR_USEC_PER_SEC (1000000)
  28. static inline circpad_purpose_mask_t circpad_circ_purpose_to_mask(uint8_t
  29. circ_purpose);
  30. static inline circpad_circuit_state_t circpad_circuit_state(
  31. origin_circuit_t *circ);
  32. static void circpad_setup_machine_on_circ(circuit_t *on_circ,
  33. const circpad_machine_t *machine);
  34. static double circpad_distribution_sample(circpad_distribution_t dist);
  35. /** Cached consensus params */
  36. static uint8_t circpad_global_max_padding_percent;
  37. static uint16_t circpad_global_allowed_cells;
  38. /** Global cell counts, for rate limiting */
  39. static uint64_t circpad_global_padding_sent;
  40. static uint64_t circpad_global_nonpadding_sent;
  41. /** This is the list of circpad_machine_t's parsed from consensus and torrc
  42. * that have origin_side == 1 (ie: are for client side) */
  43. STATIC smartlist_t *origin_padding_machines = NULL;
  44. /** This is the list of circpad_machine_t's parsed from consensus and torrc
  45. * that have origin_side == 0 (ie: are for relay side) */
  46. STATIC smartlist_t *relay_padding_machines = NULL;
  47. /** Loop over the current padding state machines using <b>loop_var</b> as the
  48. * loop variable. */
  49. #define FOR_EACH_CIRCUIT_MACHINE_BEGIN(loop_var) \
  50. STMT_BEGIN \
  51. for (int loop_var = 0; loop_var < CIRCPAD_MAX_MACHINES; loop_var++) {
  52. #define FOR_EACH_CIRCUIT_MACHINE_END } STMT_END ;
  53. /** Loop over the current active padding state machines using <b>loop_var</b>
  54. * as the loop variable. If a machine is not active, skip it. */
  55. #define FOR_EACH_ACTIVE_CIRCUIT_MACHINE_BEGIN(loop_var, circ) \
  56. FOR_EACH_CIRCUIT_MACHINE_BEGIN(loop_var) \
  57. if (!(circ)->padding_info[loop_var]) \
  58. continue;
  59. #define FOR_EACH_ACTIVE_CIRCUIT_MACHINE_END } STMT_END ;
  60. /**
  61. * Return a human-readable description for a circuit padding state.
  62. */
  63. static const char *
  64. circpad_state_to_string(circpad_statenum_t state)
  65. {
  66. const char *descr;
  67. switch (state) {
  68. case CIRCPAD_STATE_START:
  69. descr = "START";
  70. break;
  71. case CIRCPAD_STATE_BURST:
  72. descr = "BURST";
  73. break;
  74. case CIRCPAD_STATE_GAP:
  75. descr = "GAP";
  76. break;
  77. case CIRCPAD_STATE_END:
  78. descr = "END";
  79. break;
  80. default:
  81. descr = "CUSTOM"; // XXX: Just return # in static char buf?
  82. }
  83. return descr;
  84. }
  85. /**
  86. * Free the machineinfo at an index
  87. */
  88. static void
  89. circpad_circuit_machineinfo_free_idx(circuit_t *circ, int idx)
  90. {
  91. if (circ->padding_info[idx]) {
  92. tor_free(circ->padding_info[idx]->histogram);
  93. timer_free(circ->padding_info[idx]->padding_timer);
  94. tor_free(circ->padding_info[idx]);
  95. }
  96. }
  97. /** Free all the machineinfos in <b>circ</b> that match <b>machine_num</b>. */
  98. static void
  99. free_circ_machineinfos_with_machine_num(circuit_t *circ, int machine_num)
  100. {
  101. FOR_EACH_CIRCUIT_MACHINE_BEGIN(i) {
  102. if (circ->padding_machine[i] &&
  103. circ->padding_machine[i]->machine_num == machine_num) {
  104. circpad_circuit_machineinfo_free_idx(circ, i);
  105. circ->padding_machine[i] = NULL;
  106. }
  107. } FOR_EACH_CIRCUIT_MACHINE_END;
  108. }
  109. /**
  110. * Free all padding machines and mutable info associated with circuit
  111. */
  112. void
  113. circpad_circuit_free_all_machineinfos(circuit_t *circ)
  114. {
  115. FOR_EACH_CIRCUIT_MACHINE_BEGIN(i) {
  116. circpad_circuit_machineinfo_free_idx(circ, i);
  117. } FOR_EACH_CIRCUIT_MACHINE_END;
  118. }
  119. /**
  120. * Allocate a new mutable machineinfo structure.
  121. */
  122. STATIC circpad_machineinfo_t *
  123. circpad_circuit_machineinfo_new(circuit_t *on_circ, int machine_index)
  124. {
  125. circpad_machineinfo_t *mi = tor_malloc_zero(sizeof(circpad_machineinfo_t));
  126. mi->machine_index = machine_index;
  127. mi->on_circ = on_circ;
  128. return mi;
  129. }
  130. /**
  131. * Return the circpad_state_t for the current state based on the
  132. * mutable info.
  133. *
  134. * This function returns NULL when the machine is in the end state or in an
  135. * invalid state.
  136. */
  137. STATIC const circpad_state_t *
  138. circpad_machine_current_state(circpad_machineinfo_t *mi)
  139. {
  140. const circpad_machine_t *machine = CIRCPAD_GET_MACHINE(mi);
  141. if (mi->current_state == CIRCPAD_STATE_END) {
  142. return NULL;
  143. } else if (BUG(mi->current_state >= machine->num_states)) {
  144. log_fn(LOG_WARN,LD_CIRC,
  145. "Invalid circuit padding state %d",
  146. mi->current_state);
  147. return NULL;
  148. }
  149. return &machine->states[mi->current_state];
  150. }
  151. /**
  152. * Calculate the lower bound of a histogram bin. The upper bound
  153. * is obtained by calling this function with bin+1, and subtracting 1.
  154. *
  155. * The 0th bin has a special value -- it only represents start_usec.
  156. * This is so we can specify a probability on 0-delay values.
  157. *
  158. * After bin 0, bins are exponentially spaced, so that each subsequent
  159. * bin is twice as large as the previous. This is done so that higher
  160. * time resolution is given to lower time values.
  161. *
  162. * The infinity bin is a the last bin in the array (histogram_len-1).
  163. * It has a usec value of CIRCPAD_DELAY_INFINITE (UINT32_MAX).
  164. */
  165. STATIC circpad_delay_t
  166. circpad_histogram_bin_to_usec(circpad_machineinfo_t *mi,
  167. circpad_hist_index_t bin)
  168. {
  169. const circpad_state_t *state = circpad_machine_current_state(mi);
  170. circpad_delay_t start_usec;
  171. /* Our state should have been checked to be non-null by the caller
  172. * (circpad_machine_remove_token()) */
  173. if (BUG(state == NULL)) {
  174. return CIRCPAD_DELAY_INFINITE;
  175. }
  176. if (state->use_rtt_estimate)
  177. start_usec = mi->rtt_estimate_usec+state->start_usec;
  178. else
  179. start_usec = state->start_usec;
  180. if (bin >= CIRCPAD_INFINITY_BIN(state))
  181. return CIRCPAD_DELAY_INFINITE;
  182. if (bin == 0)
  183. return start_usec;
  184. if (bin == 1)
  185. return start_usec+1;
  186. /* The bin widths double every index, so that we can have more resolution
  187. * for lower time values in the histogram. */
  188. const circpad_time_t bin_width_exponent =
  189. 1 << (CIRCPAD_INFINITY_BIN(state) - bin);
  190. return (circpad_delay_t)MIN(start_usec +
  191. state->range_usec/bin_width_exponent,
  192. CIRCPAD_DELAY_INFINITE);
  193. }
  194. /**
  195. * Return the bin that contains the usec argument.
  196. * "Contains" is defined as us in [lower, upper).
  197. *
  198. * This function will never return the infinity bin (histogram_len-1),
  199. * in order to simplify the rest of the code.
  200. *
  201. * This means that technically the last bin (histogram_len-2)
  202. * has range [start_usec+range_usec, CIRCPAD_DELAY_INFINITE].
  203. */
  204. STATIC circpad_hist_index_t
  205. circpad_histogram_usec_to_bin(const circpad_machineinfo_t *mi,
  206. circpad_delay_t usec)
  207. {
  208. const circpad_state_t *state = circpad_machine_current_state(mi);
  209. circpad_delay_t start_usec;
  210. int32_t bin; /* Larger than return type to properly clamp overflow */
  211. /* Our state should have been checked to be non-null by the caller
  212. * (circpad_machine_remove_token()) */
  213. if (BUG(state == NULL)) {
  214. return 0;
  215. }
  216. if (state->use_rtt_estimate)
  217. start_usec = mi->rtt_estimate_usec+state->start_usec;
  218. else
  219. start_usec = state->start_usec;
  220. if (usec <= start_usec)
  221. return 0;
  222. if (usec == start_usec+1)
  223. return 1;
  224. const circpad_time_t histogram_range_usec = state->range_usec;
  225. /* We need to find the bin corresponding to our position in the range.
  226. * Since bins are exponentially spaced in powers of two, we need to
  227. * take the log2 of our position in histogram_range_usec. However,
  228. * since tor_log2() returns the floor(log2(u64)), we have to adjust
  229. * it to behave like ceil(log2(u64)). This is verified in our tests
  230. * to properly invert the operation done in
  231. * circpad_histogram_bin_to_usec(). */
  232. bin = CIRCPAD_INFINITY_BIN(state) -
  233. tor_log2(2*histogram_range_usec/(usec-start_usec+1));
  234. /* Clamp the return value to account for timevals before the start
  235. * of bin 0, or after the last bin. Don't return the infinity bin
  236. * index. */
  237. bin = MIN(MAX(bin, 1), CIRCPAD_INFINITY_BIN(state)-1);
  238. return bin;
  239. }
  240. /**
  241. * This function frees any token bins allocated from a previous state
  242. *
  243. * Called after a state transition, or if the bins are empty.
  244. */
  245. STATIC void
  246. circpad_machine_setup_tokens(circpad_machineinfo_t *mi)
  247. {
  248. const circpad_state_t *state = circpad_machine_current_state(mi);
  249. /* If this state doesn't exist, or doesn't have token removal,
  250. * free any previous state's histogram, and bail */
  251. if (!state || state->token_removal == CIRCPAD_TOKEN_REMOVAL_NONE) {
  252. if (mi->histogram) {
  253. tor_free(mi->histogram);
  254. mi->histogram = NULL;
  255. mi->histogram_len = 0;
  256. }
  257. return;
  258. }
  259. /* Try to avoid re-mallocing if we don't really need to */
  260. if (!mi->histogram || (mi->histogram
  261. && mi->histogram_len != state->histogram_len)) {
  262. tor_free(mi->histogram); // null ok
  263. mi->histogram = tor_malloc_zero(sizeof(circpad_hist_token_t)
  264. *state->histogram_len);
  265. }
  266. mi->histogram_len = state->histogram_len;
  267. memcpy(mi->histogram, state->histogram,
  268. sizeof(circpad_hist_token_t)*state->histogram_len);
  269. }
  270. /**
  271. * Choose a length for this state (in cells), if specified.
  272. */
  273. static void
  274. circpad_choose_state_length(circpad_machineinfo_t *mi)
  275. {
  276. const circpad_state_t *state = circpad_machine_current_state(mi);
  277. double length;
  278. if (!state || state->length_dist.type == CIRCPAD_DIST_NONE) {
  279. mi->state_length = CIRCPAD_STATE_LENGTH_INFINITE;
  280. return;
  281. }
  282. length = circpad_distribution_sample(state->length_dist);
  283. length = MAX(0, length);
  284. length += state->start_length;
  285. length = MIN(length, state->max_length);
  286. mi->state_length = clamp_double_to_int64(length);
  287. }
  288. /**
  289. * Sample a value from our iat_dist, and clamp it safely
  290. * to circpad_delay_t.
  291. */
  292. static circpad_delay_t
  293. circpad_distribution_sample_iat_delay(const circpad_state_t *state,
  294. circpad_delay_t start_usec)
  295. {
  296. double val = circpad_distribution_sample(state->iat_dist);
  297. /* These comparisons are safe, because the output is in the range
  298. * [0, 2**32), and double has a precision of 53 bits. */
  299. val = MAX(0, val);
  300. val = MIN(val, state->range_usec);
  301. /* This addition is exact: val is at most 2**32-1, start_usec
  302. * is at most 2**32-1, and doubles have a precision of 53 bits. */
  303. val += start_usec;
  304. /* Clamp the distribution at infinite delay val */
  305. return (circpad_delay_t)MIN(tor_llround(val), CIRCPAD_DELAY_INFINITE);
  306. }
  307. /**
  308. * Sample an expected time-until-next-packet delay from the histogram.
  309. *
  310. * The bin is chosen with probability proportional to the number
  311. * of tokens in each bin, and then a time value is chosen uniformly from
  312. * that bin's [start,end) time range.
  313. */
  314. static circpad_delay_t
  315. circpad_machine_sample_delay(circpad_machineinfo_t *mi)
  316. {
  317. const circpad_state_t *state = circpad_machine_current_state(mi);
  318. const circpad_hist_token_t *histogram = NULL;
  319. circpad_hist_index_t curr_bin = 0;
  320. circpad_delay_t bin_start, bin_end;
  321. circpad_delay_t start_usec;
  322. /* These three must all be larger than circpad_hist_token_t, because
  323. * we sum several circpad_hist_token_t values across the histogram */
  324. uint64_t curr_weight = 0;
  325. uint64_t histogram_total_tokens = 0;
  326. uint64_t bin_choice;
  327. tor_assert(state);
  328. if (state->use_rtt_estimate)
  329. start_usec = mi->rtt_estimate_usec+state->start_usec;
  330. else
  331. start_usec = state->start_usec;
  332. if (state->iat_dist.type != CIRCPAD_DIST_NONE) {
  333. /* Sample from a fixed IAT distribution and return */
  334. return circpad_distribution_sample_iat_delay(state, start_usec);
  335. } else if (state->token_removal != CIRCPAD_TOKEN_REMOVAL_NONE) {
  336. /* We have a mutable histogram. Do basic sanity check and apply: */
  337. if (BUG(!mi->histogram) ||
  338. BUG(mi->histogram_len != state->histogram_len)) {
  339. return CIRCPAD_DELAY_INFINITE;
  340. }
  341. histogram = mi->histogram;
  342. for (circpad_hist_index_t b = 0; b < state->histogram_len; b++)
  343. histogram_total_tokens += histogram[b];
  344. } else {
  345. /* We have a histogram, but it's immutable */
  346. histogram = state->histogram;
  347. histogram_total_tokens = state->histogram_total_tokens;
  348. }
  349. bin_choice = crypto_rand_uint64(histogram_total_tokens);
  350. /* Skip all the initial zero bins */
  351. while (!histogram[curr_bin]) {
  352. curr_bin++;
  353. }
  354. curr_weight = histogram[curr_bin];
  355. // TODO: This is not constant-time. Pretty sure we don't
  356. // really need it to be, though.
  357. while (curr_weight < bin_choice) {
  358. curr_bin++;
  359. /* It should be impossible to run past the end of the histogram */
  360. if (BUG(curr_bin >= state->histogram_len)) {
  361. return CIRCPAD_DELAY_INFINITE;
  362. }
  363. curr_weight += histogram[curr_bin];
  364. }
  365. /* Do some basic checking of the current bin we are in */
  366. if (BUG(curr_bin >= state->histogram_len) ||
  367. BUG(histogram[curr_bin] == 0)) {
  368. return CIRCPAD_DELAY_INFINITE;
  369. }
  370. // Store this index to remove the token upon callback.
  371. if (state->token_removal != CIRCPAD_TOKEN_REMOVAL_NONE) {
  372. mi->chosen_bin = curr_bin;
  373. }
  374. if (curr_bin >= CIRCPAD_INFINITY_BIN(state)) {
  375. if (state->token_removal != CIRCPAD_TOKEN_REMOVAL_NONE &&
  376. mi->histogram[curr_bin] > 0) {
  377. mi->histogram[curr_bin]--;
  378. }
  379. // Infinity: Don't send a padding packet. Wait for a real packet
  380. // and then see if our bins are empty or what else we should do.
  381. return CIRCPAD_DELAY_INFINITE;
  382. }
  383. tor_assert(curr_bin < CIRCPAD_INFINITY_BIN(state));
  384. bin_start = circpad_histogram_bin_to_usec(mi, curr_bin);
  385. bin_end = circpad_histogram_bin_to_usec(mi, curr_bin+1);
  386. /* Truncate the high bin in case it's the infinity bin:
  387. * Don't actually schedule an "infinite"-1 delay */
  388. bin_end = MIN(bin_end, start_usec+state->range_usec);
  389. // Sample uniformly between histogram[i] to histogram[i+1]-1,
  390. // but no need to sample if they are the same timeval (aka bin 0 or bin 1).
  391. if (bin_end <= bin_start+1)
  392. return bin_start;
  393. else
  394. return (circpad_delay_t)crypto_rand_uint64_range(bin_start, bin_end);
  395. }
  396. /**
  397. * Sample a value from the specified probability distribution.
  398. *
  399. * This performs inverse transform sampling
  400. * (https://en.wikipedia.org/wiki/Inverse_transform_sampling).
  401. *
  402. * XXX: These formulas were taken verbatim. Need a floating wizard
  403. * to check them for catastropic cancellation and other issues (teor?).
  404. * Also: is 32bits of double from [0.0,1.0) enough?
  405. */
  406. static double
  407. circpad_distribution_sample(circpad_distribution_t dist)
  408. {
  409. double p = 0;
  410. switch (dist.type) {
  411. case CIRCPAD_DIST_NONE:
  412. return 0;
  413. case CIRCPAD_DIST_UNIFORM:
  414. p = crypto_rand_double();
  415. // param2 is upper bound, param1 is lower
  416. /* The subtraction is exact as long as param2 and param1 are less than
  417. * 2**53. The multiplication is accurate as long as (param2 - param1)
  418. * is less than 2**52. (And when they are large, the low bits aren't
  419. * important.) The result covers the full range of outputs, as long as
  420. * p has a resolution of 1/2**32 or greater. */
  421. p *= (dist.param2 - dist.param1);
  422. p += dist.param1;
  423. return p;
  424. case CIRCPAD_DIST_LOGISTIC:
  425. p = crypto_rand_double();
  426. /* https://en.wikipedia.org/wiki/Logistic_distribution#Quantile_function
  427. * param1 is Mu, param2 is s. */
  428. if (p <= 0.0) // Avoid log(0)
  429. return 0;
  430. return dist.param1 + dist.param2*tor_mathlog(p/(1.0-p));
  431. case CIRCPAD_DIST_LOG_LOGISTIC:
  432. p = crypto_rand_double();
  433. /* https://en.wikipedia.org/wiki/Log-logistic_distribution#Quantiles
  434. * param1 is Alpha, param2 is Beta */
  435. return dist.param1 * pow(p/(1.0-p), 1.0/dist.param2);
  436. case CIRCPAD_DIST_GEOMETRIC:
  437. p = crypto_rand_double();
  438. /* https://github.com/distributions-io/geometric-quantile/
  439. * param1 is 'p' (success probability) */
  440. return ceil(tor_mathlog(1.0-p)/tor_mathlog(1.0-dist.param1));
  441. case CIRCPAD_DIST_WEIBULL:
  442. p = crypto_rand_double();
  443. /* https://en.wikipedia.org/wiki/Weibull_distribution \
  444. * #Cumulative_distribution_function
  445. * param1 is k, param2 is Lambda */
  446. return dist.param2*pow(-tor_mathlog(1.0-p), 1.0/dist.param1);
  447. case CIRCPAD_DIST_PARETO:
  448. p = 1.0-crypto_rand_double(); // Pareto quantile needs (0,1]
  449. /* https://en.wikipedia.org/wiki/Generalized_Pareto_distribution \
  450. * #Generating_generalized_Pareto_random_variables
  451. * param1 is Sigma, param2 is Xi
  452. * Since it's piecewise, we must define it for 0 (or close to 0) */
  453. if (fabs(dist.param2) <= 1e-22)
  454. return -dist.param1*tor_mathlog(p);
  455. else
  456. return dist.param1*(pow(p, -dist.param2) - 1.0)/dist.param2;
  457. }
  458. return 0;
  459. }
  460. /**
  461. * Find the index of the first bin whose upper bound is
  462. * greater than the target, and that has tokens remaining.
  463. */
  464. static circpad_hist_index_t
  465. circpad_machine_first_higher_index(circpad_machineinfo_t *mi,
  466. circpad_delay_t target_bin_usec)
  467. {
  468. circpad_hist_index_t bin = circpad_histogram_usec_to_bin(mi,
  469. target_bin_usec);
  470. /* Don't remove from the infinity bin */
  471. for (; bin < CIRCPAD_INFINITY_BIN(mi); bin++) {
  472. if (mi->histogram[bin] &&
  473. circpad_histogram_bin_to_usec(mi, bin+1) > target_bin_usec) {
  474. return bin;
  475. }
  476. }
  477. return mi->histogram_len;
  478. }
  479. /**
  480. * Find the index of the first bin whose lower bound is lower or equal to
  481. * <b>target_bin_usec</b>, and that still has tokens remaining.
  482. */
  483. static circpad_hist_index_t
  484. circpad_machine_first_lower_index(circpad_machineinfo_t *mi,
  485. circpad_delay_t target_bin_usec)
  486. {
  487. circpad_hist_index_t bin = circpad_histogram_usec_to_bin(mi,
  488. target_bin_usec);
  489. for (; bin >= 0; bin--) {
  490. if (mi->histogram[bin] &&
  491. circpad_histogram_bin_to_usec(mi, bin) <= target_bin_usec) {
  492. return bin;
  493. }
  494. }
  495. return -1;
  496. }
  497. /**
  498. * Remove a token from the first non-empty bin whose upper bound is
  499. * greater than the target.
  500. */
  501. STATIC void
  502. circpad_machine_remove_higher_token(circpad_machineinfo_t *mi,
  503. circpad_delay_t target_bin_usec)
  504. {
  505. /* We need to remove the token from the first bin
  506. * whose upper bound is greater than the target, and that
  507. * has tokens remaining. */
  508. circpad_hist_index_t bin = circpad_machine_first_higher_index(mi,
  509. target_bin_usec);
  510. if (bin >= 0 && bin < CIRCPAD_INFINITY_BIN(mi)) {
  511. if (!BUG(mi->histogram[bin] == 0)) {
  512. mi->histogram[bin]--;
  513. }
  514. }
  515. }
  516. /**
  517. * Remove a token from the first non-empty bin whose upper bound is
  518. * lower than the target.
  519. */
  520. STATIC void
  521. circpad_machine_remove_lower_token(circpad_machineinfo_t *mi,
  522. circpad_delay_t target_bin_usec)
  523. {
  524. circpad_hist_index_t bin = circpad_machine_first_lower_index(mi,
  525. target_bin_usec);
  526. if (bin >= 0 && bin < CIRCPAD_INFINITY_BIN(mi)) {
  527. if (!BUG(mi->histogram[bin] == 0)) {
  528. mi->histogram[bin]--;
  529. }
  530. }
  531. }
  532. /* Helper macro: Ensure that the bin has tokens available, and BUG out of the
  533. * function if it's not the case. */
  534. #define ENSURE_BIN_CAPACITY(bin_index) \
  535. if (BUG(mi->histogram[bin_index] == 0)) { \
  536. return; \
  537. }
  538. /**
  539. * Remove a token from the closest non-empty bin to the target.
  540. *
  541. * If use_usec is true, measure "closest" in terms of bin start usec.
  542. * If it is false, use bin index distance only.
  543. */
  544. STATIC void
  545. circpad_machine_remove_closest_token(circpad_machineinfo_t *mi,
  546. circpad_delay_t target_bin_usec,
  547. bool use_usec)
  548. {
  549. circpad_hist_index_t lower, higher, current;
  550. circpad_hist_index_t bin_to_remove = -1;
  551. lower = circpad_machine_first_lower_index(mi, target_bin_usec);
  552. higher = circpad_machine_first_higher_index(mi, target_bin_usec);
  553. current = circpad_histogram_usec_to_bin(mi, target_bin_usec);
  554. /* Sanity check the results */
  555. if (BUG(lower > current) || BUG(higher < current)) {
  556. return;
  557. }
  558. if (higher == mi->histogram_len && lower == -1) {
  559. // Bins are empty
  560. return;
  561. } else if (higher == mi->histogram_len) {
  562. /* All higher bins are empty */
  563. ENSURE_BIN_CAPACITY(lower);
  564. mi->histogram[lower]--;
  565. return;
  566. } else if (lower == -1) {
  567. /* All lower bins are empty */
  568. ENSURE_BIN_CAPACITY(higher);
  569. mi->histogram[higher]--;
  570. return;
  571. }
  572. if (use_usec) {
  573. /* Find the closest bin midpoint to the target */
  574. circpad_delay_t lower_usec = circpad_get_histogram_bin_midpoint(mi, lower);
  575. circpad_delay_t higher_usec =
  576. circpad_get_histogram_bin_midpoint(mi, higher);
  577. if (target_bin_usec < lower_usec) {
  578. // Lower bin is closer
  579. ENSURE_BIN_CAPACITY(lower);
  580. bin_to_remove = lower;
  581. } else if (target_bin_usec > higher_usec) {
  582. // Higher bin is closer
  583. ENSURE_BIN_CAPACITY(higher);
  584. bin_to_remove = higher;
  585. } else if (target_bin_usec-lower_usec > higher_usec-target_bin_usec) {
  586. // Higher bin is closer
  587. ENSURE_BIN_CAPACITY(higher);
  588. bin_to_remove = higher;
  589. } else {
  590. // Lower bin is closer
  591. ENSURE_BIN_CAPACITY(lower);
  592. bin_to_remove = lower;
  593. }
  594. } else {
  595. if (current - lower > higher - current) {
  596. // Higher bin is closer
  597. ENSURE_BIN_CAPACITY(higher);
  598. mi->histogram[higher]--;
  599. return;
  600. } else {
  601. // Lower bin is closer
  602. ENSURE_BIN_CAPACITY(lower);
  603. mi->histogram[lower]--;
  604. return;
  605. }
  606. }
  607. }
  608. #undef ENSURE_BIN_CAPACITY
  609. /**
  610. * Remove a token from the exact bin corresponding to the target.
  611. *
  612. * If it is empty, do nothing.
  613. */
  614. static void
  615. circpad_machine_remove_exact(circpad_machineinfo_t *mi,
  616. circpad_delay_t target_bin_usec)
  617. {
  618. circpad_hist_index_t bin = circpad_histogram_usec_to_bin(mi,
  619. target_bin_usec);
  620. if (mi->histogram[bin] > 0)
  621. mi->histogram[bin]--;
  622. }
  623. /**
  624. * Check our state's cell limit count and tokens.
  625. *
  626. * Returns 1 if either limits are hit and we decide to change states,
  627. * otherwise returns 0.
  628. */
  629. static circpad_decision_t
  630. check_machine_token_supply(circpad_machineinfo_t *mi)
  631. {
  632. uint32_t histogram_total_tokens = 0;
  633. /* Check if bins empty. This requires summing up the current mutable
  634. * machineinfo histogram token total and checking if it is zero.
  635. * Machineinfo does not keep a running token count. We're assuming the
  636. * extra space is not worth this short loop iteration.
  637. *
  638. * We also do not count infinity bin in histogram totals.
  639. */
  640. if (mi->histogram_len && mi->histogram) {
  641. for (circpad_hist_index_t b = 0; b < CIRCPAD_INFINITY_BIN(mi); b++)
  642. histogram_total_tokens += mi->histogram[b];
  643. /* If we change state, we're done */
  644. if (histogram_total_tokens == 0) {
  645. if (circpad_internal_event_bins_empty(mi) == CIRCPAD_STATE_CHANGED)
  646. return CIRCPAD_STATE_CHANGED;
  647. }
  648. }
  649. if (mi->state_length == 0) {
  650. return circpad_internal_event_state_length_up(mi);
  651. }
  652. return CIRCPAD_STATE_UNCHANGED;
  653. }
  654. /**
  655. * Remove a token from the bin corresponding to the delta since
  656. * last packet. If that bin is empty, choose a token based on
  657. * the specified removal strategy in the state machine.
  658. *
  659. * This function also updates and checks rate limit and state
  660. * limit counters.
  661. *
  662. * Returns 1 if we transition states, 0 otherwise.
  663. */
  664. circpad_decision_t
  665. circpad_machine_remove_token(circpad_machineinfo_t *mi)
  666. {
  667. const circpad_state_t *state = NULL;
  668. circpad_time_t current_time;
  669. circpad_delay_t target_bin_usec;
  670. /* Update non-padding counts for rate limiting: We scale at UINT16_MAX
  671. * because we only use this for a percentile limit of 2 sig figs, and
  672. * space is scare in the machineinfo struct. */
  673. mi->nonpadding_sent++;
  674. if (mi->nonpadding_sent == UINT16_MAX) {
  675. mi->padding_sent /= 2;
  676. mi->nonpadding_sent /= 2;
  677. }
  678. /* Dont remove any tokens if there was no padding scheduled */
  679. if (!mi->padding_scheduled_at_usec) {
  680. return CIRCPAD_STATE_UNCHANGED;
  681. }
  682. state = circpad_machine_current_state(mi);
  683. current_time = monotime_absolute_usec();
  684. /* If we have scheduled padding some time in the future, we want to see what
  685. bin we are in at the current time */
  686. target_bin_usec = (circpad_delay_t)
  687. MIN((current_time - mi->padding_scheduled_at_usec),
  688. CIRCPAD_DELAY_INFINITE-1);
  689. /* We are treating this non-padding cell as a padding cell, so we cancel
  690. padding timer, if present. */
  691. mi->padding_scheduled_at_usec = 0;
  692. if (mi->is_padding_timer_scheduled) {
  693. mi->is_padding_timer_scheduled = 0;
  694. timer_disable(mi->padding_timer);
  695. }
  696. /* If we are not in a padding state (like start or end), we're done */
  697. if (!state)
  698. return CIRCPAD_STATE_UNCHANGED;
  699. /* If we're enforcing a state length on non-padding packets,
  700. * decrement it */
  701. if (mi->state_length != CIRCPAD_STATE_LENGTH_INFINITE &&
  702. state->length_includes_nonpadding &&
  703. mi->state_length > 0) {
  704. mi->state_length--;
  705. }
  706. /* Perform the specified token removal strategy */
  707. switch (state->token_removal) {
  708. case CIRCPAD_TOKEN_REMOVAL_NONE:
  709. break;
  710. case CIRCPAD_TOKEN_REMOVAL_CLOSEST_USEC:
  711. circpad_machine_remove_closest_token(mi, target_bin_usec, 1);
  712. break;
  713. case CIRCPAD_TOKEN_REMOVAL_CLOSEST:
  714. circpad_machine_remove_closest_token(mi, target_bin_usec, 0);
  715. break;
  716. case CIRCPAD_TOKEN_REMOVAL_LOWER:
  717. circpad_machine_remove_lower_token(mi, target_bin_usec);
  718. break;
  719. case CIRCPAD_TOKEN_REMOVAL_HIGHER:
  720. circpad_machine_remove_higher_token(mi, target_bin_usec);
  721. break;
  722. case CIRCPAD_TOKEN_REMOVAL_EXACT:
  723. circpad_machine_remove_exact(mi, target_bin_usec);
  724. break;
  725. }
  726. /* Check our token and state length limits */
  727. return check_machine_token_supply(mi);
  728. }
  729. /**
  730. * Send a relay command with a relay cell payload on a circuit to
  731. * the particular hopnum.
  732. *
  733. * Hopnum starts at 1 (1=guard, 2=middle, 3=exit, etc).
  734. *
  735. * Payload may be null.
  736. *
  737. * Returns negative on error, 0 on success.
  738. */
  739. static signed_error_t
  740. circpad_send_command_to_hop(origin_circuit_t *circ, uint8_t hopnum,
  741. uint8_t relay_command, const uint8_t *payload,
  742. ssize_t payload_len)
  743. {
  744. crypt_path_t *target_hop = circuit_get_cpath_hop(circ, hopnum);
  745. signed_error_t ret;
  746. /* Check that the cpath has the target hop */
  747. if (!target_hop) {
  748. log_fn(LOG_WARN, LD_BUG, "Padding circuit %u has %d hops, not %d",
  749. circ->global_identifier, circuit_get_cpath_len(circ), hopnum);
  750. return -1;
  751. }
  752. /* Check that the target hop is opened */
  753. if (target_hop->state != CPATH_STATE_OPEN) {
  754. log_fn(LOG_WARN,LD_CIRC,
  755. "Padding circuit %u has %d hops, not %d",
  756. circ->global_identifier,
  757. circuit_get_cpath_opened_len(circ), hopnum);
  758. return -1;
  759. }
  760. /* Send the drop command to the second hop */
  761. ret = relay_send_command_from_edge(0, TO_CIRCUIT(circ), relay_command,
  762. (const char*)payload, payload_len,
  763. target_hop);
  764. return ret;
  765. }
  766. /**
  767. * Callback helper to send a padding cell.
  768. *
  769. * This helper is called after our histogram-sampled delay period passes
  770. * without another packet being sent first. If a packet is sent before this
  771. * callback happens, it is canceled. So when we're called here, send padding
  772. * right away.
  773. *
  774. * If sending this padding cell forced us to transition states return
  775. * CIRCPAD_STATE_CHANGED. Otherwise return CIRCPAD_STATE_UNCHANGED.
  776. */
  777. circpad_decision_t
  778. circpad_send_padding_cell_for_callback(circpad_machineinfo_t *mi)
  779. {
  780. circuit_t *circ = mi->on_circ;
  781. int machine_idx = mi->machine_index;
  782. mi->padding_scheduled_at_usec = 0;
  783. circpad_statenum_t state = mi->current_state;
  784. // Make sure circuit didn't close on us
  785. if (mi->on_circ->marked_for_close) {
  786. log_fn(LOG_INFO,LD_CIRC,
  787. "Padding callback on a circuit marked for close. Ignoring.");
  788. return CIRCPAD_STATE_CHANGED;
  789. }
  790. /* If it's a histogram, reduce the token count */
  791. if (mi->histogram && mi->histogram_len) {
  792. /* Basic sanity check on the histogram before removing anything */
  793. if (BUG(mi->chosen_bin >= mi->histogram_len) ||
  794. BUG(mi->histogram[mi->chosen_bin] == 0)) {
  795. return CIRCPAD_STATE_CHANGED;
  796. }
  797. mi->histogram[mi->chosen_bin]--;
  798. }
  799. /* If we have a valid state length bound, consider it */
  800. if (mi->state_length != CIRCPAD_STATE_LENGTH_INFINITE &&
  801. !BUG(mi->state_length <= 0)) {
  802. mi->state_length--;
  803. }
  804. /*
  805. * Update non-padding counts for rate limiting: We scale at UINT16_MAX
  806. * because we only use this for a percentile limit of 2 sig figs, and
  807. * space is scare in the machineinfo struct.
  808. */
  809. mi->padding_sent++;
  810. if (mi->padding_sent == UINT16_MAX) {
  811. mi->padding_sent /= 2;
  812. mi->nonpadding_sent /= 2;
  813. }
  814. circpad_global_padding_sent++;
  815. if (CIRCUIT_IS_ORIGIN(mi->on_circ)) {
  816. circpad_send_command_to_hop(TO_ORIGIN_CIRCUIT(mi->on_circ),
  817. CIRCPAD_GET_MACHINE(mi)->target_hopnum,
  818. RELAY_COMMAND_DROP, NULL, 0);
  819. log_fn(LOG_INFO,LD_CIRC, "Callback: Sending padding to origin circuit %u.",
  820. TO_ORIGIN_CIRCUIT(mi->on_circ)->global_identifier);
  821. } else {
  822. // If we're a non-origin circ, we can just send from here as if we're the
  823. // edge.
  824. log_fn(LOG_INFO,LD_CIRC,
  825. "Callback: Sending padding to non-origin circuit.");
  826. relay_send_command_from_edge(0, mi->on_circ, RELAY_COMMAND_DROP, NULL,
  827. 0, NULL);
  828. }
  829. rep_hist_padding_count_write(PADDING_TYPE_DROP);
  830. /* This is a padding cell sent from the client or from the middle node,
  831. * (because it's invoked from circuitpadding.c) */
  832. circpad_cell_event_padding_sent(circ);
  833. /* The circpad_cell_event_padding_sent() could cause us to transition.
  834. * Check that we still have a padding machineinfo, and then check our token
  835. * supply. */
  836. if (circ->padding_info[machine_idx] != NULL) {
  837. if (state != circ->padding_info[machine_idx]->current_state)
  838. return CIRCPAD_STATE_CHANGED;
  839. else
  840. return check_machine_token_supply(circ->padding_info[machine_idx]);
  841. } else {
  842. return CIRCPAD_STATE_CHANGED;
  843. }
  844. }
  845. /**
  846. * Tor-timer compatible callback that tells us to send a padding cell.
  847. *
  848. * Timers are associated with circpad_machineinfo_t's. When the machineinfo
  849. * is freed on a circuit, the timers are cancelled. Since the lifetime
  850. * of machineinfo is always longer than the timers, handles are not
  851. * needed.
  852. */
  853. static void
  854. circpad_send_padding_callback(tor_timer_t *timer, void *args,
  855. const struct monotime_t *time)
  856. {
  857. circpad_machineinfo_t *mi = ((circpad_machineinfo_t*)args);
  858. (void)timer; (void)time;
  859. if (mi && mi->on_circ) {
  860. assert_circuit_ok(mi->on_circ);
  861. circpad_send_padding_cell_for_callback(mi);
  862. } else {
  863. // This shouldn't happen (represents a timer leak)
  864. log_fn(LOG_WARN,LD_CIRC,
  865. "Circuit closed while waiting for padding timer.");
  866. tor_fragile_assert();
  867. }
  868. // TODO-MP-AP: Unify this counter with channelpadding for rephist stats
  869. //total_timers_pending--;
  870. }
  871. /**
  872. * Cache our consensus parameters upon consensus update.
  873. */
  874. void
  875. circpad_new_consensus_params(const networkstatus_t *ns)
  876. {
  877. circpad_global_allowed_cells =
  878. networkstatus_get_param(ns, "circpad_global_allowed_cells",
  879. 0, 0, UINT16_MAX-1);
  880. circpad_global_max_padding_percent =
  881. networkstatus_get_param(ns, "circpad_global_max_padding_pct",
  882. 0, 0, 100);
  883. }
  884. /**
  885. * Check this machine against its padding limits, as well as global
  886. * consensus limits.
  887. *
  888. * We have two limits: a percent and a cell count. The cell count
  889. * limit must be reached before the percent is enforced (this is to
  890. * optionally allow very light padding of things like circuit setup
  891. * while there is no other traffic on the circuit).
  892. *
  893. * TODO: Don't apply limits to machines form torrc.
  894. *
  895. * Returns 1 if limits are set and we've hit them. Otherwise returns 0.
  896. */
  897. static bool
  898. circpad_machine_reached_padding_limit(circpad_machineinfo_t *mi)
  899. {
  900. const circpad_machine_t *machine = CIRCPAD_GET_MACHINE(mi);
  901. /* If machine_padding_pct is non-zero, and we've sent more
  902. * than the allowed count of padding cells, then check our
  903. * percent limits for this machine. */
  904. if (machine->max_padding_percent &&
  905. mi->padding_sent >= machine->allowed_padding_count) {
  906. uint32_t total_cells = mi->padding_sent + mi->nonpadding_sent;
  907. /* Check the percent */
  908. if ((100*(uint32_t)mi->padding_sent) / total_cells >
  909. machine->max_padding_percent) {
  910. return 1; // limit is reached. Stop.
  911. }
  912. }
  913. /* If circpad_max_global_padding_pct is non-zero, and we've
  914. * sent more than the global padding cell limit, then check our
  915. * gloabl tor process percentage limit on padding. */
  916. if (circpad_global_max_padding_percent &&
  917. circpad_global_padding_sent >= circpad_global_allowed_cells) {
  918. uint64_t total_cells = circpad_global_padding_sent +
  919. circpad_global_nonpadding_sent;
  920. /* Check the percent */
  921. if ((100*circpad_global_padding_sent) / total_cells >
  922. circpad_global_max_padding_percent) {
  923. return 1; // global limit reached. Stop.
  924. }
  925. }
  926. return 0; // All good!
  927. }
  928. /**
  929. * Schedule the next padding time according to the machineinfo on a
  930. * circuit.
  931. *
  932. * The histograms represent inter-packet-delay. Whenever you get an packet
  933. * event you should be scheduling your next timer (after cancelling any old
  934. * ones and updating tokens accordingly).
  935. *
  936. * Returns 1 if we decide to transition states (due to infinity bin),
  937. * 0 otherwise.
  938. */
  939. circpad_decision_t
  940. circpad_machine_schedule_padding(circpad_machineinfo_t *mi)
  941. {
  942. circpad_delay_t in_usec = 0;
  943. struct timeval timeout;
  944. tor_assert(mi);
  945. // Don't pad in end (but also don't cancel any previously
  946. // scheduled padding either).
  947. if (mi->current_state == CIRCPAD_STATE_END) {
  948. log_fn(LOG_INFO, LD_CIRC, "Padding end state");
  949. return CIRCPAD_STATE_UNCHANGED;
  950. }
  951. /* Check our padding limits */
  952. if (circpad_machine_reached_padding_limit(mi)) {
  953. if (CIRCUIT_IS_ORIGIN(mi->on_circ)) {
  954. log_fn(LOG_INFO, LD_CIRC,
  955. "Padding machine has reached padding limit on circuit %u",
  956. TO_ORIGIN_CIRCUIT(mi->on_circ)->global_identifier);
  957. } else {
  958. log_fn(LOG_INFO, LD_CIRC,
  959. "Padding machine has reached padding limit on circuit %"PRIu64
  960. ", %d",
  961. mi->on_circ->n_chan ? mi->on_circ->n_chan->global_identifier : 0,
  962. mi->on_circ->n_circ_id);
  963. }
  964. return CIRCPAD_STATE_UNCHANGED;
  965. }
  966. if (mi->is_padding_timer_scheduled) {
  967. /* Cancel current timer (if any) */
  968. timer_disable(mi->padding_timer);
  969. mi->is_padding_timer_scheduled = 0;
  970. }
  971. /* in_usec = in microseconds */
  972. in_usec = circpad_machine_sample_delay(mi);
  973. mi->padding_scheduled_at_usec = monotime_absolute_usec();
  974. log_fn(LOG_INFO,LD_CIRC,"\tPadding in %u usec", in_usec);
  975. // Don't schedule if we have infinite delay.
  976. if (in_usec == CIRCPAD_DELAY_INFINITE) {
  977. return circpad_internal_event_infinity(mi);
  978. }
  979. if (mi->state_length == 0) {
  980. /* If we're at length 0, that means we hit 0 after sending
  981. * a cell earlier, and emitted an event for it, but
  982. * for whatever reason we did not decide to change states then.
  983. * So maybe the machine is waiting for bins empty, or for an
  984. * infinity event later? That would be a strange machine,
  985. * but there's no reason to make it impossible. */
  986. return CIRCPAD_STATE_UNCHANGED;
  987. }
  988. if (in_usec <= 0) {
  989. return circpad_send_padding_cell_for_callback(mi);
  990. }
  991. timeout.tv_sec = in_usec/TOR_USEC_PER_SEC;
  992. timeout.tv_usec = (in_usec%TOR_USEC_PER_SEC);
  993. log_fn(LOG_INFO, LD_CIRC, "\tPadding in %u sec, %u usec",
  994. (unsigned)timeout.tv_sec, (unsigned)timeout.tv_usec);
  995. if (mi->padding_timer) {
  996. timer_set_cb(mi->padding_timer, circpad_send_padding_callback, mi);
  997. } else {
  998. mi->padding_timer =
  999. timer_new(circpad_send_padding_callback, mi);
  1000. }
  1001. timer_schedule(mi->padding_timer, &timeout);
  1002. mi->is_padding_timer_scheduled = 1;
  1003. // TODO-MP-AP: Unify with channelpadding counter
  1004. //rep_hist_padding_count_timers(++total_timers_pending);
  1005. return CIRCPAD_STATE_UNCHANGED;
  1006. }
  1007. /**
  1008. * If the machine transitioned to the END state, we need
  1009. * to check to see if it wants us to shut it down immediately.
  1010. * If it does, then we need to send the appropate negotation commands
  1011. * depending on which side it is.
  1012. *
  1013. * After this function is called, mi may point to freed memory. Do
  1014. * not access it.
  1015. */
  1016. static void
  1017. circpad_machine_transitioned_to_end(circpad_machineinfo_t *mi)
  1018. {
  1019. const circpad_machine_t *machine = CIRCPAD_GET_MACHINE(mi);
  1020. /*
  1021. * We allow machines to shut down and delete themselves as opposed
  1022. * to just going back to START or waiting forever in END so that
  1023. * we can handle the case where this machine started while it was
  1024. * the only machine that matched conditions, but *since* then more
  1025. * "higher ranking" machines now match the conditions, and would
  1026. * be given a chance to take precidence over this one in
  1027. * circpad_add_matching_machines().
  1028. *
  1029. * Returning to START or waiting forever in END would not give those
  1030. * other machines a chance to be launched, where as shutting down
  1031. * here does.
  1032. */
  1033. if (machine->should_negotiate_end) {
  1034. circuit_t *on_circ = mi->on_circ;
  1035. if (machine->is_origin_side) {
  1036. /* We free the machine info here so that we can be replaced
  1037. * by a different machine. But we must leave the padding_machine
  1038. * in place to wait for the negotiated response */
  1039. circpad_circuit_machineinfo_free_idx(on_circ,
  1040. machine->machine_index);
  1041. circpad_negotiate_padding(TO_ORIGIN_CIRCUIT(on_circ),
  1042. machine->machine_num,
  1043. machine->target_hopnum,
  1044. CIRCPAD_COMMAND_STOP);
  1045. } else {
  1046. circpad_circuit_machineinfo_free_idx(on_circ,
  1047. machine->machine_index);
  1048. circpad_padding_negotiated(on_circ,
  1049. machine->machine_num,
  1050. CIRCPAD_COMMAND_STOP,
  1051. CIRCPAD_RESPONSE_OK);
  1052. on_circ->padding_machine[machine->machine_index] = NULL;
  1053. }
  1054. }
  1055. }
  1056. /**
  1057. * Generic state transition function for padding state machines.
  1058. *
  1059. * Given an event and our mutable machine info, decide if/how to
  1060. * transition to a different state, and perform actions accordingly.
  1061. *
  1062. * Returns 1 if we transition states, 0 otherwise.
  1063. */
  1064. circpad_decision_t
  1065. circpad_machine_transition(circpad_machineinfo_t *mi,
  1066. circpad_event_t event)
  1067. {
  1068. const circpad_state_t *state =
  1069. circpad_machine_current_state(mi);
  1070. /* If state is null we are in the end state. */
  1071. if (!state) {
  1072. /* If we in end state we don't pad no matter what. */
  1073. return CIRCPAD_STATE_UNCHANGED;
  1074. }
  1075. /* Check if this event is ignored or causes a cancel */
  1076. if (state->next_state[event] == CIRCPAD_STATE_IGNORE) {
  1077. return CIRCPAD_STATE_UNCHANGED;
  1078. } else if (state->next_state[event] == CIRCPAD_STATE_CANCEL) {
  1079. /* Check cancel events and cancel any pending padding */
  1080. mi->padding_scheduled_at_usec = 0;
  1081. if (mi->is_padding_timer_scheduled) {
  1082. mi->is_padding_timer_scheduled = 0;
  1083. /* Cancel current timer (if any) */
  1084. timer_disable(mi->padding_timer);
  1085. }
  1086. return CIRCPAD_STATE_UNCHANGED;
  1087. } else {
  1088. circpad_statenum_t s = state->next_state[event];
  1089. /* See if we need to transition to any other states based on this event.
  1090. * Whenever a transition happens, even to our own state, we schedule
  1091. * padding.
  1092. *
  1093. * So if a state only wants to schedule padding for an event, it specifies
  1094. * a transition to itself. All non-specified events are ignored.
  1095. */
  1096. log_fn(LOG_INFO, LD_CIRC,
  1097. "Circpad machine %d transitioning from %s to %s",
  1098. mi->machine_index, circpad_state_to_string(mi->current_state),
  1099. circpad_state_to_string(s));
  1100. /* If this is not the same state, switch and init tokens,
  1101. * otherwise just reschedule padding. */
  1102. if (mi->current_state != s) {
  1103. mi->current_state = s;
  1104. circpad_machine_setup_tokens(mi);
  1105. circpad_choose_state_length(mi);
  1106. /* If we transition to the end state, check to see
  1107. * if this machine wants to be shut down at end */
  1108. if (s == CIRCPAD_STATE_END) {
  1109. circpad_machine_transitioned_to_end(mi);
  1110. /* We transitioned but we don't pad in end. Also, mi
  1111. * may be freed. Returning STATE_CHANGED prevents us
  1112. * from accessing it in any callers of this function. */
  1113. return CIRCPAD_STATE_CHANGED;
  1114. }
  1115. /* We transitioned to a new state, schedule padding */
  1116. circpad_machine_schedule_padding(mi);
  1117. return CIRCPAD_STATE_CHANGED;
  1118. }
  1119. /* We transitioned back to the same state. Schedule padding,
  1120. * and inform if that causes a state transition. */
  1121. return circpad_machine_schedule_padding(mi);
  1122. }
  1123. return CIRCPAD_STATE_UNCHANGED;
  1124. }
  1125. /**
  1126. * Estimate the circuit RTT from the current middle hop out to the
  1127. * end of the circuit.
  1128. *
  1129. * We estimate RTT by calculating the time between "receive" and
  1130. * "send" at a middle hop. This is because we "receive" a cell
  1131. * from the origin, and then relay it towards the exit before a
  1132. * response comes back. It is that response time from the exit side
  1133. * that we want to measure, so that we can make use of it for synthetic
  1134. * response delays.
  1135. */
  1136. static void
  1137. circpad_estimate_circ_rtt_on_received(circuit_t *circ,
  1138. circpad_machineinfo_t *mi)
  1139. {
  1140. /* Origin circuits don't estimate RTT. They could do it easily enough,
  1141. * but they have no reason to use it in any delay calculations. */
  1142. if (CIRCUIT_IS_ORIGIN(circ) || mi->stop_rtt_update)
  1143. return;
  1144. /* If we already have a last receieved packet time, that means we
  1145. * did not get a response before this packet. The RTT estimate
  1146. * only makes sense if we do not have multiple packets on the
  1147. * wire, so stop estimating if this is the second packet
  1148. * back to back. However, for the first set of back-to-back
  1149. * packets, we can wait until the very first response comes back
  1150. * to us, to measure that RTT (for the response to optimistic
  1151. * data, for example). Hence stop_rtt_update is only checked
  1152. * in this received side function, and not in send side below.
  1153. */
  1154. if (mi->last_received_time_usec) {
  1155. /* We also allow multiple back-to-back packets if the circuit is not
  1156. * opened, to handle var cells.
  1157. * XXX: Will this work with out var cell plans? Maybe not,
  1158. * since we're opened at the middle hop as soon as we process
  1159. * one var extend2 :/ */
  1160. if (circ->state == CIRCUIT_STATE_OPEN) {
  1161. log_fn(LOG_INFO, LD_CIRC,
  1162. "Stopping padding RTT estimation on circuit (%"PRIu64
  1163. ", %d) after two back to back packets. Current RTT: %d",
  1164. circ->n_chan ? circ->n_chan->global_identifier : 0,
  1165. circ->n_circ_id, mi->rtt_estimate_usec);
  1166. mi->stop_rtt_update = 1;
  1167. }
  1168. } else {
  1169. mi->last_received_time_usec = monotime_absolute_usec();
  1170. }
  1171. }
  1172. /**
  1173. * Handles the "send" side of RTT calculation at middle nodes.
  1174. *
  1175. * This function calculates the RTT from the middle to the end
  1176. * of the circuit by subtracting the last received cell timestamp
  1177. * from the current time. It allows back-to-back cells until
  1178. * the circuit is opened, to allow for var cell handshakes.
  1179. * XXX: Check our var cell plans to make sure this will work.
  1180. */
  1181. static void
  1182. circpad_estimate_circ_rtt_on_send(circuit_t *circ,
  1183. circpad_machineinfo_t *mi)
  1184. {
  1185. /* Origin circuits don't estimate RTT. They could do it easily enough,
  1186. * but they have no reason to use it in any delay calculations. */
  1187. if (CIRCUIT_IS_ORIGIN(circ))
  1188. return;
  1189. /* If last_received_time_usec is non-zero, we are waiting for a response
  1190. * from the exit side. Calculate the time delta and use it as RTT. */
  1191. if (mi->last_received_time_usec) {
  1192. circpad_time_t rtt_time = monotime_absolute_usec() -
  1193. mi->last_received_time_usec;
  1194. /* Reset the last RTT packet time, so we can tell if two cells
  1195. * arrive back to back */
  1196. mi->last_received_time_usec = 0;
  1197. /* Use INT32_MAX to ensure the addition doesn't overflow */
  1198. if (rtt_time >= INT32_MAX) {
  1199. log_fn(LOG_WARN,LD_CIRC,
  1200. "Circuit padding RTT estimate overflowed: %"PRIu64
  1201. " vs %"PRIu64, monotime_absolute_usec(),
  1202. mi->last_received_time_usec);
  1203. return;
  1204. }
  1205. /* If the old RTT estimate is lower than this one, use this one, because
  1206. * the circuit is getting longer. If this estimate is somehow
  1207. * faster than the previous, then maybe that was network jitter.
  1208. * In that case, average them. */
  1209. if (mi->rtt_estimate_usec < (circpad_delay_t)rtt_time) {
  1210. mi->rtt_estimate_usec = (circpad_delay_t)rtt_time;
  1211. } else {
  1212. mi->rtt_estimate_usec += (circpad_delay_t)rtt_time;
  1213. mi->rtt_estimate_usec /= 2;
  1214. }
  1215. } else if (circ->state == CIRCUIT_STATE_OPEN) {
  1216. /* If last_received_time_usec is zero, then we have gotten two cells back
  1217. * to back. Stop estimating RTT in this case. Note that we only
  1218. * stop RTT update if the circuit is opened, to allow for RTT estimates
  1219. * of var cells during circ setup. */
  1220. mi->stop_rtt_update = 1;
  1221. if (!mi->rtt_estimate_usec) {
  1222. log_fn(LOG_NOTICE, LD_CIRC,
  1223. "Got two cells back to back on a circuit before estimating RTT.");
  1224. }
  1225. }
  1226. }
  1227. /**
  1228. * A "non-padding" cell has been sent from this endpoint. React
  1229. * according to any padding state machines on the circuit.
  1230. *
  1231. * For origin circuits, this means we sent a cell into the network.
  1232. * For middle relay circuits, this means we sent a cell towards the
  1233. * origin.
  1234. */
  1235. void
  1236. circpad_cell_event_nonpadding_sent(circuit_t *on_circ)
  1237. {
  1238. /* Update global cell count */
  1239. circpad_global_nonpadding_sent++;
  1240. /* If there are no machines then this loop should not iterate */
  1241. FOR_EACH_ACTIVE_CIRCUIT_MACHINE_BEGIN(i, on_circ) {
  1242. /* First, update any RTT estimate */
  1243. circpad_estimate_circ_rtt_on_send(on_circ, on_circ->padding_info[i]);
  1244. /* Remove a token: this is the idea of adaptive padding, since we have an
  1245. * ideal distribution that we want our distribution to look like. */
  1246. if (!circpad_machine_remove_token(on_circ->padding_info[i])) {
  1247. /* If removing a token did not cause a transition, check if
  1248. * non-padding sent event should */
  1249. circpad_machine_transition(on_circ->padding_info[i],
  1250. CIRCPAD_EVENT_NONPADDING_SENT);
  1251. }
  1252. } FOR_EACH_ACTIVE_CIRCUIT_MACHINE_END;
  1253. }
  1254. /**
  1255. * A "non-padding" cell has been received by this endpoint. React
  1256. * according to any padding state machines on the circuit.
  1257. *
  1258. * For origin circuits, this means we read a cell from the network.
  1259. * For middle relay circuits, this means we received a cell from the
  1260. * origin.
  1261. */
  1262. void
  1263. circpad_cell_event_nonpadding_received(circuit_t *on_circ)
  1264. {
  1265. FOR_EACH_ACTIVE_CIRCUIT_MACHINE_BEGIN(i, on_circ) {
  1266. /* First, update any RTT estimate */
  1267. circpad_estimate_circ_rtt_on_received(on_circ, on_circ->padding_info[i]);
  1268. circpad_machine_transition(on_circ->padding_info[i],
  1269. CIRCPAD_EVENT_NONPADDING_RECV);
  1270. } FOR_EACH_ACTIVE_CIRCUIT_MACHINE_END;
  1271. }
  1272. /**
  1273. * A padding cell has been sent from this endpoint. React
  1274. * according to any padding state machines on the circuit.
  1275. *
  1276. * For origin circuits, this means we sent a cell into the network.
  1277. * For middle relay circuits, this means we sent a cell towards the
  1278. * origin.
  1279. */
  1280. void
  1281. circpad_cell_event_padding_sent(circuit_t *on_circ)
  1282. {
  1283. FOR_EACH_ACTIVE_CIRCUIT_MACHINE_BEGIN(i, on_circ) {
  1284. circpad_machine_transition(on_circ->padding_info[i],
  1285. CIRCPAD_EVENT_PADDING_SENT);
  1286. } FOR_EACH_ACTIVE_CIRCUIT_MACHINE_END;
  1287. }
  1288. /**
  1289. * A padding cell has been received by this endpoint. React
  1290. * according to any padding state machines on the circuit.
  1291. *
  1292. * For origin circuits, this means we read a cell from the network.
  1293. * For middle relay circuits, this means we received a cell from the
  1294. * origin.
  1295. */
  1296. void
  1297. circpad_cell_event_padding_received(circuit_t *on_circ)
  1298. {
  1299. /* identical to padding sent */
  1300. FOR_EACH_ACTIVE_CIRCUIT_MACHINE_BEGIN(i, on_circ) {
  1301. circpad_machine_transition(on_circ->padding_info[i],
  1302. CIRCPAD_EVENT_PADDING_RECV);
  1303. } FOR_EACH_ACTIVE_CIRCUIT_MACHINE_END;
  1304. }
  1305. /**
  1306. * An "infinite" delay has ben chosen from one of our histograms.
  1307. *
  1308. * "Infinite" delays mean don't send padding -- but they can also
  1309. * mean transition to another state depending on the state machine
  1310. * definitions. Check the rules and react accordingly.
  1311. *
  1312. * Return 1 if we decide to transition, 0 otherwise.
  1313. */
  1314. circpad_decision_t
  1315. circpad_internal_event_infinity(circpad_machineinfo_t *mi)
  1316. {
  1317. return circpad_machine_transition(mi, CIRCPAD_EVENT_INFINITY);
  1318. }
  1319. /**
  1320. * All of the bins of our current state's histogram's are empty.
  1321. *
  1322. * Check to see if this means transition to another state, and if
  1323. * not, refill the tokens.
  1324. *
  1325. * Return 1 if we decide to transition, 0 otherwise.
  1326. */
  1327. circpad_decision_t
  1328. circpad_internal_event_bins_empty(circpad_machineinfo_t *mi)
  1329. {
  1330. if (circpad_machine_transition(mi, CIRCPAD_EVENT_BINS_EMPTY)
  1331. == CIRCPAD_STATE_CHANGED) {
  1332. return CIRCPAD_STATE_CHANGED;
  1333. } else {
  1334. /* If we dont transition, then we refill the tokens */
  1335. circpad_machine_setup_tokens(mi);
  1336. return CIRCPAD_STATE_UNCHANGED;
  1337. }
  1338. }
  1339. /**
  1340. * This state has used up its cell count. Emit the event and
  1341. * see if we transition.
  1342. *
  1343. * Return 1 if we decide to transition, 0 otherwise.
  1344. */
  1345. circpad_decision_t
  1346. circpad_internal_event_state_length_up(circpad_machineinfo_t *mi)
  1347. {
  1348. return circpad_machine_transition(mi, CIRCPAD_EVENT_LENGTH_COUNT);
  1349. }
  1350. /**
  1351. * Returns true if the circuit matches the conditions.
  1352. */
  1353. static inline bool
  1354. circpad_machine_conditions_met(origin_circuit_t *circ,
  1355. const circpad_machine_t *machine)
  1356. {
  1357. if (!(circpad_circ_purpose_to_mask(TO_CIRCUIT(circ)->purpose)
  1358. & machine->conditions.purpose_mask))
  1359. return 0;
  1360. if (machine->conditions.requires_vanguards) {
  1361. const or_options_t *options = get_options();
  1362. /* Pinned middles are effectively vanguards */
  1363. if (!(options->HSLayer2Nodes || options->HSLayer3Nodes))
  1364. return 0;
  1365. }
  1366. /* We check for any bits set in the circuit state mask so that machines
  1367. * can say any of the following through their state bitmask:
  1368. * "I want to apply to circuits with either streams or no streams"; OR
  1369. * "I only want to apply to circuits with streams"; OR
  1370. * "I only want to apply to circuits without streams". */
  1371. if (!(circpad_circuit_state(circ) & machine->conditions.state_mask))
  1372. return 0;
  1373. if (circuit_get_cpath_opened_len(circ) < machine->conditions.min_hops)
  1374. return 0;
  1375. return 1;
  1376. }
  1377. /**
  1378. * Returns a minimized representation of the circuit state.
  1379. *
  1380. * The padding code only cares if the circuit is building,
  1381. * opened, used for streams, and/or still has relay early cells.
  1382. * This returns a bitmask of all state properities that apply to
  1383. * this circuit.
  1384. */
  1385. static inline
  1386. circpad_circuit_state_t
  1387. circpad_circuit_state(origin_circuit_t *circ)
  1388. {
  1389. circpad_circuit_state_t retmask = 0;
  1390. if (circ->p_streams)
  1391. retmask |= CIRCPAD_CIRC_STREAMS;
  1392. else
  1393. retmask |= CIRCPAD_CIRC_NO_STREAMS;
  1394. /* We use has_opened to prevent cannibialized circs from flapping. */
  1395. if (circ->has_opened)
  1396. retmask |= CIRCPAD_CIRC_OPENED;
  1397. else
  1398. retmask |= CIRCPAD_CIRC_BUILDING;
  1399. if (circ->remaining_relay_early_cells > 0)
  1400. retmask |= CIRCPAD_CIRC_HAS_RELAY_EARLY;
  1401. else
  1402. retmask |= CIRCPAD_CIRC_HAS_NO_RELAY_EARLY;
  1403. return retmask;
  1404. }
  1405. /**
  1406. * Convert a normal circuit purpose into a bitmask that we can
  1407. * use for determining matching circuits.
  1408. */
  1409. static inline
  1410. circpad_purpose_mask_t
  1411. circpad_circ_purpose_to_mask(uint8_t circ_purpose)
  1412. {
  1413. /* Treat OR circ purposes as ignored. They should not be passed here*/
  1414. if (BUG(circ_purpose <= CIRCUIT_PURPOSE_OR_MAX_)) {
  1415. return 0;
  1416. }
  1417. /* Treat new client circuit purposes as "OMG ITS EVERYTHING".
  1418. * This also should not happen */
  1419. if (BUG(circ_purpose - CIRCUIT_PURPOSE_OR_MAX_ - 1 > 32)) {
  1420. return CIRCPAD_PURPOSE_ALL;
  1421. }
  1422. /* Convert the purpose to a bit position */
  1423. return 1 << (circ_purpose - CIRCUIT_PURPOSE_OR_MAX_ - 1);
  1424. }
  1425. /**
  1426. * Shut down any machines whose conditions no longer match
  1427. * the current circuit.
  1428. */
  1429. static void
  1430. circpad_shutdown_old_machines(origin_circuit_t *on_circ)
  1431. {
  1432. circuit_t *circ = TO_CIRCUIT(on_circ);
  1433. FOR_EACH_ACTIVE_CIRCUIT_MACHINE_BEGIN(i, circ) {
  1434. if (!circpad_machine_conditions_met(on_circ,
  1435. circ->padding_machine[i])) {
  1436. // Clear machineinfo (frees timers)
  1437. circpad_circuit_machineinfo_free_idx(circ, i);
  1438. // Send padding negotiate stop
  1439. circpad_negotiate_padding(on_circ,
  1440. circ->padding_machine[i]->machine_num,
  1441. circ->padding_machine[i]->target_hopnum,
  1442. CIRCPAD_COMMAND_STOP);
  1443. }
  1444. } FOR_EACH_ACTIVE_CIRCUIT_MACHINE_END;
  1445. }
  1446. /**
  1447. * Negotiate new machines that would apply to this circuit.
  1448. *
  1449. * This function checks to see if we have any free machine indexes,
  1450. * and for each free machine index, it initializes the most recently
  1451. * added origin-side padding machine that matches the target machine
  1452. * index and circuit conditions, and negotiates it with the appropriate
  1453. * middle relay.
  1454. */
  1455. static void
  1456. circpad_add_matching_machines(origin_circuit_t *on_circ)
  1457. {
  1458. circuit_t *circ = TO_CIRCUIT(on_circ);
  1459. #ifdef TOR_UNIT_TESTS
  1460. /* Tests don't have to init our padding machines */
  1461. if (!origin_padding_machines)
  1462. return;
  1463. #endif
  1464. /* If padding negotiation failed before, do not try again */
  1465. if (on_circ->padding_negotiation_failed)
  1466. return;
  1467. FOR_EACH_CIRCUIT_MACHINE_BEGIN(i) {
  1468. /* If there is a padding machine info, this index is occupied.
  1469. * No need to check conditions for this index. */
  1470. if (circ->padding_info[i])
  1471. continue;
  1472. /* We have a free machine index. Check the origin padding
  1473. * machines in reverse order, so that more recently added
  1474. * machines take priority over older ones. */
  1475. SMARTLIST_FOREACH_REVERSE_BEGIN(origin_padding_machines,
  1476. circpad_machine_t *,
  1477. machine) {
  1478. /* Machine definitions have a specific target machine index.
  1479. * This is so event ordering is deterministic with respect
  1480. * to which machine gets events first when there are two
  1481. * machines installed on a circuit. Make sure we only
  1482. * add this machine if its target machine index is free. */
  1483. if (machine->machine_index == i &&
  1484. circpad_machine_conditions_met(on_circ, machine)) {
  1485. // We can only replace this machine if the target hopnum
  1486. // is the same, otherwise we'll get invalid data
  1487. if (circ->padding_machine[i]) {
  1488. if (circ->padding_machine[i]->target_hopnum !=
  1489. machine->target_hopnum)
  1490. continue;
  1491. /* Replace it. (Don't free - is global). */
  1492. circ->padding_machine[i] = NULL;
  1493. }
  1494. /* Set up the machine immediately so that the slot is occupied.
  1495. * We will tear it down on error return, or if there is an error
  1496. * response from the relay. */
  1497. circpad_setup_machine_on_circ(circ, machine);
  1498. if (circpad_negotiate_padding(on_circ, machine->machine_num,
  1499. machine->target_hopnum,
  1500. CIRCPAD_COMMAND_START) < 0) {
  1501. circpad_circuit_machineinfo_free_idx(circ, i);
  1502. circ->padding_machine[i] = NULL;
  1503. on_circ->padding_negotiation_failed = 1;
  1504. } else {
  1505. /* Success. Don't try any more machines */
  1506. return;
  1507. }
  1508. }
  1509. } SMARTLIST_FOREACH_END(machine);
  1510. } FOR_EACH_CIRCUIT_MACHINE_END;
  1511. }
  1512. /**
  1513. * Event that tells us we added a hop to an origin circuit.
  1514. *
  1515. * This event is used to decide if we should create a padding machine
  1516. * on a circuit.
  1517. */
  1518. void
  1519. circpad_machine_event_circ_added_hop(origin_circuit_t *on_circ)
  1520. {
  1521. /* Since our padding conditions do not specify a max_hops,
  1522. * all we can do is add machines here */
  1523. circpad_add_matching_machines(on_circ);
  1524. }
  1525. /**
  1526. * Event that tells us that an origin circuit is now built.
  1527. *
  1528. * Shut down any machines that only applied to un-built circuits.
  1529. * Activate any new ones.
  1530. */
  1531. void
  1532. circpad_machine_event_circ_built(origin_circuit_t *circ)
  1533. {
  1534. circpad_shutdown_old_machines(circ);
  1535. circpad_add_matching_machines(circ);
  1536. }
  1537. /**
  1538. * Circpad purpose changed event.
  1539. *
  1540. * Shut down any machines that don't apply to our circ purpose.
  1541. * Activate any new ones that do.
  1542. */
  1543. void
  1544. circpad_machine_event_circ_purpose_changed(origin_circuit_t *circ)
  1545. {
  1546. circpad_shutdown_old_machines(circ);
  1547. circpad_add_matching_machines(circ);
  1548. }
  1549. /**
  1550. * Event that tells us that an origin circuit is out of RELAY_EARLY
  1551. * cells.
  1552. *
  1553. * Shut down any machines that only applied to RELAY_EARLY circuits.
  1554. * Activate any new ones.
  1555. */
  1556. void
  1557. circpad_machine_event_circ_has_no_relay_early(origin_circuit_t *circ)
  1558. {
  1559. circpad_shutdown_old_machines(circ);
  1560. circpad_add_matching_machines(circ);
  1561. }
  1562. /**
  1563. * Streams attached event.
  1564. *
  1565. * Called from link_apconn_to_circ() and handle_hs_exit_conn()
  1566. *
  1567. * Shut down any machines that only applied to machines without
  1568. * streams. Activate any new ones.
  1569. */
  1570. void
  1571. circpad_machine_event_circ_has_streams(origin_circuit_t *circ)
  1572. {
  1573. circpad_shutdown_old_machines(circ);
  1574. circpad_add_matching_machines(circ);
  1575. }
  1576. /**
  1577. * Streams detached event.
  1578. *
  1579. * Called from circuit_detach_stream()
  1580. *
  1581. * Shut down any machines that only applied to machines without
  1582. * streams. Activate any new ones.
  1583. */
  1584. void
  1585. circpad_machine_event_circ_has_no_streams(origin_circuit_t *circ)
  1586. {
  1587. circpad_shutdown_old_machines(circ);
  1588. circpad_add_matching_machines(circ);
  1589. }
  1590. /**
  1591. * Verify that padding is coming from the expected hop.
  1592. *
  1593. * Returns true if from_hop matches the target hop from
  1594. * one of our padding machines.
  1595. *
  1596. * Returns false if we're not an origin circuit, or if from_hop
  1597. * does not match one of the padding machines.
  1598. */
  1599. bool
  1600. circpad_padding_is_from_expected_hop(circuit_t *circ,
  1601. crypt_path_t *from_hop)
  1602. {
  1603. crypt_path_t *target_hop = NULL;
  1604. if (!CIRCUIT_IS_ORIGIN(circ))
  1605. return 0;
  1606. FOR_EACH_CIRCUIT_MACHINE_BEGIN(i) {
  1607. /* We have to check padding_machine and not padding_info/active
  1608. * machines here because padding may arrive after we shut down a
  1609. * machine. The info is gone, but the padding_machine waits
  1610. * for the padding_negotiated response to come back. */
  1611. if (!circ->padding_machine[i])
  1612. continue;
  1613. target_hop = circuit_get_cpath_hop(TO_ORIGIN_CIRCUIT(circ),
  1614. circ->padding_machine[i]->target_hopnum);
  1615. if (target_hop == from_hop)
  1616. return 1;
  1617. } FOR_EACH_CIRCUIT_MACHINE_END;
  1618. return 0;
  1619. }
  1620. /**
  1621. * Deliver circpad events for an "unrecognized cell".
  1622. *
  1623. * Unrecognized cells are sent to relays and are forwarded
  1624. * onto the next hop of their circuits. Unrecognized cells
  1625. * are by definition not padding. We need to tell relay-side
  1626. * state machines that a non-padding cell was sent or received,
  1627. * depending on the direction, so they can update their histograms
  1628. * and decide to pad or not.
  1629. */
  1630. void
  1631. circpad_deliver_unrecognized_cell_events(circuit_t *circ,
  1632. cell_direction_t dir)
  1633. {
  1634. // We should never see unrecognized cells at origin.
  1635. // Our caller emits a warn when this happens.
  1636. if (CIRCUIT_IS_ORIGIN(circ)) {
  1637. return;
  1638. }
  1639. if (dir == CELL_DIRECTION_OUT) {
  1640. /* When direction is out (away from origin), then we received non-padding
  1641. cell coming from the origin to us. */
  1642. circpad_cell_event_nonpadding_received(circ);
  1643. } else if (dir == CELL_DIRECTION_IN) {
  1644. /* It's in and not origin, so the cell is going away from us.
  1645. * So we are relaying a non-padding cell towards the origin. */
  1646. circpad_cell_event_nonpadding_sent(circ);
  1647. }
  1648. }
  1649. /**
  1650. * Deliver circpad events for "recognized" relay cells.
  1651. *
  1652. * Recognized cells are destined for this hop, either client or middle.
  1653. * Check if this is a padding cell or not, and send the appropiate
  1654. * received event.
  1655. */
  1656. void
  1657. circpad_deliver_recognized_relay_cell_events(circuit_t *circ,
  1658. uint8_t relay_command,
  1659. crypt_path_t *layer_hint)
  1660. {
  1661. /* Padding negotiate cells are ignored by the state machines
  1662. * for simplicity. */
  1663. if (relay_command == RELAY_COMMAND_PADDING_NEGOTIATE ||
  1664. relay_command == RELAY_COMMAND_PADDING_NEGOTIATED) {
  1665. return;
  1666. }
  1667. if (relay_command == RELAY_COMMAND_DROP) {
  1668. rep_hist_padding_count_read(PADDING_TYPE_DROP);
  1669. if (CIRCUIT_IS_ORIGIN(circ)) {
  1670. if (circpad_padding_is_from_expected_hop(circ, layer_hint)) {
  1671. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), 0);
  1672. } else {
  1673. /* This is unexpected padding. Ignore it for now. */
  1674. return;
  1675. }
  1676. }
  1677. /* The cell should be recognized by now, which means that we are on the
  1678. destination, which means that we received a padding cell. We might be
  1679. the client or the Middle node, still, because leaky-pipe. */
  1680. circpad_cell_event_padding_received(circ);
  1681. log_fn(LOG_INFO, LD_CIRC, "Got padding cell on %s circuit %u.",
  1682. CIRCUIT_IS_ORIGIN(circ) ? "origin" : "non-origin",
  1683. CIRCUIT_IS_ORIGIN(circ) ?
  1684. TO_ORIGIN_CIRCUIT(circ)->global_identifier : 0);
  1685. } else {
  1686. /* We received a non-padding cell on the edge */
  1687. circpad_cell_event_nonpadding_received(circ);
  1688. }
  1689. }
  1690. /**
  1691. * Deliver circpad events for relay cells sent from us.
  1692. *
  1693. * If this is a padding cell, update our padding stats
  1694. * and deliver the event. Otherwise just deliver the event.
  1695. */
  1696. void
  1697. circpad_deliver_sent_relay_cell_events(circuit_t *circ,
  1698. uint8_t relay_command)
  1699. {
  1700. /* Padding negotiate cells are ignored by the state machines
  1701. * for simplicity. */
  1702. if (relay_command == RELAY_COMMAND_PADDING_NEGOTIATE ||
  1703. relay_command == RELAY_COMMAND_PADDING_NEGOTIATED) {
  1704. return;
  1705. }
  1706. /* RELAY_COMMAND_DROP is the multi-hop (aka circuit-level) padding cell in
  1707. * tor. (CELL_PADDING is a channel-level padding cell, which is not relayed
  1708. * or processed here) */
  1709. if (relay_command == RELAY_COMMAND_DROP) {
  1710. /* Optimization: The event for RELAY_COMMAND_DROP is sent directly
  1711. * from circpad_send_padding_cell_for_callback(). This is to avoid
  1712. * putting a cell_t and a relay_header_t on the stack repeatedly
  1713. * if we decide to send a long train of padidng cells back-to-back
  1714. * with 0 delay. So we do nothing here. */
  1715. return;
  1716. } else {
  1717. /* This is a non-padding cell sent from the client or from
  1718. * this node. */
  1719. circpad_cell_event_nonpadding_sent(circ);
  1720. }
  1721. }
  1722. /**
  1723. * Initialize the states array for a circpad machine.
  1724. */
  1725. void
  1726. circpad_machine_states_init(circpad_machine_t *machine,
  1727. circpad_statenum_t num_states)
  1728. {
  1729. if (BUG(num_states > CIRCPAD_MAX_MACHINE_STATES)) {
  1730. num_states = CIRCPAD_MAX_MACHINE_STATES;
  1731. }
  1732. machine->num_states = num_states;
  1733. machine->states = tor_malloc_zero(sizeof(circpad_state_t)*num_states);
  1734. /* Initialize the default next state for all events to
  1735. * "ignore" -- if events aren't specified, they are ignored. */
  1736. for (circpad_statenum_t s = 0; s < num_states; s++) {
  1737. for (int e = 0; e < CIRCPAD_NUM_EVENTS; e++) {
  1738. machine->states[s].next_state[e] = CIRCPAD_STATE_IGNORE;
  1739. }
  1740. }
  1741. }
  1742. static void
  1743. circpad_setup_machine_on_circ(circuit_t *on_circ,
  1744. const circpad_machine_t *machine)
  1745. {
  1746. if (CIRCUIT_IS_ORIGIN(on_circ) && !machine->is_origin_side) {
  1747. log_fn(LOG_WARN, LD_BUG,
  1748. "Can't set up non-origin machine on origin circuit!");
  1749. return;
  1750. }
  1751. if (!CIRCUIT_IS_ORIGIN(on_circ) && machine->is_origin_side) {
  1752. log_fn(LOG_WARN, LD_BUG,
  1753. "Can't set up origin machine on non-origin circuit!");
  1754. return;
  1755. }
  1756. tor_assert_nonfatal(on_circ->padding_machine[machine->machine_index]
  1757. == NULL);
  1758. tor_assert_nonfatal(on_circ->padding_info[machine->machine_index] == NULL);
  1759. on_circ->padding_info[machine->machine_index] =
  1760. circpad_circuit_machineinfo_new(on_circ, machine->machine_index);
  1761. on_circ->padding_machine[machine->machine_index] = machine;
  1762. }
  1763. static void
  1764. circpad_circ_client_machine_init(void)
  1765. {
  1766. circpad_machine_t *circ_client_machine
  1767. = tor_malloc_zero(sizeof(circpad_machine_t));
  1768. // XXX: Better conditions for merge.. Or disable this machine in
  1769. // merge?
  1770. circ_client_machine->conditions.min_hops = 2;
  1771. circ_client_machine->conditions.state_mask =
  1772. CIRCPAD_CIRC_BUILDING|CIRCPAD_CIRC_OPENED|CIRCPAD_CIRC_HAS_RELAY_EARLY;
  1773. circ_client_machine->conditions.purpose_mask = CIRCPAD_PURPOSE_ALL;
  1774. circ_client_machine->target_hopnum = 2;
  1775. circ_client_machine->is_origin_side = 1;
  1776. /* Start, gap, burst */
  1777. circpad_machine_states_init(circ_client_machine, 3);
  1778. circ_client_machine->states[CIRCPAD_STATE_START].
  1779. next_state[CIRCPAD_EVENT_NONPADDING_RECV] = CIRCPAD_STATE_BURST;
  1780. circ_client_machine->states[CIRCPAD_STATE_BURST].
  1781. next_state[CIRCPAD_EVENT_NONPADDING_RECV] = CIRCPAD_STATE_BURST;
  1782. circ_client_machine->states[CIRCPAD_STATE_BURST].
  1783. next_state[CIRCPAD_EVENT_PADDING_RECV] = CIRCPAD_STATE_BURST;
  1784. /* If we are in burst state, and we send a non-padding cell, then we cancel
  1785. the timer for the next padding cell:
  1786. We dont want to send fake extends when actual extends are going on */
  1787. circ_client_machine->states[CIRCPAD_STATE_BURST].
  1788. next_state[CIRCPAD_EVENT_NONPADDING_SENT] = CIRCPAD_STATE_CANCEL;
  1789. circ_client_machine->states[CIRCPAD_STATE_BURST].
  1790. next_state[CIRCPAD_EVENT_BINS_EMPTY] = CIRCPAD_STATE_END;
  1791. circ_client_machine->states[CIRCPAD_STATE_BURST].token_removal =
  1792. CIRCPAD_TOKEN_REMOVAL_CLOSEST;
  1793. // FIXME: Tune this histogram
  1794. circ_client_machine->states[CIRCPAD_STATE_BURST].histogram_len = 2;
  1795. circ_client_machine->states[CIRCPAD_STATE_BURST].start_usec = 500;
  1796. circ_client_machine->states[CIRCPAD_STATE_BURST].range_usec = 1000000;
  1797. /* We have 5 tokens in the histogram, which means that all circuits will look
  1798. * like they have 7 hops (since we start this machine after the second hop,
  1799. * and tokens are decremented for any valid hops, and fake extends are
  1800. * used after that -- 2+5==7). */
  1801. circ_client_machine->states[CIRCPAD_STATE_BURST].histogram[0] = 5;
  1802. circ_client_machine->states[CIRCPAD_STATE_BURST].histogram_total_tokens = 5;
  1803. circ_client_machine->machine_num = smartlist_len(origin_padding_machines);
  1804. smartlist_add(origin_padding_machines, circ_client_machine);
  1805. }
  1806. static void
  1807. circpad_circ_responder_machine_init(void)
  1808. {
  1809. circpad_machine_t *circ_responder_machine
  1810. = tor_malloc_zero(sizeof(circpad_machine_t));
  1811. /* Shut down the machine after we've sent enough packets */
  1812. circ_responder_machine->should_negotiate_end = 1;
  1813. /* The relay-side doesn't care what hopnum it is, but for consistency,
  1814. * let's match the client */
  1815. circ_responder_machine->target_hopnum = 2;
  1816. circ_responder_machine->is_origin_side = 0;
  1817. /* Start, gap, burst */
  1818. circpad_machine_states_init(circ_responder_machine, 3);
  1819. /* This is the settings of the state machine. In the future we are gonna
  1820. serialize this into the consensus or the torrc */
  1821. /* We transition to the burst state on padding receive and on non-padding
  1822. * recieve */
  1823. circ_responder_machine->states[CIRCPAD_STATE_START].
  1824. next_state[CIRCPAD_EVENT_PADDING_RECV] = CIRCPAD_STATE_BURST;
  1825. circ_responder_machine->states[CIRCPAD_STATE_START].
  1826. next_state[CIRCPAD_EVENT_NONPADDING_RECV] = CIRCPAD_STATE_BURST;
  1827. /* Inside the burst state we _stay_ in the burst state when a non-padding
  1828. * is sent */
  1829. circ_responder_machine->states[CIRCPAD_STATE_BURST].
  1830. next_state[CIRCPAD_EVENT_NONPADDING_SENT] = CIRCPAD_STATE_BURST;
  1831. /* Inside the burst state we transition to the gap state when we receive a
  1832. * padding cell */
  1833. circ_responder_machine->states[CIRCPAD_STATE_BURST].
  1834. next_state[CIRCPAD_EVENT_PADDING_RECV] = CIRCPAD_STATE_GAP;
  1835. /* These describe the padding charasteristics when in burst state */
  1836. /* use_rtt_estimate tries to estimate how long padding cells take to go from
  1837. C->M, and uses that as what as the base of the histogram */
  1838. circ_responder_machine->states[CIRCPAD_STATE_BURST].use_rtt_estimate = 1;
  1839. /* The histogram is 2 bins: an empty one, and infinity */
  1840. circ_responder_machine->states[CIRCPAD_STATE_BURST].histogram_len = 2;
  1841. circ_responder_machine->states[CIRCPAD_STATE_BURST].start_usec = 5000;
  1842. circ_responder_machine->states[CIRCPAD_STATE_BURST].range_usec = 1000000;
  1843. /* During burst state we wait forever for padding to arrive.
  1844. We are waiting for a padding cell from the client to come in, so that we
  1845. respond, and we immitate how extend looks like */
  1846. circ_responder_machine->states[CIRCPAD_STATE_BURST].histogram[0] = 0;
  1847. // Only infinity bin:
  1848. circ_responder_machine->states[CIRCPAD_STATE_BURST].histogram[1] = 1;
  1849. circ_responder_machine->states[CIRCPAD_STATE_BURST].
  1850. histogram_total_tokens = 1;
  1851. /* From the gap state, we _stay_ in the gap state, when we receive padding
  1852. * or non padding */
  1853. circ_responder_machine->states[CIRCPAD_STATE_GAP].
  1854. next_state[CIRCPAD_EVENT_PADDING_RECV] = CIRCPAD_STATE_GAP;
  1855. circ_responder_machine->states[CIRCPAD_STATE_GAP].
  1856. next_state[CIRCPAD_EVENT_NONPADDING_RECV] = CIRCPAD_STATE_GAP;
  1857. /* And from the gap state, we go to the end, when the bins are empty or a
  1858. * non-padding cell is sent */
  1859. circ_responder_machine->states[CIRCPAD_STATE_GAP].
  1860. next_state[CIRCPAD_EVENT_BINS_EMPTY] = CIRCPAD_STATE_END;
  1861. circ_responder_machine->states[CIRCPAD_STATE_GAP].
  1862. next_state[CIRCPAD_EVENT_NONPADDING_SENT] = CIRCPAD_STATE_END;
  1863. // FIXME: Tune this histogram
  1864. /* The gap state is the delay you wait after you receive a padding cell
  1865. before you send a padding response */
  1866. circ_responder_machine->states[CIRCPAD_STATE_GAP].use_rtt_estimate = 1;
  1867. circ_responder_machine->states[CIRCPAD_STATE_GAP].histogram_len = 6;
  1868. circ_responder_machine->states[CIRCPAD_STATE_GAP].start_usec = 5000;
  1869. circ_responder_machine->states[CIRCPAD_STATE_GAP].range_usec = 1000000;
  1870. circ_responder_machine->states[CIRCPAD_STATE_GAP].histogram[0] = 0;
  1871. circ_responder_machine->states[CIRCPAD_STATE_GAP].histogram[1] = 1;
  1872. circ_responder_machine->states[CIRCPAD_STATE_GAP].histogram[2] = 2;
  1873. circ_responder_machine->states[CIRCPAD_STATE_GAP].histogram[3] = 2;
  1874. circ_responder_machine->states[CIRCPAD_STATE_GAP].histogram[4] = 1;
  1875. /* Total number of tokens */
  1876. circ_responder_machine->states[CIRCPAD_STATE_GAP].histogram_total_tokens = 6;
  1877. circ_responder_machine->states[CIRCPAD_STATE_GAP].token_removal =
  1878. CIRCPAD_TOKEN_REMOVAL_CLOSEST_USEC;
  1879. circ_responder_machine->machine_num = smartlist_len(relay_padding_machines);
  1880. smartlist_add(relay_padding_machines, circ_responder_machine);
  1881. }
  1882. /**
  1883. * Initialize all of our padding machines.
  1884. *
  1885. * This is called at startup. It sets up some global machines, and then
  1886. * loads some from torrc, and from the tor consensus.
  1887. */
  1888. void
  1889. circpad_machines_init(void)
  1890. {
  1891. tor_assert_nonfatal(origin_padding_machines == NULL);
  1892. tor_assert_nonfatal(relay_padding_machines == NULL);
  1893. origin_padding_machines = smartlist_new();
  1894. relay_padding_machines = smartlist_new();
  1895. // TODO: Parse machines from consensus and torrc
  1896. circpad_circ_client_machine_init();
  1897. circpad_circ_responder_machine_init();
  1898. }
  1899. /**
  1900. * Free our padding machines
  1901. */
  1902. void
  1903. circpad_machines_free(void)
  1904. {
  1905. if (origin_padding_machines) {
  1906. SMARTLIST_FOREACH(origin_padding_machines,
  1907. circpad_machine_t *,
  1908. m, tor_free(m->states); tor_free(m));
  1909. smartlist_free(origin_padding_machines);
  1910. }
  1911. if (relay_padding_machines) {
  1912. SMARTLIST_FOREACH(relay_padding_machines,
  1913. circpad_machine_t *,
  1914. m, tor_free(m->states); tor_free(m));
  1915. smartlist_free(relay_padding_machines);
  1916. }
  1917. }
  1918. /**
  1919. * Check the Protover info to see if a node supports padding.
  1920. */
  1921. static bool
  1922. circpad_node_supports_padding(const node_t *node)
  1923. {
  1924. if (node->rs) {
  1925. log_fn(LOG_INFO, LD_CIRC, "Checking padding: %s",
  1926. node->rs->pv.supports_padding ? "supported" : "unsupported");
  1927. return node->rs->pv.supports_padding;
  1928. }
  1929. log_fn(LOG_INFO, LD_CIRC, "Empty routerstatus in padding check");
  1930. return 0;
  1931. }
  1932. /**
  1933. * Get a node_t for the nth hop in our circuit, starting from 1.
  1934. *
  1935. * Returns node_t from the consensus for that hop, if it is opened.
  1936. * Otherwise returns NULL.
  1937. */
  1938. static const node_t *
  1939. circuit_get_nth_node(origin_circuit_t *circ, int hop)
  1940. {
  1941. crypt_path_t *iter = circuit_get_cpath_hop(circ, hop);
  1942. if (!iter || iter->state != CPATH_STATE_OPEN)
  1943. return NULL;
  1944. return node_get_by_id(iter->extend_info->identity_digest);
  1945. }
  1946. /**
  1947. * Return true if a particular circuit supports padding
  1948. * at the desired hop.
  1949. */
  1950. static bool
  1951. circpad_circuit_supports_padding(origin_circuit_t *circ,
  1952. int target_hopnum)
  1953. {
  1954. const node_t *hop;
  1955. if (!(hop = circuit_get_nth_node(circ, target_hopnum))) {
  1956. return 0;
  1957. }
  1958. return circpad_node_supports_padding(hop);
  1959. }
  1960. /**
  1961. * Try to negotiate padding.
  1962. *
  1963. * Returns -1 on error, 0 on success.
  1964. */
  1965. signed_error_t
  1966. circpad_negotiate_padding(origin_circuit_t *circ,
  1967. circpad_machine_num_t machine,
  1968. uint8_t target_hopnum,
  1969. uint8_t command)
  1970. {
  1971. circpad_negotiate_t type;
  1972. cell_t cell;
  1973. ssize_t len;
  1974. /* Check that the target hop lists support for padding in
  1975. * its ProtoVer fields */
  1976. if (!circpad_circuit_supports_padding(circ, target_hopnum)) {
  1977. return -1;
  1978. }
  1979. memset(&cell, 0, sizeof(cell_t));
  1980. memset(&type, 0, sizeof(circpad_negotiate_t));
  1981. // This gets reset to RELAY_EARLY appropriately by
  1982. // relay_send_command_from_edge_. At least, it looks that way.
  1983. // QQQ-MP-AP: Verify that.
  1984. cell.command = CELL_RELAY;
  1985. circpad_negotiate_set_command(&type, command);
  1986. circpad_negotiate_set_version(&type, 0);
  1987. circpad_negotiate_set_machine_type(&type, machine);
  1988. if ((len = circpad_negotiate_encode(cell.payload, CELL_PAYLOAD_SIZE,
  1989. &type)) < 0)
  1990. return -1;
  1991. log_fn(LOG_INFO,LD_CIRC, "Negotiating padding on circuit %u",
  1992. circ->global_identifier);
  1993. return circpad_send_command_to_hop(circ, target_hopnum,
  1994. RELAY_COMMAND_PADDING_NEGOTIATE,
  1995. cell.payload, len);
  1996. }
  1997. /**
  1998. * Try to negotiate padding.
  1999. *
  2000. * Returns 1 if successful (or already set up), 0 otherwise.
  2001. */
  2002. bool
  2003. circpad_padding_negotiated(circuit_t *circ,
  2004. circpad_machine_num_t machine,
  2005. uint8_t command,
  2006. uint8_t response)
  2007. {
  2008. circpad_negotiated_t type;
  2009. cell_t cell;
  2010. ssize_t len;
  2011. memset(&cell, 0, sizeof(cell_t));
  2012. memset(&type, 0, sizeof(circpad_negotiated_t));
  2013. // This gets reset to RELAY_EARLY appropriately by
  2014. // relay_send_command_from_edge_. At least, it looks that way.
  2015. // QQQ-MP-AP: Verify that.
  2016. cell.command = CELL_RELAY;
  2017. circpad_negotiated_set_command(&type, command);
  2018. circpad_negotiated_set_response(&type, response);
  2019. circpad_negotiated_set_version(&type, 0);
  2020. circpad_negotiated_set_machine_type(&type, machine);
  2021. if ((len = circpad_negotiated_encode(cell.payload, CELL_PAYLOAD_SIZE,
  2022. &type)) < 0)
  2023. return 0;
  2024. /* Use relay_send because we're from the middle to the origin. We don't
  2025. * need to specify a target hop or layer_hint. */
  2026. return relay_send_command_from_edge(0, circ,
  2027. RELAY_COMMAND_PADDING_NEGOTIATED,
  2028. (void*)cell.payload,
  2029. (size_t)len, NULL) == 0;
  2030. }
  2031. /**
  2032. * Parse and react to a padding_negotiate cell.
  2033. *
  2034. * This is called at the middle node upon receipt of the client's choice of
  2035. * state machine, so that it can use the requested state machine index, if
  2036. * it is available.
  2037. *
  2038. * Returns -1 on error, 0 on success.
  2039. */
  2040. signed_error_t
  2041. circpad_handle_padding_negotiate(circuit_t *circ, cell_t *cell)
  2042. {
  2043. int retval = 0;
  2044. circpad_negotiate_t *negotiate;
  2045. if (CIRCUIT_IS_ORIGIN(circ)) {
  2046. log_fn(LOG_WARN, LD_PROTOCOL,
  2047. "Padding negotiate cell unsupported at origin.");
  2048. return -1;
  2049. }
  2050. if (circpad_negotiate_parse(&negotiate, cell->payload+RELAY_HEADER_SIZE,
  2051. CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE) < 0) {
  2052. log_fn(LOG_WARN, LD_CIRC,
  2053. "Received malformed PADDING_NEGOTIATE cell; dropping.");
  2054. return -1;
  2055. }
  2056. if (negotiate->command == CIRCPAD_COMMAND_STOP) {
  2057. /* Free the machine corresponding to this machine type */
  2058. free_circ_machineinfos_with_machine_num(circ, negotiate->machine_type);
  2059. log_fn(LOG_WARN, LD_CIRC,
  2060. "Received circuit padding stop command for unknown machine.");
  2061. goto err;
  2062. } else if (negotiate->command == CIRCPAD_COMMAND_START) {
  2063. SMARTLIST_FOREACH_BEGIN(relay_padding_machines,
  2064. const circpad_machine_t *, m) {
  2065. if (m->machine_num == negotiate->machine_type) {
  2066. circpad_setup_machine_on_circ(circ, m);
  2067. goto done;
  2068. }
  2069. } SMARTLIST_FOREACH_END(m);
  2070. }
  2071. err:
  2072. retval = -1;
  2073. done:
  2074. circpad_padding_negotiated(circ, negotiate->machine_type,
  2075. negotiate->command,
  2076. (retval == 0) ? CIRCPAD_RESPONSE_OK : CIRCPAD_RESPONSE_ERR);
  2077. circpad_negotiate_free(negotiate);
  2078. return retval;
  2079. }
  2080. /**
  2081. * Parse and react to a padding_negotiated cell.
  2082. *
  2083. * This is called at the origin upon receipt of the middle's response
  2084. * to our choice of state machine.
  2085. *
  2086. * Returns -1 on error, 0 on success.
  2087. */
  2088. signed_error_t
  2089. circpad_handle_padding_negotiated(circuit_t *circ, cell_t *cell,
  2090. crypt_path_t *layer_hint)
  2091. {
  2092. circpad_negotiated_t *negotiated;
  2093. if (!CIRCUIT_IS_ORIGIN(circ)) {
  2094. log_fn(LOG_WARN, LD_PROTOCOL,
  2095. "Padding negotiated cell unsupported at non-origin.");
  2096. return -1;
  2097. }
  2098. /* Verify this came from the expected hop */
  2099. if (!circpad_padding_is_from_expected_hop(circ, layer_hint)) {
  2100. log_fn(LOG_WARN, LD_PROTOCOL,
  2101. "Padding negotiated cell from wrong hop!");
  2102. return -1;
  2103. }
  2104. if (circpad_negotiated_parse(&negotiated, cell->payload+RELAY_HEADER_SIZE,
  2105. CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE) < 0) {
  2106. log_fn(LOG_WARN, LD_CIRC,
  2107. "Received malformed PADDING_NEGOTIATED cell; "
  2108. "dropping.");
  2109. return -1;
  2110. }
  2111. if (negotiated->command == CIRCPAD_COMMAND_STOP) {
  2112. /* There may not be a padding_info here if we shut down the
  2113. * machine in circpad_shutdown_old_machines(). Or, if
  2114. * circpad_add_matching_matchines() added a new machine,
  2115. * there may be a padding_machine for a different machine num
  2116. * than this response. */
  2117. free_circ_machineinfos_with_machine_num(circ, negotiated->machine_type);
  2118. } else if (negotiated->command == CIRCPAD_COMMAND_START &&
  2119. negotiated->response == CIRCPAD_RESPONSE_ERR) {
  2120. // This can happen due to consensus drift.. free the machines
  2121. // and be sad
  2122. free_circ_machineinfos_with_machine_num(circ, negotiated->machine_type);
  2123. TO_ORIGIN_CIRCUIT(circ)->padding_negotiation_failed = 1;
  2124. log_fn(LOG_INFO, LD_CIRC,
  2125. "Middle node did not accept our padding request.");
  2126. }
  2127. circpad_negotiated_free(negotiated);
  2128. return 0;
  2129. }
  2130. /* Serialization */
  2131. // TODO: Should we use keyword=value here? Are there helpers for that?
  2132. #if 0
  2133. static void
  2134. circpad_state_serialize(const circpad_state_t *state,
  2135. smartlist_t *chunks)
  2136. {
  2137. smartlist_add_asprintf(chunks, " %u", state->histogram[0]);
  2138. for (int i = 1; i < state->histogram_len; i++) {
  2139. smartlist_add_asprintf(chunks, ",%u",
  2140. state->histogram[i]);
  2141. }
  2142. smartlist_add_asprintf(chunks, " 0x%x",
  2143. state->transition_cancel_events);
  2144. for (int i = 0; i < CIRCPAD_NUM_STATES; i++) {
  2145. smartlist_add_asprintf(chunks, ",0x%x",
  2146. state->transition_events[i]);
  2147. }
  2148. smartlist_add_asprintf(chunks, " %u %u",
  2149. state->use_rtt_estimate,
  2150. state->token_removal);
  2151. }
  2152. char *
  2153. circpad_machine_to_string(const circpad_machine_t *machine)
  2154. {
  2155. smartlist_t *chunks = smartlist_new();
  2156. char *out;
  2157. (void)machine;
  2158. circpad_state_serialize(&machine->start, chunks);
  2159. circpad_state_serialize(&machine->gap, chunks);
  2160. circpad_state_serialize(&machine->burst, chunks);
  2161. out = smartlist_join_strings(chunks, "", 0, NULL);
  2162. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  2163. smartlist_free(chunks);
  2164. return out;
  2165. }
  2166. // XXX: Writeme
  2167. const circpad_machine_t *
  2168. circpad_string_to_machine(const char *str)
  2169. {
  2170. (void)str;
  2171. return NULL;
  2172. }
  2173. #endif