or.h 187 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2012, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file or.h
  8. * \brief Master header file for Tor-specific functionality.
  9. **/
  10. #ifndef TOR_OR_H
  11. #define TOR_OR_H
  12. #include "orconfig.h"
  13. #ifdef __COVERITY__
  14. /* If we're building for a static analysis, turn on all the off-by-default
  15. * features. */
  16. #ifndef INSTRUMENT_DOWNLOADS
  17. #define INSTRUMENT_DOWNLOADS 1
  18. #endif
  19. #endif
  20. #ifdef _WIN32
  21. #ifndef _WIN32_WINNT
  22. #define _WIN32_WINNT 0x0501
  23. #endif
  24. #define WIN32_LEAN_AND_MEAN
  25. #endif
  26. #ifdef HAVE_UNISTD_H
  27. #include <unistd.h>
  28. #endif
  29. #ifdef HAVE_SIGNAL_H
  30. #include <signal.h>
  31. #endif
  32. #ifdef HAVE_NETDB_H
  33. #include <netdb.h>
  34. #endif
  35. #ifdef HAVE_SYS_PARAM_H
  36. #include <sys/param.h> /* FreeBSD needs this to know what version it is */
  37. #endif
  38. #include "torint.h"
  39. #ifdef HAVE_SYS_WAIT_H
  40. #include <sys/wait.h>
  41. #endif
  42. #ifdef HAVE_SYS_FCNTL_H
  43. #include <sys/fcntl.h>
  44. #endif
  45. #ifdef HAVE_FCNTL_H
  46. #include <fcntl.h>
  47. #endif
  48. #ifdef HAVE_SYS_IOCTL_H
  49. #include <sys/ioctl.h>
  50. #endif
  51. #ifdef HAVE_SYS_UN_H
  52. #include <sys/un.h>
  53. #endif
  54. #ifdef HAVE_SYS_STAT_H
  55. #include <sys/stat.h>
  56. #endif
  57. #ifdef HAVE_NETINET_IN_H
  58. #include <netinet/in.h>
  59. #endif
  60. #ifdef HAVE_ARPA_INET_H
  61. #include <arpa/inet.h>
  62. #endif
  63. #ifdef HAVE_ERRNO_H
  64. #include <errno.h>
  65. #endif
  66. #ifdef HAVE_ASSERT_H
  67. #include <assert.h>
  68. #endif
  69. #ifdef HAVE_TIME_H
  70. #include <time.h>
  71. #endif
  72. #ifdef _WIN32
  73. #include <io.h>
  74. #include <process.h>
  75. #include <direct.h>
  76. #include <windows.h>
  77. #define snprintf _snprintf
  78. #endif
  79. #ifdef USE_BUFFEREVENTS
  80. #include <event2/bufferevent.h>
  81. #include <event2/buffer.h>
  82. #include <event2/util.h>
  83. #endif
  84. #include "crypto.h"
  85. #include "tortls.h"
  86. #include "../common/torlog.h"
  87. #include "container.h"
  88. #include "torgzip.h"
  89. #include "address.h"
  90. #include "compat_libevent.h"
  91. #include "ht.h"
  92. #include "replaycache.h"
  93. #include "crypto_curve25519.h"
  94. /* These signals are defined to help handle_control_signal work.
  95. */
  96. #ifndef SIGHUP
  97. #define SIGHUP 1
  98. #endif
  99. #ifndef SIGINT
  100. #define SIGINT 2
  101. #endif
  102. #ifndef SIGUSR1
  103. #define SIGUSR1 10
  104. #endif
  105. #ifndef SIGUSR2
  106. #define SIGUSR2 12
  107. #endif
  108. #ifndef SIGTERM
  109. #define SIGTERM 15
  110. #endif
  111. /* Controller signals start at a high number so we don't
  112. * conflict with system-defined signals. */
  113. #define SIGNEWNYM 129
  114. #define SIGCLEARDNSCACHE 130
  115. #if (SIZEOF_CELL_T != 0)
  116. /* On Irix, stdlib.h defines a cell_t type, so we need to make sure
  117. * that our stuff always calls cell_t something different. */
  118. #define cell_t tor_cell_t
  119. #endif
  120. #ifdef ENABLE_TOR2WEB_MODE
  121. #define NON_ANONYMOUS_MODE_ENABLED 1
  122. #endif
  123. /** Length of longest allowable configured nickname. */
  124. #define MAX_NICKNAME_LEN 19
  125. /** Length of a router identity encoded as a hexadecimal digest, plus
  126. * possible dollar sign. */
  127. #define MAX_HEX_NICKNAME_LEN (HEX_DIGEST_LEN+1)
  128. /** Maximum length of verbose router identifier: dollar sign, hex ID digest,
  129. * equal sign or tilde, nickname. */
  130. #define MAX_VERBOSE_NICKNAME_LEN (1+HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN)
  131. /** Maximum size, in bytes, for resized buffers. */
  132. #define MAX_BUF_SIZE ((1<<24)-1) /* 16MB-1 */
  133. /** Maximum size, in bytes, for any directory object that we've downloaded. */
  134. #define MAX_DIR_DL_SIZE MAX_BUF_SIZE
  135. /** For HTTP parsing: Maximum number of bytes we'll accept in the headers
  136. * of an HTTP request or response. */
  137. #define MAX_HEADERS_SIZE 50000
  138. /** Maximum size, in bytes, for any directory object that we're accepting
  139. * as an upload. */
  140. #define MAX_DIR_UL_SIZE MAX_BUF_SIZE
  141. /** Maximum size, in bytes, of a single router descriptor uploaded to us
  142. * as a directory authority. Caches and clients fetch whatever descriptors
  143. * the authorities tell them to fetch, and don't care about size. */
  144. #define MAX_DESCRIPTOR_UPLOAD_SIZE 20000
  145. /** Maximum size of a single extrainfo document, as above. */
  146. #define MAX_EXTRAINFO_UPLOAD_SIZE 50000
  147. /** How long do we keep DNS cache entries before purging them (regardless of
  148. * their TTL)? */
  149. #define MAX_DNS_ENTRY_AGE (30*60)
  150. /** How long do we cache/tell clients to cache DNS records when no TTL is
  151. * known? */
  152. #define DEFAULT_DNS_TTL (30*60)
  153. /** How long can a TTL be before we stop believing it? */
  154. #define MAX_DNS_TTL (3*60*60)
  155. /** How small can a TTL be before we stop believing it? Provides rudimentary
  156. * pinning. */
  157. #define MIN_DNS_TTL 60
  158. /** How often do we rotate onion keys? */
  159. #define MIN_ONION_KEY_LIFETIME (7*24*60*60)
  160. /** How often do we rotate TLS contexts? */
  161. #define MAX_SSL_KEY_LIFETIME_INTERNAL (2*60*60)
  162. /** What expiry time shall we place on our SSL certs? */
  163. #define MAX_SSL_KEY_LIFETIME_ADVERTISED (365*24*60*60)
  164. /** How old do we allow a router to get before removing it
  165. * from the router list? In seconds. */
  166. #define ROUTER_MAX_AGE (60*60*48)
  167. /** How old can a router get before we (as a server) will no longer
  168. * consider it live? In seconds. */
  169. #define ROUTER_MAX_AGE_TO_PUBLISH (60*60*24)
  170. /** How old do we let a saved descriptor get before force-removing it? */
  171. #define OLD_ROUTER_DESC_MAX_AGE (60*60*24*5)
  172. /** Possible rules for generating circuit IDs on an OR connection. */
  173. typedef enum {
  174. CIRC_ID_TYPE_LOWER=0, /**< Pick from 0..1<<15-1. */
  175. CIRC_ID_TYPE_HIGHER=1, /**< Pick from 1<<15..1<<16-1. */
  176. /** The other side of a connection is an OP: never create circuits to it,
  177. * and let it use any circuit ID it wants. */
  178. CIRC_ID_TYPE_NEITHER=2
  179. } circ_id_type_t;
  180. #define CONN_TYPE_MIN_ 3
  181. /** Type for sockets listening for OR connections. */
  182. #define CONN_TYPE_OR_LISTENER 3
  183. /** A bidirectional TLS connection transmitting a sequence of cells.
  184. * May be from an OR to an OR, or from an OP to an OR. */
  185. #define CONN_TYPE_OR 4
  186. /** A TCP connection from an onion router to a stream's destination. */
  187. #define CONN_TYPE_EXIT 5
  188. /** Type for sockets listening for SOCKS connections. */
  189. #define CONN_TYPE_AP_LISTENER 6
  190. /** A SOCKS proxy connection from the user application to the onion
  191. * proxy. */
  192. #define CONN_TYPE_AP 7
  193. /** Type for sockets listening for HTTP connections to the directory server. */
  194. #define CONN_TYPE_DIR_LISTENER 8
  195. /** Type for HTTP connections to the directory server. */
  196. #define CONN_TYPE_DIR 9
  197. /** Connection from the main process to a CPU worker process. */
  198. #define CONN_TYPE_CPUWORKER 10
  199. /** Type for listening for connections from user interface process. */
  200. #define CONN_TYPE_CONTROL_LISTENER 11
  201. /** Type for connections from user interface process. */
  202. #define CONN_TYPE_CONTROL 12
  203. /** Type for sockets listening for transparent connections redirected by pf or
  204. * netfilter. */
  205. #define CONN_TYPE_AP_TRANS_LISTENER 13
  206. /** Type for sockets listening for transparent connections redirected by
  207. * natd. */
  208. #define CONN_TYPE_AP_NATD_LISTENER 14
  209. /** Type for sockets listening for DNS requests. */
  210. #define CONN_TYPE_AP_DNS_LISTENER 15
  211. #define CONN_TYPE_MAX_ 15
  212. /* !!!! If CONN_TYPE_MAX_ is ever over 15, we must grow the type field in
  213. * connection_t. */
  214. /* Proxy client types */
  215. #define PROXY_NONE 0
  216. #define PROXY_CONNECT 1
  217. #define PROXY_SOCKS4 2
  218. #define PROXY_SOCKS5 3
  219. /* !!!! If there is ever a PROXY_* type over 2, we must grow the proxy_type
  220. * field in or_connection_t */
  221. /* pluggable transports proxy type */
  222. #define PROXY_PLUGGABLE 4
  223. /* Proxy client handshake states */
  224. /* We use a proxy but we haven't even connected to it yet. */
  225. #define PROXY_INFANT 1
  226. /* We use an HTTP proxy and we've sent the CONNECT command. */
  227. #define PROXY_HTTPS_WANT_CONNECT_OK 2
  228. /* We use a SOCKS4 proxy and we've sent the CONNECT command. */
  229. #define PROXY_SOCKS4_WANT_CONNECT_OK 3
  230. /* We use a SOCKS5 proxy and we try to negotiate without
  231. any authentication . */
  232. #define PROXY_SOCKS5_WANT_AUTH_METHOD_NONE 4
  233. /* We use a SOCKS5 proxy and we try to negotiate with
  234. Username/Password authentication . */
  235. #define PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929 5
  236. /* We use a SOCKS5 proxy and we just sent our credentials. */
  237. #define PROXY_SOCKS5_WANT_AUTH_RFC1929_OK 6
  238. /* We use a SOCKS5 proxy and we just sent our CONNECT command. */
  239. #define PROXY_SOCKS5_WANT_CONNECT_OK 7
  240. /* We use a proxy and we CONNECTed successfully!. */
  241. #define PROXY_CONNECTED 8
  242. /** True iff <b>x</b> is an edge connection. */
  243. #define CONN_IS_EDGE(x) \
  244. ((x)->type == CONN_TYPE_EXIT || (x)->type == CONN_TYPE_AP)
  245. /** State for any listener connection. */
  246. #define LISTENER_STATE_READY 0
  247. #define CPUWORKER_STATE_MIN_ 1
  248. /** State for a connection to a cpuworker process that's idle. */
  249. #define CPUWORKER_STATE_IDLE 1
  250. /** State for a connection to a cpuworker process that's processing a
  251. * handshake. */
  252. #define CPUWORKER_STATE_BUSY_ONION 2
  253. #define CPUWORKER_STATE_MAX_ 2
  254. #define CPUWORKER_TASK_ONION CPUWORKER_STATE_BUSY_ONION
  255. #define OR_CONN_STATE_MIN_ 1
  256. /** State for a connection to an OR: waiting for connect() to finish. */
  257. #define OR_CONN_STATE_CONNECTING 1
  258. /** State for a connection to an OR: waiting for proxy handshake to complete */
  259. #define OR_CONN_STATE_PROXY_HANDSHAKING 2
  260. /** State for an OR connection client: SSL is handshaking, not done
  261. * yet. */
  262. #define OR_CONN_STATE_TLS_HANDSHAKING 3
  263. /** State for a connection to an OR: We're doing a second SSL handshake for
  264. * renegotiation purposes. (V2 handshake only.) */
  265. #define OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING 4
  266. /** State for a connection at an OR: We're waiting for the client to
  267. * renegotiate (to indicate a v2 handshake) or send a versions cell (to
  268. * indicate a v3 handshake) */
  269. #define OR_CONN_STATE_TLS_SERVER_RENEGOTIATING 5
  270. /** State for an OR connection: We're done with our SSL handshake, we've done
  271. * renegotiation, but we haven't yet negotiated link protocol versions and
  272. * sent a netinfo cell. */
  273. #define OR_CONN_STATE_OR_HANDSHAKING_V2 6
  274. /** State for an OR connection: We're done with our SSL handshake, but we
  275. * haven't yet negotiated link protocol versions, done a V3 handshake, and
  276. * sent a netinfo cell. */
  277. #define OR_CONN_STATE_OR_HANDSHAKING_V3 7
  278. /** State for an OR connection: Ready to send/receive cells. */
  279. #define OR_CONN_STATE_OPEN 8
  280. #define OR_CONN_STATE_MAX_ 8
  281. #define EXIT_CONN_STATE_MIN_ 1
  282. /** State for an exit connection: waiting for response from DNS farm. */
  283. #define EXIT_CONN_STATE_RESOLVING 1
  284. /** State for an exit connection: waiting for connect() to finish. */
  285. #define EXIT_CONN_STATE_CONNECTING 2
  286. /** State for an exit connection: open and ready to transmit data. */
  287. #define EXIT_CONN_STATE_OPEN 3
  288. /** State for an exit connection: waiting to be removed. */
  289. #define EXIT_CONN_STATE_RESOLVEFAILED 4
  290. #define EXIT_CONN_STATE_MAX_ 4
  291. /* The AP state values must be disjoint from the EXIT state values. */
  292. #define AP_CONN_STATE_MIN_ 5
  293. /** State for a SOCKS connection: waiting for SOCKS request. */
  294. #define AP_CONN_STATE_SOCKS_WAIT 5
  295. /** State for a SOCKS connection: got a y.onion URL; waiting to receive
  296. * rendezvous descriptor. */
  297. #define AP_CONN_STATE_RENDDESC_WAIT 6
  298. /** The controller will attach this connection to a circuit; it isn't our
  299. * job to do so. */
  300. #define AP_CONN_STATE_CONTROLLER_WAIT 7
  301. /** State for a SOCKS connection: waiting for a completed circuit. */
  302. #define AP_CONN_STATE_CIRCUIT_WAIT 8
  303. /** State for a SOCKS connection: sent BEGIN, waiting for CONNECTED. */
  304. #define AP_CONN_STATE_CONNECT_WAIT 9
  305. /** State for a SOCKS connection: sent RESOLVE, waiting for RESOLVED. */
  306. #define AP_CONN_STATE_RESOLVE_WAIT 10
  307. /** State for a SOCKS connection: ready to send and receive. */
  308. #define AP_CONN_STATE_OPEN 11
  309. /** State for a transparent natd connection: waiting for original
  310. * destination. */
  311. #define AP_CONN_STATE_NATD_WAIT 12
  312. #define AP_CONN_STATE_MAX_ 12
  313. /** True iff the AP_CONN_STATE_* value <b>s</b> means that the corresponding
  314. * edge connection is not attached to any circuit. */
  315. #define AP_CONN_STATE_IS_UNATTACHED(s) \
  316. ((s) <= AP_CONN_STATE_CIRCUIT_WAIT || (s) == AP_CONN_STATE_NATD_WAIT)
  317. #define DIR_CONN_STATE_MIN_ 1
  318. /** State for connection to directory server: waiting for connect(). */
  319. #define DIR_CONN_STATE_CONNECTING 1
  320. /** State for connection to directory server: sending HTTP request. */
  321. #define DIR_CONN_STATE_CLIENT_SENDING 2
  322. /** State for connection to directory server: reading HTTP response. */
  323. #define DIR_CONN_STATE_CLIENT_READING 3
  324. /** State for connection to directory server: happy and finished. */
  325. #define DIR_CONN_STATE_CLIENT_FINISHED 4
  326. /** State for connection at directory server: waiting for HTTP request. */
  327. #define DIR_CONN_STATE_SERVER_COMMAND_WAIT 5
  328. /** State for connection at directory server: sending HTTP response. */
  329. #define DIR_CONN_STATE_SERVER_WRITING 6
  330. #define DIR_CONN_STATE_MAX_ 6
  331. /** True iff the purpose of <b>conn</b> means that it's a server-side
  332. * directory connection. */
  333. #define DIR_CONN_IS_SERVER(conn) ((conn)->purpose == DIR_PURPOSE_SERVER)
  334. #define CONTROL_CONN_STATE_MIN_ 1
  335. /** State for a control connection: Authenticated and accepting v1 commands. */
  336. #define CONTROL_CONN_STATE_OPEN 1
  337. /** State for a control connection: Waiting for authentication; speaking
  338. * protocol v1. */
  339. #define CONTROL_CONN_STATE_NEEDAUTH 2
  340. #define CONTROL_CONN_STATE_MAX_ 2
  341. #define DIR_PURPOSE_MIN_ 3
  342. /** A connection to a directory server: download a rendezvous
  343. * descriptor. */
  344. #define DIR_PURPOSE_FETCH_RENDDESC 3
  345. /** A connection to a directory server: set after a rendezvous
  346. * descriptor is downloaded. */
  347. #define DIR_PURPOSE_HAS_FETCHED_RENDDESC 4
  348. /** A connection to a directory server: download one or more v2
  349. * network-status objects */
  350. #define DIR_PURPOSE_FETCH_V2_NETWORKSTATUS 5
  351. /** A connection to a directory server: download one or more server
  352. * descriptors. */
  353. #define DIR_PURPOSE_FETCH_SERVERDESC 6
  354. /** A connection to a directory server: download one or more extra-info
  355. * documents. */
  356. #define DIR_PURPOSE_FETCH_EXTRAINFO 7
  357. /** A connection to a directory server: upload a server descriptor. */
  358. #define DIR_PURPOSE_UPLOAD_DIR 8
  359. /** A connection to a directory server: upload a rendezvous
  360. * descriptor. */
  361. #define DIR_PURPOSE_UPLOAD_RENDDESC 9
  362. /** A connection to a directory server: upload a v3 networkstatus vote. */
  363. #define DIR_PURPOSE_UPLOAD_VOTE 10
  364. /** A connection to a directory server: upload a v3 consensus signature */
  365. #define DIR_PURPOSE_UPLOAD_SIGNATURES 11
  366. /** A connection to a directory server: download one or more v3 networkstatus
  367. * votes. */
  368. #define DIR_PURPOSE_FETCH_STATUS_VOTE 12
  369. /** A connection to a directory server: download a v3 detached signatures
  370. * object for a consensus. */
  371. #define DIR_PURPOSE_FETCH_DETACHED_SIGNATURES 13
  372. /** A connection to a directory server: download a v3 networkstatus
  373. * consensus. */
  374. #define DIR_PURPOSE_FETCH_CONSENSUS 14
  375. /** A connection to a directory server: download one or more directory
  376. * authority certificates. */
  377. #define DIR_PURPOSE_FETCH_CERTIFICATE 15
  378. /** Purpose for connection at a directory server. */
  379. #define DIR_PURPOSE_SERVER 16
  380. /** A connection to a hidden service directory server: upload a v2 rendezvous
  381. * descriptor. */
  382. #define DIR_PURPOSE_UPLOAD_RENDDESC_V2 17
  383. /** A connection to a hidden service directory server: download a v2 rendezvous
  384. * descriptor. */
  385. #define DIR_PURPOSE_FETCH_RENDDESC_V2 18
  386. /** A connection to a directory server: download a microdescriptor. */
  387. #define DIR_PURPOSE_FETCH_MICRODESC 19
  388. #define DIR_PURPOSE_MAX_ 19
  389. /** True iff <b>p</b> is a purpose corresponding to uploading data to a
  390. * directory server. */
  391. #define DIR_PURPOSE_IS_UPLOAD(p) \
  392. ((p)==DIR_PURPOSE_UPLOAD_DIR || \
  393. (p)==DIR_PURPOSE_UPLOAD_RENDDESC || \
  394. (p)==DIR_PURPOSE_UPLOAD_VOTE || \
  395. (p)==DIR_PURPOSE_UPLOAD_SIGNATURES)
  396. #define EXIT_PURPOSE_MIN_ 1
  397. /** This exit stream wants to do an ordinary connect. */
  398. #define EXIT_PURPOSE_CONNECT 1
  399. /** This exit stream wants to do a resolve (either normal or reverse). */
  400. #define EXIT_PURPOSE_RESOLVE 2
  401. #define EXIT_PURPOSE_MAX_ 2
  402. /* !!!! If any connection purpose is ever over 31, we must grow the type
  403. * field in connection_t. */
  404. /** Circuit state: I'm the origin, still haven't done all my handshakes. */
  405. #define CIRCUIT_STATE_BUILDING 0
  406. /** Circuit state: Waiting to process the onionskin. */
  407. #define CIRCUIT_STATE_ONIONSKIN_PENDING 1
  408. /** Circuit state: I'd like to deliver a create, but my n_chan is still
  409. * connecting. */
  410. #define CIRCUIT_STATE_CHAN_WAIT 2
  411. /** Circuit state: onionskin(s) processed, ready to send/receive cells. */
  412. #define CIRCUIT_STATE_OPEN 3
  413. #define CIRCUIT_PURPOSE_MIN_ 1
  414. /* these circuits were initiated elsewhere */
  415. #define CIRCUIT_PURPOSE_OR_MIN_ 1
  416. /** OR-side circuit purpose: normal circuit, at OR. */
  417. #define CIRCUIT_PURPOSE_OR 1
  418. /** OR-side circuit purpose: At OR, from Bob, waiting for intro from Alices. */
  419. #define CIRCUIT_PURPOSE_INTRO_POINT 2
  420. /** OR-side circuit purpose: At OR, from Alice, waiting for Bob. */
  421. #define CIRCUIT_PURPOSE_REND_POINT_WAITING 3
  422. /** OR-side circuit purpose: At OR, both circuits have this purpose. */
  423. #define CIRCUIT_PURPOSE_REND_ESTABLISHED 4
  424. #define CIRCUIT_PURPOSE_OR_MAX_ 4
  425. /* these circuits originate at this node */
  426. /* here's how circ client-side purposes work:
  427. * normal circuits are C_GENERAL.
  428. * circuits that are c_introducing are either on their way to
  429. * becoming open, or they are open and waiting for a
  430. * suitable rendcirc before they send the intro.
  431. * circuits that are c_introduce_ack_wait have sent the intro,
  432. * but haven't gotten a response yet.
  433. * circuits that are c_establish_rend are either on their way
  434. * to becoming open, or they are open and have sent the
  435. * establish_rendezvous cell but haven't received an ack.
  436. * circuits that are c_rend_ready are open and have received a
  437. * rend ack, but haven't heard from bob yet. if they have a
  438. * buildstate->pending_final_cpath then they're expecting a
  439. * cell from bob, else they're not.
  440. * circuits that are c_rend_ready_intro_acked are open, and
  441. * some intro circ has sent its intro and received an ack.
  442. * circuits that are c_rend_joined are open, have heard from
  443. * bob, and are talking to him.
  444. */
  445. /** Client-side circuit purpose: Normal circuit, with cpath. */
  446. #define CIRCUIT_PURPOSE_C_GENERAL 5
  447. /** Client-side circuit purpose: at Alice, connecting to intro point. */
  448. #define CIRCUIT_PURPOSE_C_INTRODUCING 6
  449. /** Client-side circuit purpose: at Alice, sent INTRODUCE1 to intro point,
  450. * waiting for ACK/NAK. */
  451. #define CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT 7
  452. /** Client-side circuit purpose: at Alice, introduced and acked, closing. */
  453. #define CIRCUIT_PURPOSE_C_INTRODUCE_ACKED 8
  454. /** Client-side circuit purpose: at Alice, waiting for ack. */
  455. #define CIRCUIT_PURPOSE_C_ESTABLISH_REND 9
  456. /** Client-side circuit purpose: at Alice, waiting for Bob. */
  457. #define CIRCUIT_PURPOSE_C_REND_READY 10
  458. /** Client-side circuit purpose: at Alice, waiting for Bob, INTRODUCE
  459. * has been acknowledged. */
  460. #define CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED 11
  461. /** Client-side circuit purpose: at Alice, rendezvous established. */
  462. #define CIRCUIT_PURPOSE_C_REND_JOINED 12
  463. /** This circuit is used for build time measurement only */
  464. #define CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT 13
  465. #define CIRCUIT_PURPOSE_C_MAX_ 13
  466. /** Hidden-service-side circuit purpose: at Bob, waiting for introductions. */
  467. #define CIRCUIT_PURPOSE_S_ESTABLISH_INTRO 14
  468. /** Hidden-service-side circuit purpose: at Bob, successfully established
  469. * intro. */
  470. #define CIRCUIT_PURPOSE_S_INTRO 15
  471. /** Hidden-service-side circuit purpose: at Bob, connecting to rend point. */
  472. #define CIRCUIT_PURPOSE_S_CONNECT_REND 16
  473. /** Hidden-service-side circuit purpose: at Bob, rendezvous established. */
  474. #define CIRCUIT_PURPOSE_S_REND_JOINED 17
  475. /** A testing circuit; not meant to be used for actual traffic. */
  476. #define CIRCUIT_PURPOSE_TESTING 18
  477. /** A controller made this circuit and Tor should not use it. */
  478. #define CIRCUIT_PURPOSE_CONTROLLER 19
  479. #define CIRCUIT_PURPOSE_MAX_ 19
  480. /** A catch-all for unrecognized purposes. Currently we don't expect
  481. * to make or see any circuits with this purpose. */
  482. #define CIRCUIT_PURPOSE_UNKNOWN 255
  483. /** True iff the circuit purpose <b>p</b> is for a circuit that
  484. * originated at this node. */
  485. #define CIRCUIT_PURPOSE_IS_ORIGIN(p) ((p)>CIRCUIT_PURPOSE_OR_MAX_)
  486. /** True iff the circuit purpose <b>p</b> is for a circuit that originated
  487. * here to serve as a client. (Hidden services don't count here.) */
  488. #define CIRCUIT_PURPOSE_IS_CLIENT(p) \
  489. ((p)> CIRCUIT_PURPOSE_OR_MAX_ && \
  490. (p)<=CIRCUIT_PURPOSE_C_MAX_)
  491. /** True iff the circuit_t <b>c</b> is actually an origin_circuit_t. */
  492. #define CIRCUIT_IS_ORIGIN(c) (CIRCUIT_PURPOSE_IS_ORIGIN((c)->purpose))
  493. /** True iff the circuit purpose <b>p</b> is for an established rendezvous
  494. * circuit. */
  495. #define CIRCUIT_PURPOSE_IS_ESTABLISHED_REND(p) \
  496. ((p) == CIRCUIT_PURPOSE_C_REND_JOINED || \
  497. (p) == CIRCUIT_PURPOSE_S_REND_JOINED)
  498. /** How many circuits do we want simultaneously in-progress to handle
  499. * a given stream? */
  500. #define MIN_CIRCUITS_HANDLING_STREAM 2
  501. /* These RELAY_COMMAND constants define values for relay cell commands, and
  502. * must match those defined in tor-spec.txt. */
  503. #define RELAY_COMMAND_BEGIN 1
  504. #define RELAY_COMMAND_DATA 2
  505. #define RELAY_COMMAND_END 3
  506. #define RELAY_COMMAND_CONNECTED 4
  507. #define RELAY_COMMAND_SENDME 5
  508. #define RELAY_COMMAND_EXTEND 6
  509. #define RELAY_COMMAND_EXTENDED 7
  510. #define RELAY_COMMAND_TRUNCATE 8
  511. #define RELAY_COMMAND_TRUNCATED 9
  512. #define RELAY_COMMAND_DROP 10
  513. #define RELAY_COMMAND_RESOLVE 11
  514. #define RELAY_COMMAND_RESOLVED 12
  515. #define RELAY_COMMAND_BEGIN_DIR 13
  516. #define RELAY_COMMAND_ESTABLISH_INTRO 32
  517. #define RELAY_COMMAND_ESTABLISH_RENDEZVOUS 33
  518. #define RELAY_COMMAND_INTRODUCE1 34
  519. #define RELAY_COMMAND_INTRODUCE2 35
  520. #define RELAY_COMMAND_RENDEZVOUS1 36
  521. #define RELAY_COMMAND_RENDEZVOUS2 37
  522. #define RELAY_COMMAND_INTRO_ESTABLISHED 38
  523. #define RELAY_COMMAND_RENDEZVOUS_ESTABLISHED 39
  524. #define RELAY_COMMAND_INTRODUCE_ACK 40
  525. /* Reasons why an OR connection is closed. */
  526. #define END_OR_CONN_REASON_DONE 1
  527. #define END_OR_CONN_REASON_REFUSED 2 /* connection refused */
  528. #define END_OR_CONN_REASON_OR_IDENTITY 3
  529. #define END_OR_CONN_REASON_CONNRESET 4 /* connection reset by peer */
  530. #define END_OR_CONN_REASON_TIMEOUT 5
  531. #define END_OR_CONN_REASON_NO_ROUTE 6 /* no route to host/net */
  532. #define END_OR_CONN_REASON_IO_ERROR 7 /* read/write error */
  533. #define END_OR_CONN_REASON_RESOURCE_LIMIT 8 /* sockets, buffers, etc */
  534. #define END_OR_CONN_REASON_MISC 9
  535. /* Reasons why we (or a remote OR) might close a stream. See tor-spec.txt for
  536. * documentation of these. The values must match. */
  537. #define END_STREAM_REASON_MISC 1
  538. #define END_STREAM_REASON_RESOLVEFAILED 2
  539. #define END_STREAM_REASON_CONNECTREFUSED 3
  540. #define END_STREAM_REASON_EXITPOLICY 4
  541. #define END_STREAM_REASON_DESTROY 5
  542. #define END_STREAM_REASON_DONE 6
  543. #define END_STREAM_REASON_TIMEOUT 7
  544. #define END_STREAM_REASON_NOROUTE 8
  545. #define END_STREAM_REASON_HIBERNATING 9
  546. #define END_STREAM_REASON_INTERNAL 10
  547. #define END_STREAM_REASON_RESOURCELIMIT 11
  548. #define END_STREAM_REASON_CONNRESET 12
  549. #define END_STREAM_REASON_TORPROTOCOL 13
  550. #define END_STREAM_REASON_NOTDIRECTORY 14
  551. #define END_STREAM_REASON_ENTRYPOLICY 15
  552. /* These high-numbered end reasons are not part of the official spec,
  553. * and are not intended to be put in relay end cells. They are here
  554. * to be more informative when sending back socks replies to the
  555. * application. */
  556. /* XXXX 256 is no longer used; feel free to reuse it. */
  557. /** We were unable to attach the connection to any circuit at all. */
  558. /* XXXX the ways we use this one don't make a lot of sense. */
  559. #define END_STREAM_REASON_CANT_ATTACH 257
  560. /** We can't connect to any directories at all, so we killed our streams
  561. * before they can time out. */
  562. #define END_STREAM_REASON_NET_UNREACHABLE 258
  563. /** This is a SOCKS connection, and the client used (or misused) the SOCKS
  564. * protocol in a way we couldn't handle. */
  565. #define END_STREAM_REASON_SOCKSPROTOCOL 259
  566. /** This is a transparent proxy connection, but we can't extract the original
  567. * target address:port. */
  568. #define END_STREAM_REASON_CANT_FETCH_ORIG_DEST 260
  569. /** This is a connection on the NATD port, and the destination IP:Port was
  570. * either ill-formed or out-of-range. */
  571. #define END_STREAM_REASON_INVALID_NATD_DEST 261
  572. /** The target address is in a private network (like 127.0.0.1 or 10.0.0.1);
  573. * you don't want to do that over a randomly chosen exit */
  574. #define END_STREAM_REASON_PRIVATE_ADDR 262
  575. /** Bitwise-and this value with endreason to mask out all flags. */
  576. #define END_STREAM_REASON_MASK 511
  577. /** Bitwise-or this with the argument to control_event_stream_status
  578. * to indicate that the reason came from an END cell. */
  579. #define END_STREAM_REASON_FLAG_REMOTE 512
  580. /** Bitwise-or this with the argument to control_event_stream_status
  581. * to indicate that we already sent a CLOSED stream event. */
  582. #define END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED 1024
  583. /** Bitwise-or this with endreason to indicate that we already sent
  584. * a socks reply, and no further reply needs to be sent from
  585. * connection_mark_unattached_ap(). */
  586. #define END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED 2048
  587. /** Reason for remapping an AP connection's address: we have a cached
  588. * answer. */
  589. #define REMAP_STREAM_SOURCE_CACHE 1
  590. /** Reason for remapping an AP connection's address: the exit node told us an
  591. * answer. */
  592. #define REMAP_STREAM_SOURCE_EXIT 2
  593. /* 'type' values to use in RESOLVED cells. Specified in tor-spec.txt. */
  594. #define RESOLVED_TYPE_HOSTNAME 0
  595. #define RESOLVED_TYPE_IPV4 4
  596. #define RESOLVED_TYPE_IPV6 6
  597. #define RESOLVED_TYPE_ERROR_TRANSIENT 0xF0
  598. #define RESOLVED_TYPE_ERROR 0xF1
  599. /* Negative reasons are internal: we never send them in a DESTROY or TRUNCATE
  600. * call; they only go to the controller for tracking */
  601. /** Our post-timeout circuit time measurement period expired.
  602. * We must give up now */
  603. #define END_CIRC_REASON_MEASUREMENT_EXPIRED -3
  604. /** We couldn't build a path for this circuit. */
  605. #define END_CIRC_REASON_NOPATH -2
  606. /** Catch-all "other" reason for closing origin circuits. */
  607. #define END_CIRC_AT_ORIGIN -1
  608. /* Reasons why we (or a remote OR) might close a circuit. See tor-spec.txt for
  609. * documentation of these. */
  610. #define END_CIRC_REASON_MIN_ 0
  611. #define END_CIRC_REASON_NONE 0
  612. #define END_CIRC_REASON_TORPROTOCOL 1
  613. #define END_CIRC_REASON_INTERNAL 2
  614. #define END_CIRC_REASON_REQUESTED 3
  615. #define END_CIRC_REASON_HIBERNATING 4
  616. #define END_CIRC_REASON_RESOURCELIMIT 5
  617. #define END_CIRC_REASON_CONNECTFAILED 6
  618. #define END_CIRC_REASON_OR_IDENTITY 7
  619. #define END_CIRC_REASON_CHANNEL_CLOSED 8
  620. #define END_CIRC_REASON_FINISHED 9
  621. #define END_CIRC_REASON_TIMEOUT 10
  622. #define END_CIRC_REASON_DESTROYED 11
  623. #define END_CIRC_REASON_NOSUCHSERVICE 12
  624. #define END_CIRC_REASON_MAX_ 12
  625. /** Bitwise-OR this with the argument to circuit_mark_for_close() or
  626. * control_event_circuit_status() to indicate that the reason was
  627. * passed through from a destroy or truncate cell. */
  628. #define END_CIRC_REASON_FLAG_REMOTE 512
  629. /** Length of 'y' portion of 'y.onion' URL. */
  630. #define REND_SERVICE_ID_LEN_BASE32 16
  631. /** Length of 'y.onion' including '.onion' URL. */
  632. #define REND_SERVICE_ADDRESS_LEN (16+1+5)
  633. /** Length of a binary-encoded rendezvous service ID. */
  634. #define REND_SERVICE_ID_LEN 10
  635. /** Time period for which a v2 descriptor will be valid. */
  636. #define REND_TIME_PERIOD_V2_DESC_VALIDITY (24*60*60)
  637. /** Time period within which two sets of v2 descriptors will be uploaded in
  638. * parallel. */
  639. #define REND_TIME_PERIOD_OVERLAPPING_V2_DESCS (60*60)
  640. /** Number of non-consecutive replicas (i.e. distributed somewhere
  641. * in the ring) for a descriptor. */
  642. #define REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS 2
  643. /** Number of consecutive replicas for a descriptor. */
  644. #define REND_NUMBER_OF_CONSECUTIVE_REPLICAS 3
  645. /** Length of v2 descriptor ID (32 base32 chars = 160 bits). */
  646. #define REND_DESC_ID_V2_LEN_BASE32 32
  647. /** Length of the base32-encoded secret ID part of versioned hidden service
  648. * descriptors. */
  649. #define REND_SECRET_ID_PART_LEN_BASE32 32
  650. /** Length of the base32-encoded hash of an introduction point's
  651. * identity key. */
  652. #define REND_INTRO_POINT_ID_LEN_BASE32 32
  653. /** Length of the descriptor cookie that is used for client authorization
  654. * to hidden services. */
  655. #define REND_DESC_COOKIE_LEN 16
  656. /** Length of the base64-encoded descriptor cookie that is used for
  657. * exchanging client authorization between hidden service and client. */
  658. #define REND_DESC_COOKIE_LEN_BASE64 22
  659. /** Length of client identifier in encrypted introduction points for hidden
  660. * service authorization type 'basic'. */
  661. #define REND_BASIC_AUTH_CLIENT_ID_LEN 4
  662. /** Multiple of the number of clients to which the real number of clients
  663. * is padded with fake clients for hidden service authorization type
  664. * 'basic'. */
  665. #define REND_BASIC_AUTH_CLIENT_MULTIPLE 16
  666. /** Length of client entry consisting of client identifier and encrypted
  667. * session key for hidden service authorization type 'basic'. */
  668. #define REND_BASIC_AUTH_CLIENT_ENTRY_LEN (REND_BASIC_AUTH_CLIENT_ID_LEN \
  669. + CIPHER_KEY_LEN)
  670. /** Maximum size of v2 hidden service descriptors. */
  671. #define REND_DESC_MAX_SIZE (20 * 1024)
  672. /** Legal characters for use in authorized client names for a hidden
  673. * service. */
  674. #define REND_LEGAL_CLIENTNAME_CHARACTERS \
  675. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-_"
  676. /** Maximum length of authorized client names for a hidden service. */
  677. #define REND_CLIENTNAME_MAX_LEN 16
  678. /** Length of the rendezvous cookie that is used to connect circuits at the
  679. * rendezvous point. */
  680. #define REND_COOKIE_LEN DIGEST_LEN
  681. /** Client authorization type that a hidden service performs. */
  682. typedef enum rend_auth_type_t {
  683. REND_NO_AUTH = 0,
  684. REND_BASIC_AUTH = 1,
  685. REND_STEALTH_AUTH = 2,
  686. } rend_auth_type_t;
  687. /** Client-side configuration of authorization for a hidden service. */
  688. typedef struct rend_service_authorization_t {
  689. char descriptor_cookie[REND_DESC_COOKIE_LEN];
  690. char onion_address[REND_SERVICE_ADDRESS_LEN+1];
  691. rend_auth_type_t auth_type;
  692. } rend_service_authorization_t;
  693. /** Client- and server-side data that is used for hidden service connection
  694. * establishment. Not all fields contain data depending on where this struct
  695. * is used. */
  696. typedef struct rend_data_t {
  697. /** Onion address (without the .onion part) that a client requests. */
  698. char onion_address[REND_SERVICE_ID_LEN_BASE32+1];
  699. /** (Optional) descriptor cookie that is used by a client. */
  700. char descriptor_cookie[REND_DESC_COOKIE_LEN];
  701. /** Authorization type for accessing a service used by a client. */
  702. rend_auth_type_t auth_type;
  703. /** Hash of the hidden service's PK used by a service. */
  704. char rend_pk_digest[DIGEST_LEN];
  705. /** Rendezvous cookie used by both, client and service. */
  706. char rend_cookie[REND_COOKIE_LEN];
  707. } rend_data_t;
  708. /** Time interval for tracking replays of DH public keys received in
  709. * INTRODUCE2 cells. Used only to avoid launching multiple
  710. * simultaneous attempts to connect to the same rendezvous point. */
  711. #define REND_REPLAY_TIME_INTERVAL (5 * 60)
  712. /** Used to indicate which way a cell is going on a circuit. */
  713. typedef enum {
  714. CELL_DIRECTION_IN=1, /**< The cell is moving towards the origin. */
  715. CELL_DIRECTION_OUT=2, /**< The cell is moving away from the origin. */
  716. } cell_direction_t;
  717. /** Initial value for both sides of a circuit transmission window when the
  718. * circuit is initialized. Measured in cells. */
  719. #define CIRCWINDOW_START 1000
  720. #define CIRCWINDOW_START_MIN 100
  721. #define CIRCWINDOW_START_MAX 1000
  722. /** Amount to increment a circuit window when we get a circuit SENDME. */
  723. #define CIRCWINDOW_INCREMENT 100
  724. /** Initial value on both sides of a stream transmission window when the
  725. * stream is initialized. Measured in cells. */
  726. #define STREAMWINDOW_START 500
  727. /** Amount to increment a stream window when we get a stream SENDME. */
  728. #define STREAMWINDOW_INCREMENT 50
  729. /* Cell commands. These values are defined in tor-spec.txt. */
  730. #define CELL_PADDING 0
  731. #define CELL_CREATE 1
  732. #define CELL_CREATED 2
  733. #define CELL_RELAY 3
  734. #define CELL_DESTROY 4
  735. #define CELL_CREATE_FAST 5
  736. #define CELL_CREATED_FAST 6
  737. #define CELL_VERSIONS 7
  738. #define CELL_NETINFO 8
  739. #define CELL_RELAY_EARLY 9
  740. #define CELL_VPADDING 128
  741. #define CELL_CERTS 129
  742. #define CELL_AUTH_CHALLENGE 130
  743. #define CELL_AUTHENTICATE 131
  744. #define CELL_AUTHORIZE 132
  745. /** How long to test reachability before complaining to the user. */
  746. #define TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT (20*60)
  747. /** Legal characters in a nickname. */
  748. #define LEGAL_NICKNAME_CHARACTERS \
  749. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  750. /** Name to use in client TLS certificates if no nickname is given. Once
  751. * Tor 0.1.2.x is obsolete, we can remove this. */
  752. #define DEFAULT_CLIENT_NICKNAME "client"
  753. /** Name chosen by routers that don't configure nicknames */
  754. #define UNNAMED_ROUTER_NICKNAME "Unnamed"
  755. /** Number of bytes in a SOCKS4 header. */
  756. #define SOCKS4_NETWORK_LEN 8
  757. /*
  758. * Relay payload:
  759. * Relay command [1 byte]
  760. * Recognized [2 bytes]
  761. * Stream ID [2 bytes]
  762. * Partial SHA-1 [4 bytes]
  763. * Length [2 bytes]
  764. * Relay payload [498 bytes]
  765. */
  766. /** Number of bytes in a cell, minus cell header. */
  767. #define CELL_PAYLOAD_SIZE 509
  768. /** Number of bytes in a cell transmitted over the network. */
  769. #define CELL_NETWORK_SIZE 512
  770. /** Length of a header on a variable-length cell. */
  771. #define VAR_CELL_HEADER_SIZE 5
  772. /** Number of bytes in a relay cell's header (not including general cell
  773. * header). */
  774. #define RELAY_HEADER_SIZE (1+2+2+4+2)
  775. /** Largest number of bytes that can fit in a relay cell payload. */
  776. #define RELAY_PAYLOAD_SIZE (CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE)
  777. /** Identifies a circuit on an or_connection */
  778. typedef uint16_t circid_t;
  779. /** Identifies a stream on a circuit */
  780. typedef uint16_t streamid_t;
  781. /* channel_t typedef; struct channel_s is in channel.h */
  782. typedef struct channel_s channel_t;
  783. /* channel_listener_t typedef; struct channel_listener_s is in channel.h */
  784. typedef struct channel_listener_s channel_listener_t;
  785. /* channel states for channel_t */
  786. typedef enum {
  787. /*
  788. * Closed state - channel is inactive
  789. *
  790. * Permitted transitions from:
  791. * - CHANNEL_STATE_CLOSING
  792. * Permitted transitions to:
  793. * - CHANNEL_STATE_OPENING
  794. */
  795. CHANNEL_STATE_CLOSED = 0,
  796. /*
  797. * Opening state - channel is trying to connect
  798. *
  799. * Permitted transitions from:
  800. * - CHANNEL_STATE_CLOSED
  801. * Permitted transitions to:
  802. * - CHANNEL_STATE_CLOSING
  803. * - CHANNEL_STATE_ERROR
  804. * - CHANNEL_STATE_OPEN
  805. */
  806. CHANNEL_STATE_OPENING,
  807. /*
  808. * Open state - channel is active and ready for use
  809. *
  810. * Permitted transitions from:
  811. * - CHANNEL_STATE_MAINT
  812. * - CHANNEL_STATE_OPENING
  813. * Permitted transitions to:
  814. * - CHANNEL_STATE_CLOSING
  815. * - CHANNEL_STATE_ERROR
  816. * - CHANNEL_STATE_MAINT
  817. */
  818. CHANNEL_STATE_OPEN,
  819. /*
  820. * Maintenance state - channel is temporarily offline for subclass specific
  821. * maintenance activities such as TLS renegotiation.
  822. *
  823. * Permitted transitions from:
  824. * - CHANNEL_STATE_OPEN
  825. * Permitted transitions to:
  826. * - CHANNEL_STATE_CLOSING
  827. * - CHANNEL_STATE_ERROR
  828. * - CHANNEL_STATE_OPEN
  829. */
  830. CHANNEL_STATE_MAINT,
  831. /*
  832. * Closing state - channel is shutting down
  833. *
  834. * Permitted transitions from:
  835. * - CHANNEL_STATE_MAINT
  836. * - CHANNEL_STATE_OPEN
  837. * Permitted transitions to:
  838. * - CHANNEL_STATE_CLOSED,
  839. * - CHANNEL_STATE_ERROR
  840. */
  841. CHANNEL_STATE_CLOSING,
  842. /*
  843. * Error state - channel has experienced a permanent error
  844. *
  845. * Permitted transitions from:
  846. * - CHANNEL_STATE_CLOSING
  847. * - CHANNEL_STATE_MAINT
  848. * - CHANNEL_STATE_OPENING
  849. * - CHANNEL_STATE_OPEN
  850. * Permitted transitions to:
  851. * - None
  852. */
  853. CHANNEL_STATE_ERROR,
  854. /*
  855. * Placeholder for maximum state value
  856. */
  857. CHANNEL_STATE_LAST
  858. } channel_state_t;
  859. /* channel listener states for channel_listener_t */
  860. typedef enum {
  861. /*
  862. * Closed state - channel listener is inactive
  863. *
  864. * Permitted transitions from:
  865. * - CHANNEL_LISTENER_STATE_CLOSING
  866. * Permitted transitions to:
  867. * - CHANNEL_LISTENER_STATE_LISTENING
  868. */
  869. CHANNEL_LISTENER_STATE_CLOSED = 0,
  870. /*
  871. * Listening state - channel listener is listening for incoming
  872. * connections
  873. *
  874. * Permitted transitions from:
  875. * - CHANNEL_LISTENER_STATE_CLOSED
  876. * Permitted transitions to:
  877. * - CHANNEL_LISTENER_STATE_CLOSING
  878. * - CHANNEL_LISTENER_STATE_ERROR
  879. */
  880. CHANNEL_LISTENER_STATE_LISTENING,
  881. /*
  882. * Closing state - channel listener is shutting down
  883. *
  884. * Permitted transitions from:
  885. * - CHANNEL_LISTENER_STATE_LISTENING
  886. * Permitted transitions to:
  887. * - CHANNEL_LISTENER_STATE_CLOSED,
  888. * - CHANNEL_LISTENER_STATE_ERROR
  889. */
  890. CHANNEL_LISTENER_STATE_CLOSING,
  891. /*
  892. * Error state - channel listener has experienced a permanent error
  893. *
  894. * Permitted transitions from:
  895. * - CHANNEL_STATE_CLOSING
  896. * - CHANNEL_STATE_LISTENING
  897. * Permitted transitions to:
  898. * - None
  899. */
  900. CHANNEL_LISTENER_STATE_ERROR,
  901. /*
  902. * Placeholder for maximum state value
  903. */
  904. CHANNEL_LISTENER_STATE_LAST
  905. } channel_listener_state_t;
  906. /* TLS channel stuff */
  907. typedef struct channel_tls_s channel_tls_t;
  908. /* circuitmux_t typedef; struct circuitmux_s is in circuitmux.h */
  909. typedef struct circuitmux_s circuitmux_t;
  910. /** Parsed onion routing cell. All communication between nodes
  911. * is via cells. */
  912. typedef struct cell_t {
  913. circid_t circ_id; /**< Circuit which received the cell. */
  914. uint8_t command; /**< Type of the cell: one of CELL_PADDING, CELL_CREATE,
  915. * CELL_DESTROY, etc */
  916. uint8_t payload[CELL_PAYLOAD_SIZE]; /**< Cell body. */
  917. } cell_t;
  918. /** Parsed variable-length onion routing cell. */
  919. typedef struct var_cell_t {
  920. /** Type of the cell: CELL_VERSIONS, etc. */
  921. uint8_t command;
  922. /** Circuit thich received the cell */
  923. circid_t circ_id;
  924. /** Number of bytes actually stored in <b>payload</b> */
  925. uint16_t payload_len;
  926. /** Payload of this cell */
  927. uint8_t payload[FLEXIBLE_ARRAY_MEMBER];
  928. } var_cell_t;
  929. /** A cell as packed for writing to the network. */
  930. typedef struct packed_cell_t {
  931. struct packed_cell_t *next; /**< Next cell queued on this circuit. */
  932. char body[CELL_NETWORK_SIZE]; /**< Cell as packed for network. */
  933. } packed_cell_t;
  934. /** Number of cells added to a circuit queue including their insertion
  935. * time on 10 millisecond detail; used for buffer statistics. */
  936. typedef struct insertion_time_elem_t {
  937. struct insertion_time_elem_t *next; /**< Next element in queue. */
  938. uint32_t insertion_time; /**< When were cells inserted (in 10 ms steps
  939. * starting at 0:00 of the current day)? */
  940. unsigned counter; /**< How many cells were inserted? */
  941. } insertion_time_elem_t;
  942. /** Queue of insertion times. */
  943. typedef struct insertion_time_queue_t {
  944. struct insertion_time_elem_t *first; /**< First element in queue. */
  945. struct insertion_time_elem_t *last; /**< Last element in queue. */
  946. } insertion_time_queue_t;
  947. /** A queue of cells on a circuit, waiting to be added to the
  948. * or_connection_t's outbuf. */
  949. typedef struct cell_queue_t {
  950. packed_cell_t *head; /**< The first cell, or NULL if the queue is empty. */
  951. packed_cell_t *tail; /**< The last cell, or NULL if the queue is empty. */
  952. int n; /**< The number of cells in the queue. */
  953. insertion_time_queue_t *insertion_times; /**< Insertion times of cells. */
  954. } cell_queue_t;
  955. /** Beginning of a RELAY cell payload. */
  956. typedef struct {
  957. uint8_t command; /**< The end-to-end relay command. */
  958. uint16_t recognized; /**< Used to tell whether cell is for us. */
  959. streamid_t stream_id; /**< Which stream is this cell associated with? */
  960. char integrity[4]; /**< Used to tell whether cell is corrupted. */
  961. uint16_t length; /**< How long is the payload body? */
  962. } relay_header_t;
  963. typedef struct buf_t buf_t;
  964. typedef struct socks_request_t socks_request_t;
  965. #ifdef USE_BUFFEREVENTS
  966. #define generic_buffer_t struct evbuffer
  967. #else
  968. #define generic_buffer_t buf_t
  969. #endif
  970. /* Values for connection_t.magic: used to make sure that downcasts (casts from
  971. * connection_t to foo_connection_t) are safe. */
  972. #define BASE_CONNECTION_MAGIC 0x7C3C304Eu
  973. #define OR_CONNECTION_MAGIC 0x7D31FF03u
  974. #define EDGE_CONNECTION_MAGIC 0xF0374013u
  975. #define ENTRY_CONNECTION_MAGIC 0xbb4a5703
  976. #define DIR_CONNECTION_MAGIC 0x9988ffeeu
  977. #define CONTROL_CONNECTION_MAGIC 0x8abc765du
  978. #define LISTENER_CONNECTION_MAGIC 0x1a1ac741u
  979. /** Description of a connection to another host or process, and associated
  980. * data.
  981. *
  982. * A connection is named based on what it's connected to -- an "OR
  983. * connection" has a Tor node on the other end, an "exit
  984. * connection" has a website or other server on the other end, and an
  985. * "AP connection" has an application proxy (and thus a user) on the
  986. * other end.
  987. *
  988. * Every connection has a type and a state. Connections never change
  989. * their type, but can go through many state changes in their lifetime.
  990. *
  991. * Every connection has two associated input and output buffers.
  992. * Listeners don't use them. For non-listener connections, incoming
  993. * data is appended to conn->inbuf, and outgoing data is taken from
  994. * conn->outbuf. Connections differ primarily in the functions called
  995. * to fill and drain these buffers.
  996. */
  997. typedef struct connection_t {
  998. uint32_t magic; /**< For memory debugging: must equal one of
  999. * *_CONNECTION_MAGIC. */
  1000. uint8_t state; /**< Current state of this connection. */
  1001. unsigned int type:4; /**< What kind of connection is this? */
  1002. unsigned int purpose:5; /**< Only used for DIR and EXIT types currently. */
  1003. /* The next fields are all one-bit booleans. Some are only applicable to
  1004. * connection subtypes, but we hold them here anyway, to save space.
  1005. */
  1006. unsigned int read_blocked_on_bw:1; /**< Boolean: should we start reading
  1007. * again once the bandwidth throttler allows it? */
  1008. unsigned int write_blocked_on_bw:1; /**< Boolean: should we start writing
  1009. * again once the bandwidth throttler allows
  1010. * writes? */
  1011. unsigned int hold_open_until_flushed:1; /**< Despite this connection's being
  1012. * marked for close, do we flush it
  1013. * before closing it? */
  1014. unsigned int inbuf_reached_eof:1; /**< Boolean: did read() return 0 on this
  1015. * conn? */
  1016. /** Set to 1 when we're inside connection_flushed_some to keep us from
  1017. * calling connection_handle_write() recursively. */
  1018. unsigned int in_flushed_some:1;
  1019. /* For linked connections:
  1020. */
  1021. unsigned int linked:1; /**< True if there is, or has been, a linked_conn. */
  1022. /** True iff we'd like to be notified about read events from the
  1023. * linked conn. */
  1024. unsigned int reading_from_linked_conn:1;
  1025. /** True iff we're willing to write to the linked conn. */
  1026. unsigned int writing_to_linked_conn:1;
  1027. /** True iff we're currently able to read on the linked conn, and our
  1028. * read_event should be made active with libevent. */
  1029. unsigned int active_on_link:1;
  1030. /** True iff we've called connection_close_immediate() on this linked
  1031. * connection. */
  1032. unsigned int linked_conn_is_closed:1;
  1033. /** CONNECT/SOCKS proxy client handshake state (for outgoing connections). */
  1034. unsigned int proxy_state:4;
  1035. /** Our socket; set to TOR_INVALID_SOCKET if this connection is closed,
  1036. * or has no socket. */
  1037. tor_socket_t s;
  1038. int conn_array_index; /**< Index into the global connection array. */
  1039. struct event *read_event; /**< Libevent event structure. */
  1040. struct event *write_event; /**< Libevent event structure. */
  1041. buf_t *inbuf; /**< Buffer holding data read over this connection. */
  1042. buf_t *outbuf; /**< Buffer holding data to write over this connection. */
  1043. size_t outbuf_flushlen; /**< How much data should we try to flush from the
  1044. * outbuf? */
  1045. time_t timestamp_lastread; /**< When was the last time libevent said we could
  1046. * read? */
  1047. time_t timestamp_lastwritten; /**< When was the last time libevent said we
  1048. * could write? */
  1049. #ifdef USE_BUFFEREVENTS
  1050. struct bufferevent *bufev; /**< A Libevent buffered IO structure. */
  1051. #endif
  1052. time_t timestamp_created; /**< When was this connection_t created? */
  1053. /* XXXX_IP6 make this IPv6-capable */
  1054. int socket_family; /**< Address family of this connection's socket. Usually
  1055. * AF_INET, but it can also be AF_UNIX, or in the future
  1056. * AF_INET6 */
  1057. tor_addr_t addr; /**< IP of the other side of the connection; used to
  1058. * identify routers, along with port. */
  1059. uint16_t port; /**< If non-zero, port on the other end
  1060. * of the connection. */
  1061. uint16_t marked_for_close; /**< Should we close this conn on the next
  1062. * iteration of the main loop? (If true, holds
  1063. * the line number where this connection was
  1064. * marked.) */
  1065. const char *marked_for_close_file; /**< For debugging: in which file were
  1066. * we marked for close? */
  1067. char *address; /**< FQDN (or IP) of the guy on the other end.
  1068. * strdup into this, because free_connection() frees it. */
  1069. /** Another connection that's connected to this one in lieu of a socket. */
  1070. struct connection_t *linked_conn;
  1071. /** Unique identifier for this connection on this Tor instance. */
  1072. uint64_t global_identifier;
  1073. } connection_t;
  1074. /** Subtype of connection_t; used for a listener socket. */
  1075. typedef struct listener_connection_t {
  1076. connection_t base_;
  1077. /** If the connection is a CONN_TYPE_AP_DNS_LISTENER, this field points
  1078. * to the evdns_server_port it uses to listen to and answer connections. */
  1079. struct evdns_server_port *dns_server_port;
  1080. /** @name Isolation parameters
  1081. *
  1082. * For an AP listener, these fields describe how to isolate streams that
  1083. * arrive on the listener.
  1084. *
  1085. * @{
  1086. */
  1087. /** The session group for this listener. */
  1088. int session_group;
  1089. /** One or more ISO_ flags to describe how to isolate streams. */
  1090. uint8_t isolation_flags;
  1091. /**@}*/
  1092. /** For a SOCKS listener, these fields describe whether we should
  1093. * allow IPv4 and IPv6 addresses from our exit nodes, respectively.
  1094. *
  1095. * @{
  1096. */
  1097. unsigned int socks_ipv4_traffic : 1;
  1098. unsigned int socks_ipv6_traffic : 1;
  1099. /** @} */
  1100. /** For a socks listener: should we tell the exit that we prefer IPv6
  1101. * addresses? */
  1102. unsigned int socks_prefer_ipv6 : 1;
  1103. } listener_connection_t;
  1104. /** Minimum length of the random part of an AUTH_CHALLENGE cell. */
  1105. #define OR_AUTH_CHALLENGE_LEN 32
  1106. /**
  1107. * @name Certificate types for CERTS cells.
  1108. *
  1109. * These values are defined by the protocol, and affect how an X509
  1110. * certificate in a CERTS cell is interpreted and used.
  1111. *
  1112. * @{ */
  1113. /** A certificate that authenticates a TLS link key. The subject key
  1114. * must match the key used in the TLS handshake; it must be signed by
  1115. * the identity key. */
  1116. #define OR_CERT_TYPE_TLS_LINK 1
  1117. /** A self-signed identity certificate. The subject key must be a
  1118. * 1024-bit RSA key. */
  1119. #define OR_CERT_TYPE_ID_1024 2
  1120. /** A certificate that authenticates a key used in an AUTHENTICATE cell
  1121. * in the v3 handshake. The subject key must be a 1024-bit RSA key; it
  1122. * must be signed by the identity key */
  1123. #define OR_CERT_TYPE_AUTH_1024 3
  1124. /**@}*/
  1125. /** The one currently supported type of AUTHENTICATE cell. It contains
  1126. * a bunch of structures signed with an RSA1024 key. The signed
  1127. * structures include a HMAC using negotiated TLS secrets, and a digest
  1128. * of all cells sent or received before the AUTHENTICATE cell (including
  1129. * the random server-generated AUTH_CHALLENGE cell).
  1130. */
  1131. #define AUTHTYPE_RSA_SHA256_TLSSECRET 1
  1132. /** The length of the part of the AUTHENTICATE cell body that the client and
  1133. * server can generate independently (when using RSA_SHA256_TLSSECRET). It
  1134. * contains everything except the client's timestamp, the client's randomly
  1135. * generated nonce, and the signature. */
  1136. #define V3_AUTH_FIXED_PART_LEN (8+(32*6))
  1137. /** The length of the part of the AUTHENTICATE cell body that the client
  1138. * signs. */
  1139. #define V3_AUTH_BODY_LEN (V3_AUTH_FIXED_PART_LEN + 8 + 16)
  1140. /** Stores flags and information related to the portion of a v2/v3 Tor OR
  1141. * connection handshake that happens after the TLS handshake is finished.
  1142. */
  1143. typedef struct or_handshake_state_t {
  1144. /** When was the VERSIONS cell sent on this connection? Used to get
  1145. * an estimate of the skew in the returning NETINFO reply. */
  1146. time_t sent_versions_at;
  1147. /** True iff we originated this connection */
  1148. unsigned int started_here : 1;
  1149. /** True iff we have received and processed a VERSIONS cell. */
  1150. unsigned int received_versions : 1;
  1151. /** True iff we have received and processed an AUTH_CHALLENGE cell */
  1152. unsigned int received_auth_challenge : 1;
  1153. /** True iff we have received and processed a CERTS cell. */
  1154. unsigned int received_certs_cell : 1;
  1155. /** True iff we have received and processed an AUTHENTICATE cell */
  1156. unsigned int received_authenticate : 1;
  1157. /* True iff we've received valid authentication to some identity. */
  1158. unsigned int authenticated : 1;
  1159. /** True iff we should feed outgoing cells into digest_sent and
  1160. * digest_received respectively.
  1161. *
  1162. * From the server's side of the v3 handshake, we want to capture everything
  1163. * from the VERSIONS cell through and including the AUTH_CHALLENGE cell.
  1164. * From the client's, we want to capture everything from the VERSIONS cell
  1165. * through but *not* including the AUTHENTICATE cell.
  1166. *
  1167. * @{ */
  1168. unsigned int digest_sent_data : 1;
  1169. unsigned int digest_received_data : 1;
  1170. /**@}*/
  1171. /** Identity digest that we have received and authenticated for our peer
  1172. * on this connection. */
  1173. uint8_t authenticated_peer_id[DIGEST_LEN];
  1174. /** Digests of the cells that we have sent or received as part of a V3
  1175. * handshake. Used for making and checking AUTHENTICATE cells.
  1176. *
  1177. * @{
  1178. */
  1179. crypto_digest_t *digest_sent;
  1180. crypto_digest_t *digest_received;
  1181. /** @} */
  1182. /** Certificates that a connection initiator sent us in a CERTS cell; we're
  1183. * holding on to them until we get an AUTHENTICATE cell.
  1184. *
  1185. * @{
  1186. */
  1187. /** The cert for the key that's supposed to sign the AUTHENTICATE cell */
  1188. tor_cert_t *auth_cert;
  1189. /** A self-signed identity certificate */
  1190. tor_cert_t *id_cert;
  1191. /**@}*/
  1192. } or_handshake_state_t;
  1193. /** Subtype of connection_t for an "OR connection" -- that is, one that speaks
  1194. * cells over TLS. */
  1195. typedef struct or_connection_t {
  1196. connection_t base_;
  1197. /** Hash of the public RSA key for the other side's identity key, or zeroes
  1198. * if the other side hasn't shown us a valid identity key. */
  1199. char identity_digest[DIGEST_LEN];
  1200. char *nickname; /**< Nickname of OR on other side (if any). */
  1201. tor_tls_t *tls; /**< TLS connection state. */
  1202. int tls_error; /**< Last tor_tls error code. */
  1203. /** When we last used this conn for any client traffic. If not
  1204. * recent, we can rate limit it further. */
  1205. /* Channel using this connection */
  1206. channel_tls_t *chan;
  1207. tor_addr_t real_addr; /**< The actual address that this connection came from
  1208. * or went to. The <b>addr</b> field is prone to
  1209. * getting overridden by the address from the router
  1210. * descriptor matching <b>identity_digest</b>. */
  1211. /** Should this connection be used for extending circuits to the server
  1212. * matching the <b>identity_digest</b> field? Set to true if we're pretty
  1213. * sure we aren't getting MITMed, either because we're connected to an
  1214. * address listed in a server descriptor, or because an authenticated
  1215. * NETINFO cell listed the address we're connected to as recognized. */
  1216. unsigned int is_canonical:1;
  1217. /** True iff we have decided that the other end of this connection
  1218. * is a client. Connections with this flag set should never be used
  1219. * to satisfy an EXTEND request. */
  1220. unsigned int is_connection_with_client:1;
  1221. /** True iff this is an outgoing connection. */
  1222. unsigned int is_outgoing:1;
  1223. unsigned int proxy_type:2; /**< One of PROXY_NONE...PROXY_SOCKS5 */
  1224. uint8_t link_proto; /**< What protocol version are we using? 0 for
  1225. * "none negotiated yet." */
  1226. or_handshake_state_t *handshake_state; /**< If we are setting this connection
  1227. * up, state information to do so. */
  1228. time_t timestamp_lastempty; /**< When was the outbuf last completely empty?*/
  1229. time_t timestamp_last_added_nonpadding; /** When did we last add a
  1230. * non-padding cell to the outbuf? */
  1231. /* bandwidth* and *_bucket only used by ORs in OPEN state: */
  1232. int bandwidthrate; /**< Bytes/s added to the bucket. (OPEN ORs only.) */
  1233. int bandwidthburst; /**< Max bucket size for this conn. (OPEN ORs only.) */
  1234. #ifndef USE_BUFFEREVENTS
  1235. int read_bucket; /**< When this hits 0, stop receiving. Every second we
  1236. * add 'bandwidthrate' to this, capping it at
  1237. * bandwidthburst. (OPEN ORs only) */
  1238. int write_bucket; /**< When this hits 0, stop writing. Like read_bucket. */
  1239. #else
  1240. /** A rate-limiting configuration object to determine how this connection
  1241. * set its read- and write- limits. */
  1242. /* XXXX we could share this among all connections. */
  1243. struct ev_token_bucket_cfg *bucket_cfg;
  1244. #endif
  1245. struct or_connection_t *next_with_same_id; /**< Next connection with same
  1246. * identity digest as this one. */
  1247. } or_connection_t;
  1248. /** Subtype of connection_t for an "edge connection" -- that is, an entry (ap)
  1249. * connection, or an exit. */
  1250. typedef struct edge_connection_t {
  1251. connection_t base_;
  1252. struct edge_connection_t *next_stream; /**< Points to the next stream at this
  1253. * edge, if any */
  1254. int package_window; /**< How many more relay cells can I send into the
  1255. * circuit? */
  1256. int deliver_window; /**< How many more relay cells can end at me? */
  1257. struct circuit_t *on_circuit; /**< The circuit (if any) that this edge
  1258. * connection is using. */
  1259. /** A pointer to which node in the circ this conn exits at. Set for AP
  1260. * connections and for hidden service exit connections. */
  1261. struct crypt_path_t *cpath_layer;
  1262. /** What rendezvous service are we querying for (if an AP) or providing (if
  1263. * an exit)? */
  1264. rend_data_t *rend_data;
  1265. uint32_t address_ttl; /**< TTL for address-to-addr mapping on exit
  1266. * connection. Exit connections only. */
  1267. uint32_t begincell_flags; /** Flags sent or received in the BEGIN cell
  1268. * for this connection */
  1269. streamid_t stream_id; /**< The stream ID used for this edge connection on its
  1270. * circuit */
  1271. /** The reason why this connection is closing; passed to the controller. */
  1272. uint16_t end_reason;
  1273. /** Bytes read since last call to control_event_stream_bandwidth_used() */
  1274. uint32_t n_read;
  1275. /** Bytes written since last call to control_event_stream_bandwidth_used() */
  1276. uint32_t n_written;
  1277. /** True iff this connection is for a DNS request only. */
  1278. unsigned int is_dns_request:1;
  1279. /** True iff this connection is for a PTR DNS request. (exit only) */
  1280. unsigned int is_reverse_dns_lookup:1;
  1281. unsigned int edge_has_sent_end:1; /**< For debugging; only used on edge
  1282. * connections. Set once we've set the stream end,
  1283. * and check in connection_about_to_close_connection().
  1284. */
  1285. /** True iff we've blocked reading until the circuit has fewer queued
  1286. * cells. */
  1287. unsigned int edge_blocked_on_circ:1;
  1288. /** Unique ID for directory requests; this used to be in connection_t, but
  1289. * that's going away and being used on channels instead. We still tag
  1290. * edge connections with dirreq_id from circuits, so it's copied here. */
  1291. uint64_t dirreq_id;
  1292. } edge_connection_t;
  1293. /** Subtype of edge_connection_t for an "entry connection" -- that is, a SOCKS
  1294. * connection, a DNS request, a TransPort connection or a NATD connection */
  1295. typedef struct entry_connection_t {
  1296. edge_connection_t edge_;
  1297. /** Nickname of planned exit node -- used with .exit support. */
  1298. char *chosen_exit_name;
  1299. socks_request_t *socks_request; /**< SOCKS structure describing request (AP
  1300. * only.) */
  1301. /* === Isolation related, AP only. === */
  1302. /** AP only: based on which factors do we isolate this stream? */
  1303. uint8_t isolation_flags;
  1304. /** AP only: what session group is this stream in? */
  1305. int session_group;
  1306. /** AP only: The newnym epoch in which we created this connection. */
  1307. unsigned nym_epoch;
  1308. /** AP only: The original requested address before we rewrote it. */
  1309. char *original_dest_address;
  1310. /* Other fields to isolate on already exist. The ClientAddr is addr. The
  1311. ClientProtocol is a combination of type and socks_request->
  1312. socks_version. SocksAuth is socks_request->username/password.
  1313. DestAddr is in socks_request->address. */
  1314. /** Number of times we've reassigned this application connection to
  1315. * a new circuit. We keep track because the timeout is longer if we've
  1316. * already retried several times. */
  1317. uint8_t num_socks_retries;
  1318. /** For AP connections only: buffer for data that we have sent
  1319. * optimistically, which we might need to re-send if we have to
  1320. * retry this connection. */
  1321. generic_buffer_t *pending_optimistic_data;
  1322. /* For AP connections only: buffer for data that we previously sent
  1323. * optimistically which we are currently re-sending as we retry this
  1324. * connection. */
  1325. generic_buffer_t *sending_optimistic_data;
  1326. /** If this is a DNSPort connection, this field holds the pending DNS
  1327. * request that we're going to try to answer. */
  1328. struct evdns_server_request *dns_server_request;
  1329. #define NUM_CIRCUITS_LAUNCHED_THRESHOLD 10
  1330. /** Number of times we've launched a circuit to handle this stream. If
  1331. * it gets too high, that could indicate an inconsistency between our
  1332. * "launch a circuit to handle this stream" logic and our "attach our
  1333. * stream to one of the available circuits" logic. */
  1334. unsigned int num_circuits_launched:4;
  1335. /** True iff this stream must attach to a one-hop circuit (e.g. for
  1336. * begin_dir). */
  1337. unsigned int want_onehop:1;
  1338. /** True iff this stream should use a BEGIN_DIR relay command to establish
  1339. * itself rather than BEGIN (either via onehop or via a whole circuit). */
  1340. unsigned int use_begindir:1;
  1341. /** For AP connections only. If 1, and we fail to reach the chosen exit,
  1342. * stop requiring it. */
  1343. unsigned int chosen_exit_optional:1;
  1344. /** For AP connections only. If non-zero, this exit node was picked as
  1345. * a result of the TrackHostExit, and the value decrements every time
  1346. * we fail to complete a circuit to our chosen exit -- if it reaches
  1347. * zero, abandon the associated mapaddress. */
  1348. unsigned int chosen_exit_retries:3;
  1349. /** True iff this is an AP connection that came from a transparent or
  1350. * NATd connection */
  1351. unsigned int is_transparent_ap:1;
  1352. /** For AP connections only: Set if this connection's target exit node
  1353. * allows optimistic data (that is, data sent on this stream before
  1354. * the exit has sent a CONNECTED cell) and we have chosen to use it.
  1355. */
  1356. unsigned int may_use_optimistic_data : 1;
  1357. /** Should we permit IPv4 and IPv6 traffic to use this connection?
  1358. *
  1359. * @{ */
  1360. unsigned int ipv4_traffic_ok : 1;
  1361. unsigned int ipv6_traffic_ok : 1;
  1362. /** @} */
  1363. /** Should we say we prefer IPv6 traffic? */
  1364. unsigned int prefer_ipv6_traffic : 1;
  1365. } entry_connection_t;
  1366. /** Subtype of connection_t for an "directory connection" -- that is, an HTTP
  1367. * connection to retrieve or serve directory material. */
  1368. typedef struct dir_connection_t {
  1369. connection_t base_;
  1370. /** Which 'resource' did we ask the directory for? This is typically the part
  1371. * of the URL string that defines, relative to the directory conn purpose,
  1372. * what thing we want. For example, in router descriptor downloads by
  1373. * descriptor digest, it contains "d/", then one ore more +-separated
  1374. * fingerprints.
  1375. **/
  1376. char *requested_resource;
  1377. unsigned int dirconn_direct:1; /**< Is this dirconn direct, or via Tor? */
  1378. /* Used only for server sides of some dir connections, to implement
  1379. * "spooling" of directory material to the outbuf. Otherwise, we'd have
  1380. * to append everything to the outbuf in one enormous chunk. */
  1381. /** What exactly are we spooling right now? */
  1382. enum {
  1383. DIR_SPOOL_NONE=0, DIR_SPOOL_SERVER_BY_DIGEST, DIR_SPOOL_SERVER_BY_FP,
  1384. DIR_SPOOL_EXTRA_BY_DIGEST, DIR_SPOOL_EXTRA_BY_FP,
  1385. DIR_SPOOL_CACHED_DIR, DIR_SPOOL_NETWORKSTATUS,
  1386. DIR_SPOOL_MICRODESC, /* NOTE: if we add another entry, add another bit. */
  1387. } dir_spool_src : 3;
  1388. /** If we're fetching descriptors, what router purpose shall we assign
  1389. * to them? */
  1390. uint8_t router_purpose;
  1391. /** List of fingerprints for networkstatuses or descriptors to be spooled. */
  1392. smartlist_t *fingerprint_stack;
  1393. /** A cached_dir_t object that we're currently spooling out */
  1394. struct cached_dir_t *cached_dir;
  1395. /** The current offset into cached_dir. */
  1396. off_t cached_dir_offset;
  1397. /** The zlib object doing on-the-fly compression for spooled data. */
  1398. tor_zlib_state_t *zlib_state;
  1399. /** What rendezvous service are we querying for? */
  1400. rend_data_t *rend_data;
  1401. char identity_digest[DIGEST_LEN]; /**< Hash of the public RSA key for
  1402. * the directory server's signing key. */
  1403. /** Unique ID for directory requests; this used to be in connection_t, but
  1404. * that's going away and being used on channels instead. The dirserver still
  1405. * needs this for the incoming side, so it's moved here. */
  1406. uint64_t dirreq_id;
  1407. } dir_connection_t;
  1408. /** Subtype of connection_t for an connection to a controller. */
  1409. typedef struct control_connection_t {
  1410. connection_t base_;
  1411. uint32_t event_mask; /**< Bitfield: which events does this controller
  1412. * care about? */
  1413. /** True if we have sent a protocolinfo reply on this connection. */
  1414. unsigned int have_sent_protocolinfo:1;
  1415. /** True if we have received a takeownership command on this
  1416. * connection. */
  1417. unsigned int is_owning_control_connection:1;
  1418. /** If we have sent an AUTHCHALLENGE reply on this connection and
  1419. * have not received a successful AUTHENTICATE command, points to
  1420. * the value which the client must send to authenticate itself;
  1421. * otherwise, NULL. */
  1422. char *safecookie_client_hash;
  1423. /** Amount of space allocated in incoming_cmd. */
  1424. uint32_t incoming_cmd_len;
  1425. /** Number of bytes currently stored in incoming_cmd. */
  1426. uint32_t incoming_cmd_cur_len;
  1427. /** A control command that we're reading from the inbuf, but which has not
  1428. * yet arrived completely. */
  1429. char *incoming_cmd;
  1430. } control_connection_t;
  1431. /** Cast a connection_t subtype pointer to a connection_t **/
  1432. #define TO_CONN(c) (&(((c)->base_)))
  1433. /** Helper macro: Given a pointer to to.base_, of type from*, return &to. */
  1434. #define DOWNCAST(to, ptr) ((to*)SUBTYPE_P(ptr, to, base_))
  1435. /** Cast a entry_connection_t subtype pointer to a edge_connection_t **/
  1436. #define ENTRY_TO_EDGE_CONN(c) (&(((c))->edge_))
  1437. /** Cast a entry_connection_t subtype pointer to a connection_t **/
  1438. #define ENTRY_TO_CONN(c) (TO_CONN(ENTRY_TO_EDGE_CONN(c)))
  1439. /** Convert a connection_t* to an or_connection_t*; assert if the cast is
  1440. * invalid. */
  1441. static or_connection_t *TO_OR_CONN(connection_t *);
  1442. /** Convert a connection_t* to a dir_connection_t*; assert if the cast is
  1443. * invalid. */
  1444. static dir_connection_t *TO_DIR_CONN(connection_t *);
  1445. /** Convert a connection_t* to an edge_connection_t*; assert if the cast is
  1446. * invalid. */
  1447. static edge_connection_t *TO_EDGE_CONN(connection_t *);
  1448. /** Convert a connection_t* to an entry_connection_t*; assert if the cast is
  1449. * invalid. */
  1450. static entry_connection_t *TO_ENTRY_CONN(connection_t *);
  1451. /** Convert a edge_connection_t* to an entry_connection_t*; assert if the cast
  1452. * is invalid. */
  1453. static entry_connection_t *EDGE_TO_ENTRY_CONN(edge_connection_t *);
  1454. /** Convert a connection_t* to an control_connection_t*; assert if the cast is
  1455. * invalid. */
  1456. static control_connection_t *TO_CONTROL_CONN(connection_t *);
  1457. /** Convert a connection_t* to an listener_connection_t*; assert if the cast is
  1458. * invalid. */
  1459. static listener_connection_t *TO_LISTENER_CONN(connection_t *);
  1460. static INLINE or_connection_t *TO_OR_CONN(connection_t *c)
  1461. {
  1462. tor_assert(c->magic == OR_CONNECTION_MAGIC);
  1463. return DOWNCAST(or_connection_t, c);
  1464. }
  1465. static INLINE dir_connection_t *TO_DIR_CONN(connection_t *c)
  1466. {
  1467. tor_assert(c->magic == DIR_CONNECTION_MAGIC);
  1468. return DOWNCAST(dir_connection_t, c);
  1469. }
  1470. static INLINE edge_connection_t *TO_EDGE_CONN(connection_t *c)
  1471. {
  1472. tor_assert(c->magic == EDGE_CONNECTION_MAGIC ||
  1473. c->magic == ENTRY_CONNECTION_MAGIC);
  1474. return DOWNCAST(edge_connection_t, c);
  1475. }
  1476. static INLINE entry_connection_t *TO_ENTRY_CONN(connection_t *c)
  1477. {
  1478. tor_assert(c->magic == ENTRY_CONNECTION_MAGIC);
  1479. return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_.base_);
  1480. }
  1481. static INLINE entry_connection_t *EDGE_TO_ENTRY_CONN(edge_connection_t *c)
  1482. {
  1483. tor_assert(c->base_.magic == ENTRY_CONNECTION_MAGIC);
  1484. return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_);
  1485. }
  1486. static INLINE control_connection_t *TO_CONTROL_CONN(connection_t *c)
  1487. {
  1488. tor_assert(c->magic == CONTROL_CONNECTION_MAGIC);
  1489. return DOWNCAST(control_connection_t, c);
  1490. }
  1491. static INLINE listener_connection_t *TO_LISTENER_CONN(connection_t *c)
  1492. {
  1493. tor_assert(c->magic == LISTENER_CONNECTION_MAGIC);
  1494. return DOWNCAST(listener_connection_t, c);
  1495. }
  1496. /* Conditional macros to help write code that works whether bufferevents are
  1497. disabled or not.
  1498. We can't just write:
  1499. if (conn->bufev) {
  1500. do bufferevent stuff;
  1501. } else {
  1502. do other stuff;
  1503. }
  1504. because the bufferevent stuff won't even compile unless we have a fairly
  1505. new version of Libevent. Instead, we say:
  1506. IF_HAS_BUFFEREVENT(conn, { do_bufferevent_stuff } );
  1507. or:
  1508. IF_HAS_BUFFEREVENT(conn, {
  1509. do bufferevent stuff;
  1510. }) ELSE_IF_NO_BUFFEREVENT {
  1511. do non-bufferevent stuff;
  1512. }
  1513. If we're compiling with bufferevent support, then the macros expand more or
  1514. less to:
  1515. if (conn->bufev) {
  1516. do_bufferevent_stuff;
  1517. } else {
  1518. do non-bufferevent stuff;
  1519. }
  1520. and if we aren't using bufferevents, they expand more or less to:
  1521. { do non-bufferevent stuff; }
  1522. */
  1523. #ifdef USE_BUFFEREVENTS
  1524. #define HAS_BUFFEREVENT(c) (((c)->bufev) != NULL)
  1525. #define IF_HAS_BUFFEREVENT(c, stmt) \
  1526. if ((c)->bufev) do { \
  1527. stmt ; \
  1528. } while (0)
  1529. #define ELSE_IF_NO_BUFFEREVENT ; else
  1530. #define IF_HAS_NO_BUFFEREVENT(c) \
  1531. if (NULL == (c)->bufev)
  1532. #else
  1533. #define HAS_BUFFEREVENT(c) (0)
  1534. #define IF_HAS_BUFFEREVENT(c, stmt) (void)0
  1535. #define ELSE_IF_NO_BUFFEREVENT ;
  1536. #define IF_HAS_NO_BUFFEREVENT(c) \
  1537. if (1)
  1538. #endif
  1539. /** What action type does an address policy indicate: accept or reject? */
  1540. typedef enum {
  1541. ADDR_POLICY_ACCEPT=1,
  1542. ADDR_POLICY_REJECT=2,
  1543. } addr_policy_action_t;
  1544. /** A reference-counted address policy rule. */
  1545. typedef struct addr_policy_t {
  1546. int refcnt; /**< Reference count */
  1547. addr_policy_action_t policy_type:2;/**< What to do when the policy matches.*/
  1548. unsigned int is_private:1; /**< True iff this is the pseudo-address,
  1549. * "private". */
  1550. unsigned int is_canonical:1; /**< True iff this policy is the canonical
  1551. * copy (stored in a hash table to avoid
  1552. * duplication of common policies) */
  1553. maskbits_t maskbits; /**< Accept/reject all addresses <b>a</b> such that the
  1554. * first <b>maskbits</b> bits of <b>a</b> match
  1555. * <b>addr</b>. */
  1556. /** Base address to accept or reject.
  1557. *
  1558. * Note that wildcards are treated
  1559. * differntly depending on address family. An AF_UNSPEC address means
  1560. * "All addresses, IPv4 or IPv6." An AF_INET address with maskbits==0 means
  1561. * "All IPv4 addresses" and an AF_INET6 address with maskbits == 0 means
  1562. * "All IPv6 addresses".
  1563. **/
  1564. tor_addr_t addr;
  1565. uint16_t prt_min; /**< Lowest port number to accept/reject. */
  1566. uint16_t prt_max; /**< Highest port number to accept/reject. */
  1567. } addr_policy_t;
  1568. /** A cached_dir_t represents a cacheable directory object, along with its
  1569. * compressed form. */
  1570. typedef struct cached_dir_t {
  1571. char *dir; /**< Contents of this object, NUL-terminated. */
  1572. char *dir_z; /**< Compressed contents of this object. */
  1573. size_t dir_len; /**< Length of <b>dir</b> (not counting its NUL). */
  1574. size_t dir_z_len; /**< Length of <b>dir_z</b>. */
  1575. time_t published; /**< When was this object published. */
  1576. digests_t digests; /**< Digests of this object (networkstatus only) */
  1577. int refcnt; /**< Reference count for this cached_dir_t. */
  1578. } cached_dir_t;
  1579. /** Enum used to remember where a signed_descriptor_t is stored and how to
  1580. * manage the memory for signed_descriptor_body. */
  1581. typedef enum {
  1582. /** The descriptor isn't stored on disk at all: the copy in memory is
  1583. * canonical; the saved_offset field is meaningless. */
  1584. SAVED_NOWHERE=0,
  1585. /** The descriptor is stored in the cached_routers file: the
  1586. * signed_descriptor_body is meaningless; the signed_descriptor_len and
  1587. * saved_offset are used to index into the mmaped cache file. */
  1588. SAVED_IN_CACHE,
  1589. /** The descriptor is stored in the cached_routers.new file: the
  1590. * signed_descriptor_body and saved_offset fields are both set. */
  1591. /* FFFF (We could also mmap the file and grow the mmap as needed, or
  1592. * lazy-load the descriptor text by using seek and read. We don't, for
  1593. * now.)
  1594. */
  1595. SAVED_IN_JOURNAL
  1596. } saved_location_t;
  1597. /** Enumeration: what kind of download schedule are we using for a given
  1598. * object? */
  1599. typedef enum {
  1600. DL_SCHED_GENERIC = 0,
  1601. DL_SCHED_CONSENSUS = 1,
  1602. DL_SCHED_BRIDGE = 2,
  1603. } download_schedule_t;
  1604. /** Information about our plans for retrying downloads for a downloadable
  1605. * object. */
  1606. typedef struct download_status_t {
  1607. time_t next_attempt_at; /**< When should we try downloading this descriptor
  1608. * again? */
  1609. uint8_t n_download_failures; /**< Number of failures trying to download the
  1610. * most recent descriptor. */
  1611. download_schedule_t schedule : 8;
  1612. } download_status_t;
  1613. /** If n_download_failures is this high, the download can never happen. */
  1614. #define IMPOSSIBLE_TO_DOWNLOAD 255
  1615. /** The max size we expect router descriptor annotations we create to
  1616. * be. We'll accept larger ones if we see them on disk, but we won't
  1617. * create any that are larger than this. */
  1618. #define ROUTER_ANNOTATION_BUF_LEN 256
  1619. /** Information need to cache an onion router's descriptor. */
  1620. typedef struct signed_descriptor_t {
  1621. /** Pointer to the raw server descriptor, preceded by annotations. Not
  1622. * necessarily NUL-terminated. If saved_location is SAVED_IN_CACHE, this
  1623. * pointer is null. */
  1624. char *signed_descriptor_body;
  1625. /** Length of the annotations preceding the server descriptor. */
  1626. size_t annotations_len;
  1627. /** Length of the server descriptor. */
  1628. size_t signed_descriptor_len;
  1629. /** Digest of the server descriptor, computed as specified in
  1630. * dir-spec.txt. */
  1631. char signed_descriptor_digest[DIGEST_LEN];
  1632. /** Identity digest of the router. */
  1633. char identity_digest[DIGEST_LEN];
  1634. /** Declared publication time of the descriptor. */
  1635. time_t published_on;
  1636. /** For routerdescs only: digest of the corresponding extrainfo. */
  1637. char extra_info_digest[DIGEST_LEN];
  1638. /** For routerdescs only: Status of downloading the corresponding
  1639. * extrainfo. */
  1640. download_status_t ei_dl_status;
  1641. /** Where is the descriptor saved? */
  1642. saved_location_t saved_location;
  1643. /** If saved_location is SAVED_IN_CACHE or SAVED_IN_JOURNAL, the offset of
  1644. * this descriptor in the corresponding file. */
  1645. off_t saved_offset;
  1646. /** What position is this descriptor within routerlist->routers or
  1647. * routerlist->old_routers? -1 for none. */
  1648. int routerlist_index;
  1649. /** The valid-until time of the most recent consensus that listed this
  1650. * descriptor, or a bit after the publication time of the most recent v2
  1651. * networkstatus that listed it. 0 for "never listed in a consensus or
  1652. * status, so far as we know." */
  1653. time_t last_listed_as_valid_until;
  1654. /* If true, we do not ever try to save this object in the cache. */
  1655. unsigned int do_not_cache : 1;
  1656. /* If true, this item is meant to represent an extrainfo. */
  1657. unsigned int is_extrainfo : 1;
  1658. /* If true, we got an extrainfo for this item, and the digest was right,
  1659. * but it was incompatible. */
  1660. unsigned int extrainfo_is_bogus : 1;
  1661. /* If true, we are willing to transmit this item unencrypted. */
  1662. unsigned int send_unencrypted : 1;
  1663. } signed_descriptor_t;
  1664. /** A signed integer representing a country code. */
  1665. typedef int16_t country_t;
  1666. /** Information about another onion router in the network. */
  1667. typedef struct {
  1668. signed_descriptor_t cache_info;
  1669. char *address; /**< Location of OR: either a hostname or an IP address. */
  1670. char *nickname; /**< Human-readable OR name. */
  1671. uint32_t addr; /**< IPv4 address of OR, in host order. */
  1672. uint16_t or_port; /**< Port for TLS connections. */
  1673. uint16_t dir_port; /**< Port for HTTP directory connections. */
  1674. /** A router's IPv6 address, if it has one. */
  1675. /* XXXXX187 Actually these should probably be part of a list of addresses,
  1676. * not just a special case. Use abstractions to access these; don't do it
  1677. * directly. */
  1678. tor_addr_t ipv6_addr;
  1679. uint16_t ipv6_orport;
  1680. crypto_pk_t *onion_pkey; /**< Public RSA key for onions. */
  1681. crypto_pk_t *identity_pkey; /**< Public RSA key for signing. */
  1682. /** Public curve25519 key for onions */
  1683. curve25519_public_key_t *onion_curve25519_pkey;
  1684. char *platform; /**< What software/operating system is this OR using? */
  1685. /* link info */
  1686. uint32_t bandwidthrate; /**< How many bytes does this OR add to its token
  1687. * bucket per second? */
  1688. uint32_t bandwidthburst; /**< How large is this OR's token bucket? */
  1689. /** How many bytes/s is this router known to handle? */
  1690. uint32_t bandwidthcapacity;
  1691. smartlist_t *exit_policy; /**< What streams will this OR permit
  1692. * to exit on IPv4? NULL for 'reject *:*'. */
  1693. /** What streams will this OR permit to exit on IPv6?
  1694. * NULL for 'reject *:*' */
  1695. struct short_policy_t *ipv6_exit_policy;
  1696. long uptime; /**< How many seconds the router claims to have been up */
  1697. smartlist_t *declared_family; /**< Nicknames of router which this router
  1698. * claims are its family. */
  1699. char *contact_info; /**< Declared contact info for this router. */
  1700. unsigned int is_hibernating:1; /**< Whether the router claims to be
  1701. * hibernating */
  1702. unsigned int caches_extra_info:1; /**< Whether the router says it caches and
  1703. * serves extrainfo documents. */
  1704. unsigned int allow_single_hop_exits:1; /**< Whether the router says
  1705. * it allows single hop exits. */
  1706. unsigned int wants_to_be_hs_dir:1; /**< True iff this router claims to be
  1707. * a hidden service directory. */
  1708. unsigned int policy_is_reject_star:1; /**< True iff the exit policy for this
  1709. * router rejects everything. */
  1710. /** True if, after we have added this router, we should re-launch
  1711. * tests for it. */
  1712. unsigned int needs_retest_if_added:1;
  1713. /** Tor can use this router for general positions in circuits; we got it
  1714. * from a directory server as usual, or we're an authority and a server
  1715. * uploaded it. */
  1716. #define ROUTER_PURPOSE_GENERAL 0
  1717. /** Tor should avoid using this router for circuit-building: we got it
  1718. * from a crontroller. If the controller wants to use it, it'll have to
  1719. * ask for it by identity. */
  1720. #define ROUTER_PURPOSE_CONTROLLER 1
  1721. /** Tor should use this router only for bridge positions in circuits: we got
  1722. * it via a directory request from the bridge itself, or a bridge
  1723. * authority. x*/
  1724. #define ROUTER_PURPOSE_BRIDGE 2
  1725. /** Tor should not use this router; it was marked in cached-descriptors with
  1726. * a purpose we didn't recognize. */
  1727. #define ROUTER_PURPOSE_UNKNOWN 255
  1728. /* In what way did we find out about this router? One of ROUTER_PURPOSE_*.
  1729. * Routers of different purposes are kept segregated and used for different
  1730. * things; see notes on ROUTER_PURPOSE_* macros above.
  1731. */
  1732. uint8_t purpose;
  1733. } routerinfo_t;
  1734. /** Information needed to keep and cache a signed extra-info document. */
  1735. typedef struct extrainfo_t {
  1736. signed_descriptor_t cache_info;
  1737. /** The router's nickname. */
  1738. char nickname[MAX_NICKNAME_LEN+1];
  1739. /** True iff we found the right key for this extra-info, verified the
  1740. * signature, and found it to be bad. */
  1741. unsigned int bad_sig : 1;
  1742. /** If present, we didn't have the right key to verify this extra-info,
  1743. * so this is a copy of the signature in the document. */
  1744. char *pending_sig;
  1745. /** Length of pending_sig. */
  1746. size_t pending_sig_len;
  1747. } extrainfo_t;
  1748. /** Contents of a single router entry in a network status object.
  1749. */
  1750. typedef struct routerstatus_t {
  1751. time_t published_on; /**< When was this router published? */
  1752. char nickname[MAX_NICKNAME_LEN+1]; /**< The nickname this router says it
  1753. * has. */
  1754. char identity_digest[DIGEST_LEN]; /**< Digest of the router's identity
  1755. * key. */
  1756. /** Digest of the router's most recent descriptor or microdescriptor.
  1757. * If it's a descriptor, we only use the first DIGEST_LEN bytes. */
  1758. char descriptor_digest[DIGEST256_LEN];
  1759. uint32_t addr; /**< IPv4 address for this router. */
  1760. uint16_t or_port; /**< OR port for this router. */
  1761. uint16_t dir_port; /**< Directory port for this router. */
  1762. tor_addr_t ipv6_addr; /**< IPv6 address for this router. */
  1763. uint16_t ipv6_orport; /**<IPV6 OR port for this router. */
  1764. unsigned int is_authority:1; /**< True iff this router is an authority. */
  1765. unsigned int is_exit:1; /**< True iff this router is a good exit. */
  1766. unsigned int is_stable:1; /**< True iff this router stays up a long time. */
  1767. unsigned int is_fast:1; /**< True iff this router has good bandwidth. */
  1768. /** True iff this router is called 'running' in the consensus. We give it
  1769. * this funny name so that we don't accidentally use this bit as a view of
  1770. * whether we think the router is *currently* running. If that's what you
  1771. * want to know, look at is_running in node_t. */
  1772. unsigned int is_flagged_running:1;
  1773. unsigned int is_named:1; /**< True iff "nickname" belongs to this router. */
  1774. unsigned int is_unnamed:1; /**< True iff "nickname" belongs to another
  1775. * router. */
  1776. unsigned int is_valid:1; /**< True iff this router isn't invalid. */
  1777. unsigned int is_v2_dir:1; /**< True iff this router can serve directory
  1778. * information with v2 of the directory
  1779. * protocol. (All directory caches cache v1
  1780. * directories.) */
  1781. unsigned int is_possible_guard:1; /**< True iff this router would be a good
  1782. * choice as an entry guard. */
  1783. unsigned int is_bad_exit:1; /**< True iff this node is a bad choice for
  1784. * an exit node. */
  1785. unsigned int is_bad_directory:1; /**< Do we think this directory is junky,
  1786. * underpowered, or otherwise useless? */
  1787. unsigned int is_hs_dir:1; /**< True iff this router is a v2-or-later hidden
  1788. * service directory. */
  1789. /** True iff we know version info for this router. (i.e., a "v" entry was
  1790. * included.) We'll replace all these with a big tor_version_t or a char[]
  1791. * if the number of traits we care about ever becomes incredibly big. */
  1792. unsigned int version_known:1;
  1793. /** True iff this router is a version that, if it caches directory info,
  1794. * we can get microdescriptors from. */
  1795. unsigned int version_supports_microdesc_cache:1;
  1796. /** True iff this router is a version that allows DATA cells to arrive on
  1797. * a stream before it has sent a CONNECTED cell. */
  1798. unsigned int version_supports_optimistic_data:1;
  1799. unsigned int has_bandwidth:1; /**< The vote/consensus had bw info */
  1800. unsigned int has_exitsummary:1; /**< The vote/consensus had exit summaries */
  1801. unsigned int has_measured_bw:1; /**< The vote/consensus had a measured bw */
  1802. uint32_t measured_bw; /**< Measured bandwidth (capacity) of the router */
  1803. uint32_t bandwidth; /**< Bandwidth (capacity) of the router as reported in
  1804. * the vote/consensus, in kilobytes/sec. */
  1805. char *exitsummary; /**< exit policy summary -
  1806. * XXX weasel: this probably should not stay a string. */
  1807. /* ---- The fields below aren't derived from the networkstatus; they
  1808. * hold local information only. */
  1809. /** True if we, as a directory mirror, want to download the corresponding
  1810. * routerinfo from the authority who gave us this routerstatus. (That is,
  1811. * if we don't have the routerinfo, and if we haven't already tried to get it
  1812. * from this authority.) Applies in v2 networkstatus document only.
  1813. */
  1814. unsigned int need_to_mirror:1;
  1815. time_t last_dir_503_at; /**< When did this router last tell us that it
  1816. * was too busy to serve directory info? */
  1817. download_status_t dl_status;
  1818. } routerstatus_t;
  1819. /** A single entry in a parsed policy summary, describing a range of ports. */
  1820. typedef struct short_policy_entry_t {
  1821. uint16_t min_port, max_port;
  1822. } short_policy_entry_t;
  1823. /** A short_poliy_t is the parsed version of a policy summary. */
  1824. typedef struct short_policy_t {
  1825. /** True if the members of 'entries' are port ranges to accept; false if
  1826. * they are port ranges to reject */
  1827. unsigned int is_accept : 1;
  1828. /** The actual number of values in 'entries'. */
  1829. unsigned int n_entries : 31;
  1830. /** An array of 0 or more short_policy_entry_t values, each describing a
  1831. * range of ports that this policy accepts or rejects (depending on the
  1832. * value of is_accept).
  1833. */
  1834. short_policy_entry_t entries[FLEXIBLE_ARRAY_MEMBER];
  1835. } short_policy_t;
  1836. /** A microdescriptor is the smallest amount of information needed to build a
  1837. * circuit through a router. They are generated by the directory authorities,
  1838. * using information from the uploaded routerinfo documents. They are not
  1839. * self-signed, but are rather authenticated by having their hash in a signed
  1840. * networkstatus document. */
  1841. typedef struct microdesc_t {
  1842. /** Hashtable node, used to look up the microdesc by its digest. */
  1843. HT_ENTRY(microdesc_t) node;
  1844. /* Cache information */
  1845. /** When was this microdescriptor last listed in a consensus document?
  1846. * Once a microdesc has been unlisted long enough, we can drop it.
  1847. */
  1848. time_t last_listed;
  1849. /** Where is this microdescriptor currently stored? */
  1850. saved_location_t saved_location : 3;
  1851. /** If true, do not attempt to cache this microdescriptor on disk. */
  1852. unsigned int no_save : 1;
  1853. /** If true, this microdesc has an entry in the microdesc_map */
  1854. unsigned int held_in_map : 1;
  1855. /** Reference count: how many node_ts have a reference to this microdesc? */
  1856. unsigned int held_by_nodes;
  1857. /** If saved_location == SAVED_IN_CACHE, this field holds the offset of the
  1858. * microdescriptor in the cache. */
  1859. off_t off;
  1860. /* The string containing the microdesc. */
  1861. /** A pointer to the encoded body of the microdescriptor. If the
  1862. * saved_location is SAVED_IN_CACHE, then the body is a pointer into an
  1863. * mmap'd region. Otherwise, it is a malloc'd string. The string might not
  1864. * be NUL-terminated; take the length from <b>bodylen</b>. */
  1865. char *body;
  1866. /** The length of the microdescriptor in <b>body</b>. */
  1867. size_t bodylen;
  1868. /** A SHA256-digest of the microdescriptor. */
  1869. char digest[DIGEST256_LEN];
  1870. /* Fields in the microdescriptor. */
  1871. /** As routerinfo_t.onion_pkey */
  1872. crypto_pk_t *onion_pkey;
  1873. /** As routerinfo_t.onion_curve25519_pkey */
  1874. curve25519_public_key_t *onion_curve25519_pkey;
  1875. /** As routerinfo_t.ipv6_add */
  1876. tor_addr_t ipv6_addr;
  1877. /** As routerinfo_t.ipv6_orport */
  1878. uint16_t ipv6_orport;
  1879. /** As routerinfo_t.family */
  1880. smartlist_t *family;
  1881. /** IPv4 exit policy summary */
  1882. short_policy_t *exit_policy;
  1883. /** IPv6 exit policy summary */
  1884. short_policy_t *ipv6_exit_policy;
  1885. } microdesc_t;
  1886. /** A node_t represents a Tor router.
  1887. *
  1888. * Specifically, a node_t is a Tor router as we are using it: a router that
  1889. * we are considering for circuits, connections, and so on. A node_t is a
  1890. * thin wrapper around the routerstatus, routerinfo, and microdesc for a
  1891. * single wrapper, and provides a consistent interface for all of them.
  1892. *
  1893. * Also, a node_t has mutable state. While a routerinfo, a routerstatus,
  1894. * and a microdesc have[*] only the information read from a router
  1895. * descriptor, a consensus entry, and a microdescriptor (respectively)...
  1896. * a node_t has flags based on *our own current opinion* of the node.
  1897. *
  1898. * [*] Actually, there is some leftover information in each that is mutable.
  1899. * We should try to excise that.
  1900. */
  1901. typedef struct node_t {
  1902. /* Indexing information */
  1903. /** Used to look up the node_t by its identity digest. */
  1904. HT_ENTRY(node_t) ht_ent;
  1905. /** Position of the node within the list of nodes */
  1906. int nodelist_idx;
  1907. /** The identity digest of this node_t. No more than one node_t per
  1908. * identity may exist at a time. */
  1909. char identity[DIGEST_LEN];
  1910. microdesc_t *md;
  1911. routerinfo_t *ri;
  1912. routerstatus_t *rs;
  1913. /* local info: copied from routerstatus, then possibly frobbed based
  1914. * on experience. Authorities set this stuff directly. Note that
  1915. * these reflect knowledge of the primary (IPv4) OR port only. */
  1916. unsigned int is_running:1; /**< As far as we know, is this OR currently
  1917. * running? */
  1918. unsigned int is_valid:1; /**< Has a trusted dirserver validated this OR?
  1919. * (For Authdir: Have we validated this OR?) */
  1920. unsigned int is_fast:1; /** Do we think this is a fast OR? */
  1921. unsigned int is_stable:1; /** Do we think this is a stable OR? */
  1922. unsigned int is_possible_guard:1; /**< Do we think this is an OK guard? */
  1923. unsigned int is_exit:1; /**< Do we think this is an OK exit? */
  1924. unsigned int is_bad_exit:1; /**< Do we think this exit is censored, borked,
  1925. * or otherwise nasty? */
  1926. unsigned int is_bad_directory:1; /**< Do we think this directory is junky,
  1927. * underpowered, or otherwise useless? */
  1928. unsigned int is_hs_dir:1; /**< True iff this router is a hidden service
  1929. * directory according to the authorities. */
  1930. /* Local info: warning state. */
  1931. unsigned int name_lookup_warned:1; /**< Have we warned the user for referring
  1932. * to this (unnamed) router by nickname?
  1933. */
  1934. /** Local info: we treat this node as if it rejects everything */
  1935. unsigned int rejects_all:1;
  1936. /* Local info: derived. */
  1937. /** True if the IPv6 OR port is preferred over the IPv4 OR port. */
  1938. unsigned int ipv6_preferred:1;
  1939. /** According to the geoip db what country is this router in? */
  1940. /* XXXprop186 what is this suppose to mean with multiple OR ports? */
  1941. country_t country;
  1942. /* The below items are used only by authdirservers for
  1943. * reachability testing. */
  1944. /** When was the last time we could reach this OR? */
  1945. time_t last_reachable; /* IPv4. */
  1946. time_t last_reachable6; /* IPv6. */
  1947. } node_t;
  1948. /** How many times will we try to download a router's descriptor before giving
  1949. * up? */
  1950. #define MAX_ROUTERDESC_DOWNLOAD_FAILURES 8
  1951. /** How many times will we try to download a microdescriptor before giving
  1952. * up? */
  1953. #define MAX_MICRODESC_DOWNLOAD_FAILURES 8
  1954. /** Contents of a v2 (non-consensus, non-vote) network status object. */
  1955. typedef struct networkstatus_v2_t {
  1956. /** When did we receive the network-status document? */
  1957. time_t received_on;
  1958. /** What was the digest of the document? */
  1959. char networkstatus_digest[DIGEST_LEN];
  1960. /* These fields come from the actual network-status document.*/
  1961. time_t published_on; /**< Declared publication date. */
  1962. char *source_address; /**< Canonical directory server hostname. */
  1963. uint32_t source_addr; /**< Canonical directory server IP. */
  1964. uint16_t source_dirport; /**< Canonical directory server dirport. */
  1965. unsigned int binds_names:1; /**< True iff this directory server binds
  1966. * names. */
  1967. unsigned int recommends_versions:1; /**< True iff this directory server
  1968. * recommends client and server software
  1969. * versions. */
  1970. unsigned int lists_bad_exits:1; /**< True iff this directory server marks
  1971. * malfunctioning exits as bad. */
  1972. /** True iff this directory server marks malfunctioning directories as
  1973. * bad. */
  1974. unsigned int lists_bad_directories:1;
  1975. char identity_digest[DIGEST_LEN]; /**< Digest of signing key. */
  1976. char *contact; /**< How to contact directory admin? (may be NULL). */
  1977. crypto_pk_t *signing_key; /**< Key used to sign this directory. */
  1978. char *client_versions; /**< comma-separated list of recommended client
  1979. * versions. */
  1980. char *server_versions; /**< comma-separated list of recommended server
  1981. * versions. */
  1982. smartlist_t *entries; /**< List of routerstatus_t*. This list is kept
  1983. * sorted by identity_digest. */
  1984. } networkstatus_v2_t;
  1985. /** Linked list of microdesc hash lines for a single router in a directory
  1986. * vote.
  1987. */
  1988. typedef struct vote_microdesc_hash_t {
  1989. /** Next element in the list, or NULL. */
  1990. struct vote_microdesc_hash_t *next;
  1991. /** The raw contents of the microdesc hash line, excluding the "m". */
  1992. char *microdesc_hash_line;
  1993. } vote_microdesc_hash_t;
  1994. /** The claim about a single router, made in a vote. */
  1995. typedef struct vote_routerstatus_t {
  1996. routerstatus_t status; /**< Underlying 'status' object for this router.
  1997. * Flags are redundant. */
  1998. /** How many known-flags are allowed in a vote? This is the width of
  1999. * the flags field of vote_routerstatus_t */
  2000. #define MAX_KNOWN_FLAGS_IN_VOTE 64
  2001. uint64_t flags; /**< Bit-field for all recognized flags; index into
  2002. * networkstatus_t.known_flags. */
  2003. char *version; /**< The version that the authority says this router is
  2004. * running. */
  2005. /** The hash or hashes that the authority claims this microdesc has. */
  2006. vote_microdesc_hash_t *microdesc;
  2007. } vote_routerstatus_t;
  2008. /** A signature of some document by an authority. */
  2009. typedef struct document_signature_t {
  2010. /** Declared SHA-1 digest of this voter's identity key */
  2011. char identity_digest[DIGEST_LEN];
  2012. /** Declared SHA-1 digest of signing key used by this voter. */
  2013. char signing_key_digest[DIGEST_LEN];
  2014. /** Algorithm used to compute the digest of the document. */
  2015. digest_algorithm_t alg;
  2016. /** Signature of the signed thing. */
  2017. char *signature;
  2018. /** Length of <b>signature</b> */
  2019. int signature_len;
  2020. unsigned int bad_signature : 1; /**< Set to true if we've tried to verify
  2021. * the sig, and we know it's bad. */
  2022. unsigned int good_signature : 1; /**< Set to true if we've verified the sig
  2023. * as good. */
  2024. } document_signature_t;
  2025. /** Information about a single voter in a vote or a consensus. */
  2026. typedef struct networkstatus_voter_info_t {
  2027. /** Declared SHA-1 digest of this voter's identity key */
  2028. char identity_digest[DIGEST_LEN];
  2029. char *nickname; /**< Nickname of this voter */
  2030. /** Digest of this voter's "legacy" identity key, if any. In vote only; for
  2031. * consensuses, we treat legacy keys as additional signers. */
  2032. char legacy_id_digest[DIGEST_LEN];
  2033. char *address; /**< Address of this voter, in string format. */
  2034. uint32_t addr; /**< Address of this voter, in IPv4, in host order. */
  2035. uint16_t dir_port; /**< Directory port of this voter */
  2036. uint16_t or_port; /**< OR port of this voter */
  2037. char *contact; /**< Contact information for this voter. */
  2038. char vote_digest[DIGEST_LEN]; /**< Digest of this voter's vote, as signed. */
  2039. /* Nothing from here on is signed. */
  2040. /** The signature of the document and the signature's status. */
  2041. smartlist_t *sigs;
  2042. } networkstatus_voter_info_t;
  2043. /** Enumerates the possible seriousness values of a networkstatus document. */
  2044. typedef enum {
  2045. NS_TYPE_VOTE,
  2046. NS_TYPE_CONSENSUS,
  2047. NS_TYPE_OPINION,
  2048. } networkstatus_type_t;
  2049. /** Enumerates recognized flavors of a consensus networkstatus document. All
  2050. * flavors of a consensus are generated from the same set of votes, but they
  2051. * present different types information to different versions of Tor. */
  2052. typedef enum {
  2053. FLAV_NS = 0,
  2054. FLAV_MICRODESC = 1,
  2055. } consensus_flavor_t;
  2056. /** How many different consensus flavors are there? */
  2057. #define N_CONSENSUS_FLAVORS ((int)(FLAV_MICRODESC)+1)
  2058. /** A common structure to hold a v3 network status vote, or a v3 network
  2059. * status consensus. */
  2060. typedef struct networkstatus_t {
  2061. networkstatus_type_t type : 8; /**< Vote, consensus, or opinion? */
  2062. consensus_flavor_t flavor : 8; /**< If a consensus, what kind? */
  2063. time_t published; /**< Vote only: Time when vote was written. */
  2064. time_t valid_after; /**< Time after which this vote or consensus applies. */
  2065. time_t fresh_until; /**< Time before which this is the most recent vote or
  2066. * consensus. */
  2067. time_t valid_until; /**< Time after which this vote or consensus should not
  2068. * be used. */
  2069. /** Consensus only: what method was used to produce this consensus? */
  2070. int consensus_method;
  2071. /** Vote only: what methods is this voter willing to use? */
  2072. smartlist_t *supported_methods;
  2073. /** How long does this vote/consensus claim that authorities take to
  2074. * distribute their votes to one another? */
  2075. int vote_seconds;
  2076. /** How long does this vote/consensus claim that authorities take to
  2077. * distribute their consensus signatures to one another? */
  2078. int dist_seconds;
  2079. /** Comma-separated list of recommended client software, or NULL if this
  2080. * voter has no opinion. */
  2081. char *client_versions;
  2082. char *server_versions;
  2083. /** List of flags that this vote/consensus applies to routers. If a flag is
  2084. * not listed here, the voter has no opinion on what its value should be. */
  2085. smartlist_t *known_flags;
  2086. /** List of key=value strings for the parameters in this vote or
  2087. * consensus, sorted by key. */
  2088. smartlist_t *net_params;
  2089. /** List of key=value strings for the bw weight parameters in the
  2090. * consensus. */
  2091. smartlist_t *weight_params;
  2092. /** List of networkstatus_voter_info_t. For a vote, only one element
  2093. * is included. For a consensus, one element is included for every voter
  2094. * whose vote contributed to the consensus. */
  2095. smartlist_t *voters;
  2096. struct authority_cert_t *cert; /**< Vote only: the voter's certificate. */
  2097. /** Digests of this document, as signed. */
  2098. digests_t digests;
  2099. /** List of router statuses, sorted by identity digest. For a vote,
  2100. * the elements are vote_routerstatus_t; for a consensus, the elements
  2101. * are routerstatus_t. */
  2102. smartlist_t *routerstatus_list;
  2103. /** If present, a map from descriptor digest to elements of
  2104. * routerstatus_list. */
  2105. digestmap_t *desc_digest_map;
  2106. } networkstatus_t;
  2107. /** A set of signatures for a networkstatus consensus. Unless otherwise
  2108. * noted, all fields are as for networkstatus_t. */
  2109. typedef struct ns_detached_signatures_t {
  2110. time_t valid_after;
  2111. time_t fresh_until;
  2112. time_t valid_until;
  2113. strmap_t *digests; /**< Map from flavor name to digestset_t */
  2114. strmap_t *signatures; /**< Map from flavor name to list of
  2115. * document_signature_t */
  2116. } ns_detached_signatures_t;
  2117. /** Allowable types of desc_store_t. */
  2118. typedef enum store_type_t {
  2119. ROUTER_STORE = 0,
  2120. EXTRAINFO_STORE = 1
  2121. } store_type_t;
  2122. /** A 'store' is a set of descriptors saved on disk, with accompanying
  2123. * journal, mmaped as needed, rebuilt as needed. */
  2124. typedef struct desc_store_t {
  2125. /** Filename (within DataDir) for the store. We append .tmp to this
  2126. * filename for a temporary file when rebuilding the store, and .new to this
  2127. * filename for the journal. */
  2128. const char *fname_base;
  2129. /** Alternative (obsolete) value for fname_base: if the file named by
  2130. * fname_base isn't present, we read from here instead, but we never write
  2131. * here. */
  2132. const char *fname_alt_base;
  2133. /** Human-readable description of what this store contains. */
  2134. const char *description;
  2135. tor_mmap_t *mmap; /**< A mmap for the main file in the store. */
  2136. store_type_t type; /**< What's stored in this store? */
  2137. /** The size of the router log, in bytes. */
  2138. size_t journal_len;
  2139. /** The size of the router store, in bytes. */
  2140. size_t store_len;
  2141. /** Total bytes dropped since last rebuild: this is space currently
  2142. * used in the cache and the journal that could be freed by a rebuild. */
  2143. size_t bytes_dropped;
  2144. } desc_store_t;
  2145. /** Contents of a directory of onion routers. */
  2146. typedef struct {
  2147. /** Map from server identity digest to a member of routers. */
  2148. struct digest_ri_map_t *identity_map;
  2149. /** Map from server descriptor digest to a signed_descriptor_t from
  2150. * routers or old_routers. */
  2151. struct digest_sd_map_t *desc_digest_map;
  2152. /** Map from extra-info digest to an extrainfo_t. Only exists for
  2153. * routers in routers or old_routers. */
  2154. struct digest_ei_map_t *extra_info_map;
  2155. /** Map from extra-info digests to a signed_descriptor_t for a router
  2156. * descriptor having that extra-info digest. Only exists for
  2157. * routers in routers or old_routers. */
  2158. struct digest_sd_map_t *desc_by_eid_map;
  2159. /** List of routerinfo_t for all currently live routers we know. */
  2160. smartlist_t *routers;
  2161. /** List of signed_descriptor_t for older router descriptors we're
  2162. * caching. */
  2163. smartlist_t *old_routers;
  2164. /** Store holding server descriptors. If present, any router whose
  2165. * cache_info.saved_location == SAVED_IN_CACHE is stored in this file
  2166. * starting at cache_info.saved_offset */
  2167. desc_store_t desc_store;
  2168. /** Store holding extra-info documents. */
  2169. desc_store_t extrainfo_store;
  2170. } routerlist_t;
  2171. /** Information on router used when extending a circuit. We don't need a
  2172. * full routerinfo_t to extend: we only need addr:port:keyid to build an OR
  2173. * connection, and onion_key to create the onionskin. Note that for onehop
  2174. * general-purpose tunnels, the onion_key is NULL. */
  2175. typedef struct extend_info_t {
  2176. char nickname[MAX_HEX_NICKNAME_LEN+1]; /**< This router's nickname for
  2177. * display. */
  2178. char identity_digest[DIGEST_LEN]; /**< Hash of this router's identity key. */
  2179. uint16_t port; /**< OR port. */
  2180. tor_addr_t addr; /**< IP address. */
  2181. crypto_pk_t *onion_key; /**< Current onionskin key. */
  2182. #ifdef CURVE25519_ENABLED
  2183. curve25519_public_key_t curve25519_onion_key;
  2184. #endif
  2185. } extend_info_t;
  2186. /** Certificate for v3 directory protocol: binds long-term authority identity
  2187. * keys to medium-term authority signing keys. */
  2188. typedef struct authority_cert_t {
  2189. /** Information relating to caching this cert on disk and looking it up. */
  2190. signed_descriptor_t cache_info;
  2191. /** This authority's long-term authority identity key. */
  2192. crypto_pk_t *identity_key;
  2193. /** This authority's medium-term signing key. */
  2194. crypto_pk_t *signing_key;
  2195. /** The digest of <b>signing_key</b> */
  2196. char signing_key_digest[DIGEST_LEN];
  2197. /** The listed expiration time of this certificate. */
  2198. time_t expires;
  2199. /** This authority's IPv4 address, in host order. */
  2200. uint32_t addr;
  2201. /** This authority's directory port. */
  2202. uint16_t dir_port;
  2203. /** True iff this certificate was cross-certified by signing the identity
  2204. * key with the signing key. */
  2205. uint8_t is_cross_certified;
  2206. } authority_cert_t;
  2207. /** Bitfield enum type listing types of information that directory authorities
  2208. * can be authoritative about, and that directory caches may or may not cache.
  2209. *
  2210. * Note that the granularity here is based on authority granularity and on
  2211. * cache capabilities. Thus, one particular bit may correspond in practice to
  2212. * a few types of directory info, so long as every authority that pronounces
  2213. * officially about one of the types prounounces officially about all of them,
  2214. * and so long as every cache that caches one of them caches all of them.
  2215. */
  2216. typedef enum {
  2217. NO_DIRINFO = 0,
  2218. /** Serves/signs v1 directory information: Big lists of routers, and short
  2219. * routerstatus documents. */
  2220. V1_DIRINFO = 1 << 0,
  2221. /** Serves/signs v2 directory information: i.e. v2 networkstatus documents */
  2222. V2_DIRINFO = 1 << 1,
  2223. /** Serves/signs v3 directory information: votes, consensuses, certs */
  2224. V3_DIRINFO = 1 << 2,
  2225. /** Serves hidden service descriptors. */
  2226. HIDSERV_DIRINFO = 1 << 3,
  2227. /** Serves bridge descriptors. */
  2228. BRIDGE_DIRINFO = 1 << 4,
  2229. /** Serves extrainfo documents. */
  2230. EXTRAINFO_DIRINFO=1 << 5,
  2231. /** Serves microdescriptors. */
  2232. MICRODESC_DIRINFO=1 << 6,
  2233. } dirinfo_type_t;
  2234. #define CRYPT_PATH_MAGIC 0x70127012u
  2235. struct fast_handshake_state_t;
  2236. struct ntor_handshake_state_t;
  2237. #define ONION_HANDSHAKE_TYPE_TAP 0x0000
  2238. #define ONION_HANDSHAKE_TYPE_FAST 0x0001
  2239. #define ONION_HANDSHAKE_TYPE_NTOR 0x0002
  2240. typedef struct {
  2241. uint16_t tag;
  2242. union {
  2243. struct fast_handshake_state_t *fast;
  2244. crypto_dh_t *tap;
  2245. struct ntor_handshake_state_t *ntor;
  2246. } u;
  2247. } onion_handshake_state_t;
  2248. /** Holds accounting information for a single step in the layered encryption
  2249. * performed by a circuit. Used only at the client edge of a circuit. */
  2250. typedef struct crypt_path_t {
  2251. uint32_t magic;
  2252. /* crypto environments */
  2253. /** Encryption key and counter for cells heading towards the OR at this
  2254. * step. */
  2255. crypto_cipher_t *f_crypto;
  2256. /** Encryption key and counter for cells heading back from the OR at this
  2257. * step. */
  2258. crypto_cipher_t *b_crypto;
  2259. /** Digest state for cells heading towards the OR at this step. */
  2260. crypto_digest_t *f_digest; /* for integrity checking */
  2261. /** Digest state for cells heading away from the OR at this step. */
  2262. crypto_digest_t *b_digest;
  2263. /** Current state of the handshake as performed with the OR at this
  2264. * step. */
  2265. onion_handshake_state_t handshake_state;
  2266. /** Diffie-hellman handshake state for performing an introduction
  2267. * operations */
  2268. crypto_dh_t *rend_dh_handshake_state;
  2269. /** Negotiated key material shared with the OR at this step. */
  2270. /* XXXX RENAME */
  2271. char handshake_digest[DIGEST_LEN];/* KH in tor-spec.txt */
  2272. /** Information to extend to the OR at this step. */
  2273. extend_info_t *extend_info;
  2274. /** Is the circuit built to this step? Must be one of:
  2275. * - CPATH_STATE_CLOSED (The circuit has not been extended to this step)
  2276. * - CPATH_STATE_AWAITING_KEYS (We have sent an EXTEND/CREATE to this step
  2277. * and not received an EXTENDED/CREATED)
  2278. * - CPATH_STATE_OPEN (The circuit has been extended to this step) */
  2279. uint8_t state;
  2280. #define CPATH_STATE_CLOSED 0
  2281. #define CPATH_STATE_AWAITING_KEYS 1
  2282. #define CPATH_STATE_OPEN 2
  2283. struct crypt_path_t *next; /**< Link to next crypt_path_t in the circuit.
  2284. * (The list is circular, so the last node
  2285. * links to the first.) */
  2286. struct crypt_path_t *prev; /**< Link to previous crypt_path_t in the
  2287. * circuit. */
  2288. int package_window; /**< How many cells are we allowed to originate ending
  2289. * at this step? */
  2290. int deliver_window; /**< How many cells are we willing to deliver originating
  2291. * at this step? */
  2292. } crypt_path_t;
  2293. /** A reference-counted pointer to a crypt_path_t, used only to share
  2294. * the final rendezvous cpath to be used on a service-side rendezvous
  2295. * circuit among multiple circuits built in parallel to the same
  2296. * destination rendezvous point. */
  2297. typedef struct {
  2298. /** The reference count. */
  2299. unsigned int refcount;
  2300. /** The pointer. Set to NULL when the crypt_path_t is put into use
  2301. * on an opened rendezvous circuit. */
  2302. crypt_path_t *cpath;
  2303. } crypt_path_reference_t;
  2304. #define CPATH_KEY_MATERIAL_LEN (20*2+16*2)
  2305. #define DH_KEY_LEN DH_BYTES
  2306. /** Information used to build a circuit. */
  2307. typedef struct {
  2308. /** Intended length of the final circuit. */
  2309. int desired_path_len;
  2310. /** How to extend to the planned exit node. */
  2311. extend_info_t *chosen_exit;
  2312. /** Whether every node in the circ must have adequate uptime. */
  2313. unsigned int need_uptime : 1;
  2314. /** Whether every node in the circ must have adequate capacity. */
  2315. unsigned int need_capacity : 1;
  2316. /** Whether the last hop was picked with exiting in mind. */
  2317. unsigned int is_internal : 1;
  2318. /** Did we pick this as a one-hop tunnel (not safe for other streams)?
  2319. * These are for encrypted dir conns that exit to this router, not
  2320. * for arbitrary exits from the circuit. */
  2321. unsigned int onehop_tunnel : 1;
  2322. /** The crypt_path_t to append after rendezvous: used for rendezvous. */
  2323. crypt_path_t *pending_final_cpath;
  2324. /** A ref-counted reference to the crypt_path_t to append after
  2325. * rendezvous; used on the service side. */
  2326. crypt_path_reference_t *service_pending_final_cpath_ref;
  2327. /** How many times has building a circuit for this task failed? */
  2328. int failure_count;
  2329. /** At what time should we give up on this task? */
  2330. time_t expiry_time;
  2331. } cpath_build_state_t;
  2332. #define ORIGIN_CIRCUIT_MAGIC 0x35315243u
  2333. #define OR_CIRCUIT_MAGIC 0x98ABC04Fu
  2334. /**
  2335. * A circuit is a path over the onion routing
  2336. * network. Applications can connect to one end of the circuit, and can
  2337. * create exit connections at the other end of the circuit. AP and exit
  2338. * connections have only one circuit associated with them (and thus these
  2339. * connection types are closed when the circuit is closed), whereas
  2340. * OR connections multiplex many circuits at once, and stay standing even
  2341. * when there are no circuits running over them.
  2342. *
  2343. * A circuit_t structure can fill one of two roles. First, a or_circuit_t
  2344. * links two connections together: either an edge connection and an OR
  2345. * connection, or two OR connections. (When joined to an OR connection, a
  2346. * circuit_t affects only cells sent to a particular circID on that
  2347. * connection. When joined to an edge connection, a circuit_t affects all
  2348. * data.)
  2349. * Second, an origin_circuit_t holds the cipher keys and state for sending data
  2350. * along a given circuit. At the OP, it has a sequence of ciphers, each
  2351. * of which is shared with a single OR along the circuit. Separate
  2352. * ciphers are used for data going "forward" (away from the OP) and
  2353. * "backward" (towards the OP). At the OR, a circuit has only two stream
  2354. * ciphers: one for data going forward, and one for data going backward.
  2355. */
  2356. typedef struct circuit_t {
  2357. uint32_t magic; /**< For memory and type debugging: must equal
  2358. * ORIGIN_CIRCUIT_MAGIC or OR_CIRCUIT_MAGIC. */
  2359. /** The channel that is next in this circuit. */
  2360. channel_t *n_chan;
  2361. /**
  2362. * The circuit_id used in the next (forward) hop of this circuit;
  2363. * this is unique to n_chan, but this ordered pair is globally
  2364. * unique:
  2365. *
  2366. * (n_chan->global_identifier, n_circ_id)
  2367. */
  2368. circid_t n_circ_id;
  2369. /**
  2370. * Circuit mux associated with n_chan to which this circuit is attached;
  2371. * NULL if we have no n_chan.
  2372. */
  2373. circuitmux_t *n_mux;
  2374. /** Queue of cells waiting to be transmitted on n_chan */
  2375. cell_queue_t n_chan_cells;
  2376. /**
  2377. * The hop to which we want to extend this circuit. Should be NULL if
  2378. * the circuit has attached to a channel.
  2379. */
  2380. extend_info_t *n_hop;
  2381. /** True iff we are waiting for n_chan_cells to become less full before
  2382. * allowing p_streams to add any more cells. (Origin circuit only.) */
  2383. unsigned int streams_blocked_on_n_chan : 1;
  2384. /** True iff we are waiting for p_chan_cells to become less full before
  2385. * allowing n_streams to add any more cells. (OR circuit only.) */
  2386. unsigned int streams_blocked_on_p_chan : 1;
  2387. uint8_t state; /**< Current status of this circuit. */
  2388. uint8_t purpose; /**< Why are we creating this circuit? */
  2389. /** How many relay data cells can we package (read from edge streams)
  2390. * on this circuit before we receive a circuit-level sendme cell asking
  2391. * for more? */
  2392. int package_window;
  2393. /** How many relay data cells will we deliver (write to edge streams)
  2394. * on this circuit? When deliver_window gets low, we send some
  2395. * circuit-level sendme cells to indicate that we're willing to accept
  2396. * more. */
  2397. int deliver_window;
  2398. uint8_t n_chan_onionskin_len; /* XXXX MAKE THIS GET USED. */
  2399. /** For storage while n_chan is pending
  2400. * (state CIRCUIT_STATE_CHAN_WAIT). When defined, it is always
  2401. * length n_chan_onionskin_len */
  2402. char *n_chan_onionskin;
  2403. /** When was this circuit created? We keep this timestamp with a higher
  2404. * resolution than most so that the circuit-build-time tracking code can
  2405. * get millisecond resolution. */
  2406. struct timeval timestamp_created;
  2407. /** When the circuit was first used, or 0 if the circuit is clean.
  2408. *
  2409. * XXXX023 Note that some code will artifically adjust this value backward
  2410. * in time in order to indicate that a circuit shouldn't be used for new
  2411. * streams, but that it can stay alive as long as it has streams on it.
  2412. * That's a kludge we should fix.
  2413. *
  2414. * XXX023 The CBT code uses this field to record when HS-related
  2415. * circuits entered certain states. This usage probably won't
  2416. * interfere with this field's primary purpose, but we should
  2417. * document it more thoroughly to make sure of that.
  2418. */
  2419. time_t timestamp_dirty;
  2420. uint16_t marked_for_close; /**< Should we close this circuit at the end of
  2421. * the main loop? (If true, holds the line number
  2422. * where this circuit was marked.) */
  2423. const char *marked_for_close_file; /**< For debugging: in which file was this
  2424. * circuit marked for close? */
  2425. /** Unique ID for measuring tunneled network status requests. */
  2426. uint64_t dirreq_id;
  2427. struct circuit_t *next; /**< Next circuit in linked list of all circuits. */
  2428. /** Next circuit in the doubly-linked ring of circuits waiting to add
  2429. * cells to n_conn. NULL if we have no cells pending, or if we're not
  2430. * linked to an OR connection. */
  2431. struct circuit_t *next_active_on_n_chan;
  2432. /** Previous circuit in the doubly-linked ring of circuits waiting to add
  2433. * cells to n_conn. NULL if we have no cells pending, or if we're not
  2434. * linked to an OR connection. */
  2435. struct circuit_t *prev_active_on_n_chan;
  2436. } circuit_t;
  2437. /** Largest number of relay_early cells that we can send on a given
  2438. * circuit. */
  2439. #define MAX_RELAY_EARLY_CELLS_PER_CIRCUIT 8
  2440. /**
  2441. * Describes the circuit building process in simplified terms based
  2442. * on the path bias accounting state for a circuit. Created to prevent
  2443. * overcounting due to unknown cases of circuit reuse. See Bug #6475.
  2444. */
  2445. typedef enum {
  2446. /** This circuit is "new". It has not yet completed a first hop
  2447. * or been counted by the path bias code. */
  2448. PATH_STATE_NEW_CIRC = 0,
  2449. /** This circuit has completed a first hop, and has been counted by
  2450. * the path bias logic. */
  2451. PATH_STATE_DID_FIRST_HOP = 1,
  2452. /** This circuit has been completely built, and has been counted as
  2453. * successful by the path bias logic. */
  2454. PATH_STATE_SUCCEEDED = 2,
  2455. } path_state_t;
  2456. /** An origin_circuit_t holds data necessary to build and use a circuit.
  2457. */
  2458. typedef struct origin_circuit_t {
  2459. circuit_t base_;
  2460. /** Linked list of AP streams (or EXIT streams if hidden service)
  2461. * associated with this circuit. */
  2462. edge_connection_t *p_streams;
  2463. /** Build state for this circuit. It includes the intended path
  2464. * length, the chosen exit router, rendezvous information, etc.
  2465. */
  2466. cpath_build_state_t *build_state;
  2467. /** The doubly-linked list of crypt_path_t entries, one per hop,
  2468. * for this circuit. This includes ciphers for each hop,
  2469. * integrity-checking digests for each hop, and package/delivery
  2470. * windows for each hop.
  2471. */
  2472. crypt_path_t *cpath;
  2473. /** Holds all rendezvous data on either client or service side. */
  2474. rend_data_t *rend_data;
  2475. /** How many more relay_early cells can we send on this circuit, according
  2476. * to the specification? */
  2477. unsigned int remaining_relay_early_cells : 4;
  2478. /** Set if this circuit is insanely old and we already informed the user */
  2479. unsigned int is_ancient : 1;
  2480. /** Set if this circuit has already been opened. Used to detect
  2481. * cannibalized circuits. */
  2482. unsigned int has_opened : 1;
  2483. /** Kludge to help us prevent the warn in bug #6475 and eventually
  2484. * debug why we are not seeing first hops in some cases. */
  2485. path_state_t path_state : 2;
  2486. /** Set iff this is a hidden-service circuit which has timed out
  2487. * according to our current circuit-build timeout, but which has
  2488. * been kept around because it might still succeed in connecting to
  2489. * its destination, and which is not a fully-connected rendezvous
  2490. * circuit.
  2491. *
  2492. * (We clear this flag for client-side rendezvous circuits when they
  2493. * are 'joined' to the other side's rendezvous circuit, so that
  2494. * connection_ap_handshake_attach_circuit can put client streams on
  2495. * the circuit. We also clear this flag for service-side rendezvous
  2496. * circuits when they are 'joined' to a client's rend circ, but only
  2497. * for symmetry with the client case. Client-side introduction
  2498. * circuits are closed when we get a joined rend circ, and
  2499. * service-side introduction circuits never have this flag set.) */
  2500. unsigned int hs_circ_has_timed_out : 1;
  2501. /** Set iff this is a service-side rendezvous circuit for which a
  2502. * new connection attempt has been launched. We consider launching
  2503. * a new service-side rend circ to a client when the previous one
  2504. * fails; now that we don't necessarily close a service-side rend
  2505. * circ when we launch a new one to the same client, this flag keeps
  2506. * us from launching two retries for the same failed rend circ. */
  2507. unsigned int hs_service_side_rend_circ_has_been_relaunched : 1;
  2508. /** What commands were sent over this circuit that decremented the
  2509. * RELAY_EARLY counter? This is for debugging task 878. */
  2510. uint8_t relay_early_commands[MAX_RELAY_EARLY_CELLS_PER_CIRCUIT];
  2511. /** How many RELAY_EARLY cells have been sent over this circuit? This is
  2512. * for debugging task 878, too. */
  2513. int relay_early_cells_sent;
  2514. /** The next stream_id that will be tried when we're attempting to
  2515. * construct a new AP stream originating at this circuit. */
  2516. streamid_t next_stream_id;
  2517. /* The intro key replaces the hidden service's public key if purpose is
  2518. * S_ESTABLISH_INTRO or S_INTRO, provided that no unversioned rendezvous
  2519. * descriptor is used. */
  2520. crypto_pk_t *intro_key;
  2521. /** Quasi-global identifier for this circuit; used for control.c */
  2522. /* XXXX NM This can get re-used after 2**32 circuits. */
  2523. uint32_t global_identifier;
  2524. /** True if we have associated one stream to this circuit, thereby setting
  2525. * the isolation paramaters for this circuit. Note that this doesn't
  2526. * necessarily mean that we've <em>attached</em> any streams to the circuit:
  2527. * we may only have marked up this circuit during the launch process.
  2528. */
  2529. unsigned int isolation_values_set : 1;
  2530. /** True iff any stream has <em>ever</em> been attached to this circuit.
  2531. *
  2532. * In a better world we could use timestamp_dirty for this, but
  2533. * timestamp_dirty is far too overloaded at the moment.
  2534. */
  2535. unsigned int isolation_any_streams_attached : 1;
  2536. /** A bitfield of ISO_* flags for every isolation field such that this
  2537. * circuit has had streams with more than one value for that field
  2538. * attached to it. */
  2539. uint8_t isolation_flags_mixed;
  2540. /** @name Isolation parameters
  2541. *
  2542. * If any streams have been associated with this circ (isolation_values_set
  2543. * == 1), and all streams associated with the circuit have had the same
  2544. * value for some field ((isolation_flags_mixed & ISO_FOO) == 0), then these
  2545. * elements hold the value for that field.
  2546. *
  2547. * Note again that "associated" is not the same as "attached": we
  2548. * preliminarily associate streams with a circuit while the circuit is being
  2549. * launched, so that we can tell whether we need to launch more circuits.
  2550. *
  2551. * @{
  2552. */
  2553. uint8_t client_proto_type;
  2554. uint8_t client_proto_socksver;
  2555. uint16_t dest_port;
  2556. tor_addr_t client_addr;
  2557. char *dest_address;
  2558. int session_group;
  2559. unsigned nym_epoch;
  2560. size_t socks_username_len;
  2561. uint8_t socks_password_len;
  2562. /* Note that the next two values are NOT NUL-terminated; see
  2563. socks_username_len and socks_password_len for their lengths. */
  2564. char *socks_username;
  2565. char *socks_password;
  2566. /** Global identifier for the first stream attached here; used by
  2567. * ISO_STREAM. */
  2568. uint64_t associated_isolated_stream_global_id;
  2569. /**@}*/
  2570. } origin_circuit_t;
  2571. /** An or_circuit_t holds information needed to implement a circuit at an
  2572. * OR. */
  2573. typedef struct or_circuit_t {
  2574. circuit_t base_;
  2575. /** Next circuit in the doubly-linked ring of circuits waiting to add
  2576. * cells to p_chan. NULL if we have no cells pending, or if we're not
  2577. * linked to an OR connection. */
  2578. struct circuit_t *next_active_on_p_chan;
  2579. /** Previous circuit in the doubly-linked ring of circuits waiting to add
  2580. * cells to p_chan. NULL if we have no cells pending, or if we're not
  2581. * linked to an OR connection. */
  2582. struct circuit_t *prev_active_on_p_chan;
  2583. /** The circuit_id used in the previous (backward) hop of this circuit. */
  2584. circid_t p_circ_id;
  2585. /** Queue of cells waiting to be transmitted on p_conn. */
  2586. cell_queue_t p_chan_cells;
  2587. /** The channel that is previous in this circuit. */
  2588. channel_t *p_chan;
  2589. /**
  2590. * Circuit mux associated with p_chan to which this circuit is attached;
  2591. * NULL if we have no p_chan.
  2592. */
  2593. circuitmux_t *p_mux;
  2594. /** Linked list of Exit streams associated with this circuit. */
  2595. edge_connection_t *n_streams;
  2596. /** Linked list of Exit streams associated with this circuit that are
  2597. * still being resolved. */
  2598. edge_connection_t *resolving_streams;
  2599. /** The cipher used by intermediate hops for cells heading toward the
  2600. * OP. */
  2601. crypto_cipher_t *p_crypto;
  2602. /** The cipher used by intermediate hops for cells heading away from
  2603. * the OP. */
  2604. crypto_cipher_t *n_crypto;
  2605. /** The integrity-checking digest used by intermediate hops, for
  2606. * cells packaged here and heading towards the OP.
  2607. */
  2608. crypto_digest_t *p_digest;
  2609. /** The integrity-checking digest used by intermediate hops, for
  2610. * cells packaged at the OP and arriving here.
  2611. */
  2612. crypto_digest_t *n_digest;
  2613. /** Points to spliced circuit if purpose is REND_ESTABLISHED, and circuit
  2614. * is not marked for close. */
  2615. struct or_circuit_t *rend_splice;
  2616. #if REND_COOKIE_LEN >= DIGEST_LEN
  2617. #define REND_TOKEN_LEN REND_COOKIE_LEN
  2618. #else
  2619. #define REND_TOKEN_LEN DIGEST_LEN
  2620. #endif
  2621. /** A hash of location-hidden service's PK if purpose is INTRO_POINT, or a
  2622. * rendezvous cookie if purpose is REND_POINT_WAITING. Filled with zeroes
  2623. * otherwise.
  2624. * ???? move to a subtype or adjunct structure? Wastes 20 bytes. -NM
  2625. */
  2626. char rend_token[REND_TOKEN_LEN];
  2627. /* ???? move to a subtype or adjunct structure? Wastes 20 bytes -NM */
  2628. /* XXXX rename this. */
  2629. char handshake_digest[DIGEST_LEN]; /**< Stores KH for the handshake. */
  2630. /** How many more relay_early cells can we send on this circuit, according
  2631. * to the specification? */
  2632. unsigned int remaining_relay_early_cells : 4;
  2633. /** True iff this circuit was made with a CREATE_FAST cell. */
  2634. unsigned int is_first_hop : 1;
  2635. /** Number of cells that were removed from circuit queue; reset every
  2636. * time when writing buffer stats to disk. */
  2637. uint32_t processed_cells;
  2638. /** Total time in milliseconds that cells spent in both app-ward and
  2639. * exit-ward queues of this circuit; reset every time when writing
  2640. * buffer stats to disk. */
  2641. uint64_t total_cell_waiting_time;
  2642. } or_circuit_t;
  2643. /** Convert a circuit subtype to a circuit_t. */
  2644. #define TO_CIRCUIT(x) (&((x)->base_))
  2645. /** Convert a circuit_t* to a pointer to the enclosing or_circuit_t. Assert
  2646. * if the cast is impossible. */
  2647. static or_circuit_t *TO_OR_CIRCUIT(circuit_t *);
  2648. /** Convert a circuit_t* to a pointer to the enclosing origin_circuit_t.
  2649. * Assert if the cast is impossible. */
  2650. static origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *);
  2651. static INLINE or_circuit_t *TO_OR_CIRCUIT(circuit_t *x)
  2652. {
  2653. tor_assert(x->magic == OR_CIRCUIT_MAGIC);
  2654. return DOWNCAST(or_circuit_t, x);
  2655. }
  2656. static INLINE origin_circuit_t *TO_ORIGIN_CIRCUIT(circuit_t *x)
  2657. {
  2658. tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
  2659. return DOWNCAST(origin_circuit_t, x);
  2660. }
  2661. /** Bitfield type: things that we're willing to use invalid routers for. */
  2662. typedef enum invalid_router_usage_t {
  2663. ALLOW_INVALID_ENTRY =1,
  2664. ALLOW_INVALID_EXIT =2,
  2665. ALLOW_INVALID_MIDDLE =4,
  2666. ALLOW_INVALID_RENDEZVOUS =8,
  2667. ALLOW_INVALID_INTRODUCTION=16,
  2668. } invalid_router_usage_t;
  2669. /* limits for TCP send and recv buffer size used for constrained sockets */
  2670. #define MIN_CONSTRAINED_TCP_BUFFER 2048
  2671. #define MAX_CONSTRAINED_TCP_BUFFER 262144 /* 256k */
  2672. /** @name Isolation flags
  2673. Ways to isolate client streams
  2674. @{
  2675. */
  2676. /** Isolate based on destination port */
  2677. #define ISO_DESTPORT (1u<<0)
  2678. /** Isolate based on destination address */
  2679. #define ISO_DESTADDR (1u<<1)
  2680. /** Isolate based on SOCKS authentication */
  2681. #define ISO_SOCKSAUTH (1u<<2)
  2682. /** Isolate based on client protocol choice */
  2683. #define ISO_CLIENTPROTO (1u<<3)
  2684. /** Isolate based on client address */
  2685. #define ISO_CLIENTADDR (1u<<4)
  2686. /** Isolate based on session group (always on). */
  2687. #define ISO_SESSIONGRP (1u<<5)
  2688. /** Isolate based on newnym epoch (always on). */
  2689. #define ISO_NYM_EPOCH (1u<<6)
  2690. /** Isolate all streams (Internal only). */
  2691. #define ISO_STREAM (1u<<7)
  2692. /**@}*/
  2693. /** Default isolation level for ports. */
  2694. #define ISO_DEFAULT (ISO_CLIENTADDR|ISO_SOCKSAUTH|ISO_SESSIONGRP|ISO_NYM_EPOCH)
  2695. /** Indicates that we haven't yet set a session group on a port_cfg_t. */
  2696. #define SESSION_GROUP_UNSET -1
  2697. /** Session group reserved for directory connections */
  2698. #define SESSION_GROUP_DIRCONN -2
  2699. /** Session group reserved for resolve requests launched by a controller */
  2700. #define SESSION_GROUP_CONTROL_RESOLVE -3
  2701. /** First automatically allocated session group number */
  2702. #define SESSION_GROUP_FIRST_AUTO -4
  2703. /** Configuration for a single port that we're listening on. */
  2704. typedef struct port_cfg_t {
  2705. tor_addr_t addr; /**< The actual IP to listen on, if !is_unix_addr. */
  2706. int port; /**< The configured port, or CFG_AUTO_PORT to tell Tor to pick its
  2707. * own port. */
  2708. uint8_t type; /**< One of CONN_TYPE_*_LISTENER */
  2709. unsigned is_unix_addr : 1; /**< True iff this is an AF_UNIX address. */
  2710. /* Client port types (socks, dns, trans, natd) only: */
  2711. uint8_t isolation_flags; /**< Zero or more isolation flags */
  2712. int session_group; /**< A session group, or -1 if this port is not in a
  2713. * session group. */
  2714. /* Server port types (or, dir) only: */
  2715. unsigned int no_advertise : 1;
  2716. unsigned int no_listen : 1;
  2717. unsigned int all_addrs : 1;
  2718. unsigned int bind_ipv4_only : 1;
  2719. unsigned int bind_ipv6_only : 1;
  2720. unsigned int ipv4_traffic : 1;
  2721. unsigned int ipv6_traffic : 1;
  2722. unsigned int prefer_ipv6 : 1;
  2723. /* Unix sockets only: */
  2724. /** Path for an AF_UNIX address */
  2725. char unix_addr[FLEXIBLE_ARRAY_MEMBER];
  2726. } port_cfg_t;
  2727. /** Ordinary configuration line. */
  2728. #define CONFIG_LINE_NORMAL 0
  2729. /** Appends to previous configuration for the same option, even if we
  2730. * would ordinary replace it. */
  2731. #define CONFIG_LINE_APPEND 1
  2732. /* Removes all previous configuration for an option. */
  2733. #define CONFIG_LINE_CLEAR 2
  2734. /** A linked list of lines in a config file. */
  2735. typedef struct config_line_t {
  2736. char *key;
  2737. char *value;
  2738. struct config_line_t *next;
  2739. /** What special treatment (if any) does this line require? */
  2740. unsigned int command:2;
  2741. /** If true, subsequent assignments to this linelist should replace
  2742. * it, not extend it. Set only on the first item in a linelist in an
  2743. * or_options_t. */
  2744. unsigned int fragile:1;
  2745. } config_line_t;
  2746. typedef struct routerset_t routerset_t;
  2747. /** A magic value for the (Socks|OR|...)Port options below, telling Tor
  2748. * to pick its own port. */
  2749. #define CFG_AUTO_PORT 0xc4005e
  2750. /** Configuration options for a Tor process. */
  2751. typedef struct {
  2752. uint32_t magic_;
  2753. /** What should the tor process actually do? */
  2754. enum {
  2755. CMD_RUN_TOR=0, CMD_LIST_FINGERPRINT, CMD_HASH_PASSWORD,
  2756. CMD_VERIFY_CONFIG, CMD_RUN_UNITTESTS
  2757. } command;
  2758. const char *command_arg; /**< Argument for command-line option. */
  2759. config_line_t *Logs; /**< New-style list of configuration lines
  2760. * for logs */
  2761. int LogTimeGranularity; /**< Log resolution in milliseconds. */
  2762. int LogMessageDomains; /**< Boolean: Should we log the domain(s) in which
  2763. * each log message occurs? */
  2764. char *DebugLogFile; /**< Where to send verbose log messages. */
  2765. char *DataDirectory; /**< OR only: where to store long-term data. */
  2766. char *Nickname; /**< OR only: nickname of this onion router. */
  2767. char *Address; /**< OR only: configured address for this onion router. */
  2768. char *PidFile; /**< Where to store PID of Tor process. */
  2769. int DynamicDHGroups; /**< Dynamic generation of prime moduli for use in DH.*/
  2770. routerset_t *ExitNodes; /**< Structure containing nicknames, digests,
  2771. * country codes and IP address patterns of ORs to
  2772. * consider as exits. */
  2773. routerset_t *EntryNodes;/**< Structure containing nicknames, digests,
  2774. * country codes and IP address patterns of ORs to
  2775. * consider as entry points. */
  2776. int StrictNodes; /**< Boolean: When none of our EntryNodes or ExitNodes
  2777. * are up, or we need to access a node in ExcludeNodes,
  2778. * do we just fail instead? */
  2779. routerset_t *ExcludeNodes;/**< Structure containing nicknames, digests,
  2780. * country codes and IP address patterns of ORs
  2781. * not to use in circuits. But see StrictNodes
  2782. * above. */
  2783. routerset_t *ExcludeExitNodes;/**< Structure containing nicknames, digests,
  2784. * country codes and IP address patterns of
  2785. * ORs not to consider as exits. */
  2786. /** Union of ExcludeNodes and ExcludeExitNodes */
  2787. routerset_t *ExcludeExitNodesUnion_;
  2788. int DisableAllSwap; /**< Boolean: Attempt to call mlockall() on our
  2789. * process for all current and future memory. */
  2790. /** List of "entry", "middle", "exit", "introduction", "rendezvous". */
  2791. smartlist_t *AllowInvalidNodes;
  2792. /** Bitmask; derived from AllowInvalidNodes. */
  2793. invalid_router_usage_t AllowInvalid_;
  2794. config_line_t *ExitPolicy; /**< Lists of exit policy components. */
  2795. int ExitPolicyRejectPrivate; /**< Should we not exit to local addresses? */
  2796. config_line_t *SocksPolicy; /**< Lists of socks policy components */
  2797. config_line_t *DirPolicy; /**< Lists of dir policy components */
  2798. /** Addresses to bind for listening for SOCKS connections. */
  2799. config_line_t *SocksListenAddress;
  2800. /** Addresses to bind for listening for transparent pf/netfilter
  2801. * connections. */
  2802. config_line_t *TransListenAddress;
  2803. /** Addresses to bind for listening for transparent natd connections */
  2804. config_line_t *NATDListenAddress;
  2805. /** Addresses to bind for listening for SOCKS connections. */
  2806. config_line_t *DNSListenAddress;
  2807. /** Addresses to bind for listening for OR connections. */
  2808. config_line_t *ORListenAddress;
  2809. /** Addresses to bind for listening for directory connections. */
  2810. config_line_t *DirListenAddress;
  2811. /** Addresses to bind for listening for control connections. */
  2812. config_line_t *ControlListenAddress;
  2813. /** Local address to bind outbound sockets */
  2814. config_line_t *OutboundBindAddress;
  2815. /** IPv4 address derived from OutboundBindAddress. */
  2816. tor_addr_t OutboundBindAddressIPv4_;
  2817. /** IPv6 address derived from OutboundBindAddress. */
  2818. tor_addr_t OutboundBindAddressIPv6_;
  2819. /** Directory server only: which versions of
  2820. * Tor should we tell users to run? */
  2821. config_line_t *RecommendedVersions;
  2822. config_line_t *RecommendedClientVersions;
  2823. config_line_t *RecommendedServerVersions;
  2824. /** Whether dirservers allow router descriptors with private IPs. */
  2825. int DirAllowPrivateAddresses;
  2826. /** Whether routers accept EXTEND cells to routers with private IPs. */
  2827. int ExtendAllowPrivateAddresses;
  2828. char *User; /**< Name of user to run Tor as. */
  2829. char *Group; /**< Name of group to run Tor as. */
  2830. config_line_t *ORPort_lines; /**< Ports to listen on for OR connections. */
  2831. /** Ports to listen on for SOCKS connections. */
  2832. config_line_t *SocksPort_lines;
  2833. /** Ports to listen on for transparent pf/netfilter connections. */
  2834. config_line_t *TransPort_lines;
  2835. config_line_t *NATDPort_lines; /**< Ports to listen on for transparent natd
  2836. * connections. */
  2837. config_line_t *ControlPort_lines; /**< Ports to listen on for control
  2838. * connections. */
  2839. config_line_t *ControlSocket; /**< List of Unix Domain Sockets to listen on
  2840. * for control connections. */
  2841. int ControlSocketsGroupWritable; /**< Boolean: Are control sockets g+rw? */
  2842. /** Ports to listen on for directory connections. */
  2843. config_line_t *DirPort_lines;
  2844. config_line_t *DNSPort_lines; /**< Ports to listen on for DNS requests. */
  2845. /** @name port booleans
  2846. *
  2847. * Derived booleans: True iff there is a non-listener port on an AF_INET or
  2848. * AF_INET6 address of the given type configured in one of the _lines
  2849. * options above.
  2850. *
  2851. * @{
  2852. */
  2853. unsigned int ORPort_set : 1;
  2854. unsigned int SocksPort_set : 1;
  2855. unsigned int TransPort_set : 1;
  2856. unsigned int NATDPort_set : 1;
  2857. unsigned int ControlPort_set : 1;
  2858. unsigned int DirPort_set : 1;
  2859. unsigned int DNSPort_set : 1;
  2860. /**@}*/
  2861. int AssumeReachable; /**< Whether to publish our descriptor regardless. */
  2862. int AuthoritativeDir; /**< Boolean: is this an authoritative directory? */
  2863. int V1AuthoritativeDir; /**< Boolean: is this an authoritative directory
  2864. * for version 1 directories? */
  2865. int V2AuthoritativeDir; /**< Boolean: is this an authoritative directory
  2866. * for version 2 directories? */
  2867. int V3AuthoritativeDir; /**< Boolean: is this an authoritative directory
  2868. * for version 3 directories? */
  2869. int HSAuthoritativeDir; /**< Boolean: does this an authoritative directory
  2870. * handle hidden service requests? */
  2871. int NamingAuthoritativeDir; /**< Boolean: is this an authoritative directory
  2872. * that's willing to bind names? */
  2873. int VersioningAuthoritativeDir; /**< Boolean: is this an authoritative
  2874. * directory that's willing to recommend
  2875. * versions? */
  2876. int BridgeAuthoritativeDir; /**< Boolean: is this an authoritative directory
  2877. * that aggregates bridge descriptors? */
  2878. /** If set on a bridge authority, it will answer requests on its dirport
  2879. * for bridge statuses -- but only if the requests use this password. */
  2880. char *BridgePassword;
  2881. /** If BridgePassword is set, this is a SHA256 digest of the basic http
  2882. * authenticator for it. Used so we can do a time-independent comparison. */
  2883. char *BridgePassword_AuthDigest_;
  2884. int UseBridges; /**< Boolean: should we start all circuits with a bridge? */
  2885. config_line_t *Bridges; /**< List of bootstrap bridge addresses. */
  2886. config_line_t *ClientTransportPlugin; /**< List of client
  2887. transport plugins. */
  2888. config_line_t *ServerTransportPlugin; /**< List of client
  2889. transport plugins. */
  2890. /** List of TCP/IP addresses that transports should listen at. */
  2891. config_line_t *ServerTransportListenAddr;
  2892. int BridgeRelay; /**< Boolean: are we acting as a bridge relay? We make
  2893. * this explicit so we can change how we behave in the
  2894. * future. */
  2895. /** Boolean: if we know the bridge's digest, should we get new
  2896. * descriptors from the bridge authorities or from the bridge itself? */
  2897. int UpdateBridgesFromAuthority;
  2898. int AvoidDiskWrites; /**< Boolean: should we never cache things to disk?
  2899. * Not used yet. */
  2900. int ClientOnly; /**< Boolean: should we never evolve into a server role? */
  2901. /** To what authority types do we publish our descriptor? Choices are
  2902. * "v1", "v2", "v3", "bridge", or "". */
  2903. smartlist_t *PublishServerDescriptor;
  2904. /** A bitfield of authority types, derived from PublishServerDescriptor. */
  2905. dirinfo_type_t PublishServerDescriptor_;
  2906. /** Boolean: do we publish hidden service descriptors to the HS auths? */
  2907. int PublishHidServDescriptors;
  2908. int FetchServerDescriptors; /**< Do we fetch server descriptors as normal? */
  2909. int FetchHidServDescriptors; /**< and hidden service descriptors? */
  2910. int FetchV2Networkstatus; /**< Do we fetch v2 networkstatus documents when
  2911. * we don't need to? */
  2912. int HidServDirectoryV2; /**< Do we participate in the HS DHT? */
  2913. int VoteOnHidServDirectoriesV2; /**< As a directory authority, vote on
  2914. * assignment of the HSDir flag? */
  2915. int MinUptimeHidServDirectoryV2; /**< As directory authority, accept hidden
  2916. * service directories after what time? */
  2917. int FetchUselessDescriptors; /**< Do we fetch non-running descriptors too? */
  2918. int AllDirActionsPrivate; /**< Should every directory action be sent
  2919. * through a Tor circuit? */
  2920. /** Run in 'tor2web mode'? (I.e. only make client connections to hidden
  2921. * services, and use a single hop for all hidden-service-related
  2922. * circuits.) */
  2923. int Tor2webMode;
  2924. /** Close hidden service client circuits immediately when they reach
  2925. * the normal circuit-build timeout, even if they have already sent
  2926. * an INTRODUCE1 cell on its way to the service. */
  2927. int CloseHSClientCircuitsImmediatelyOnTimeout;
  2928. /** Close hidden-service-side rendezvous circuits immediately when
  2929. * they reach the normal circuit-build timeout. */
  2930. int CloseHSServiceRendCircuitsImmediatelyOnTimeout;
  2931. int ConnLimit; /**< Demanded minimum number of simultaneous connections. */
  2932. int ConnLimit_; /**< Maximum allowed number of simultaneous connections. */
  2933. int RunAsDaemon; /**< If true, run in the background. (Unix only) */
  2934. int FascistFirewall; /**< Whether to prefer ORs reachable on open ports. */
  2935. smartlist_t *FirewallPorts; /**< Which ports our firewall allows
  2936. * (strings). */
  2937. config_line_t *ReachableAddresses; /**< IP:ports our firewall allows. */
  2938. config_line_t *ReachableORAddresses; /**< IP:ports for OR conns. */
  2939. config_line_t *ReachableDirAddresses; /**< IP:ports for Dir conns. */
  2940. int ConstrainedSockets; /**< Shrink xmit and recv socket buffers. */
  2941. uint64_t ConstrainedSockSize; /**< Size of constrained buffers. */
  2942. /** Whether we should drop exit streams from Tors that we don't know are
  2943. * relays. One of "0" (never refuse), "1" (always refuse), or "-1" (do
  2944. * what the consensus says, defaulting to 'refuse' if the consensus says
  2945. * nothing). */
  2946. int RefuseUnknownExits;
  2947. /** Application ports that require all nodes in circ to have sufficient
  2948. * uptime. */
  2949. smartlist_t *LongLivedPorts;
  2950. /** Application ports that are likely to be unencrypted and
  2951. * unauthenticated; we reject requests for them to prevent the
  2952. * user from screwing up and leaking plaintext secrets to an
  2953. * observer somewhere on the Internet. */
  2954. smartlist_t *RejectPlaintextPorts;
  2955. /** Related to RejectPlaintextPorts above, except this config option
  2956. * controls whether we warn (in the log and via a controller status
  2957. * event) every time a risky connection is attempted. */
  2958. smartlist_t *WarnPlaintextPorts;
  2959. /** Should we try to reuse the same exit node for a given host */
  2960. smartlist_t *TrackHostExits;
  2961. int TrackHostExitsExpire; /**< Number of seconds until we expire an
  2962. * addressmap */
  2963. config_line_t *AddressMap; /**< List of address map directives. */
  2964. int AutomapHostsOnResolve; /**< If true, when we get a resolve request for a
  2965. * hostname ending with one of the suffixes in
  2966. * <b>AutomapHostsSuffixes</b>, map it to a
  2967. * virtual address. */
  2968. smartlist_t *AutomapHostsSuffixes; /**< List of suffixes for
  2969. * <b>AutomapHostsOnResolve</b>. */
  2970. int RendPostPeriod; /**< How often do we post each rendezvous service
  2971. * descriptor? Remember to publish them independently. */
  2972. int KeepalivePeriod; /**< How often do we send padding cells to keep
  2973. * connections alive? */
  2974. int SocksTimeout; /**< How long do we let a socks connection wait
  2975. * unattached before we fail it? */
  2976. int LearnCircuitBuildTimeout; /**< If non-zero, we attempt to learn a value
  2977. * for CircuitBuildTimeout based on timeout
  2978. * history */
  2979. int CircuitBuildTimeout; /**< Cull non-open circuits that were born at
  2980. * least this many seconds ago. Used until
  2981. * adaptive algorithm learns a new value. */
  2982. int CircuitIdleTimeout; /**< Cull open clean circuits that were born
  2983. * at least this many seconds ago. */
  2984. int CircuitStreamTimeout; /**< If non-zero, detach streams from circuits
  2985. * and try a new circuit if the stream has been
  2986. * waiting for this many seconds. If zero, use
  2987. * our default internal timeout schedule. */
  2988. int MaxOnionsPending; /**< How many circuit CREATE requests do we allow
  2989. * to wait simultaneously before we start dropping
  2990. * them? */
  2991. int NewCircuitPeriod; /**< How long do we use a circuit before building
  2992. * a new one? */
  2993. int MaxCircuitDirtiness; /**< Never use circs that were first used more than
  2994. this interval ago. */
  2995. uint64_t BandwidthRate; /**< How much bandwidth, on average, are we willing
  2996. * to use in a second? */
  2997. uint64_t BandwidthBurst; /**< How much bandwidth, at maximum, are we willing
  2998. * to use in a second? */
  2999. uint64_t MaxAdvertisedBandwidth; /**< How much bandwidth are we willing to
  3000. * tell people we have? */
  3001. uint64_t RelayBandwidthRate; /**< How much bandwidth, on average, are we
  3002. * willing to use for all relayed conns? */
  3003. uint64_t RelayBandwidthBurst; /**< How much bandwidth, at maximum, will we
  3004. * use in a second for all relayed conns? */
  3005. uint64_t PerConnBWRate; /**< Long-term bw on a single TLS conn, if set. */
  3006. uint64_t PerConnBWBurst; /**< Allowed burst on a single TLS conn, if set. */
  3007. int NumCPUs; /**< How many CPUs should we try to use? */
  3008. //int RunTesting; /**< If true, create testing circuits to measure how well the
  3009. // * other ORs are running. */
  3010. config_line_t *RendConfigLines; /**< List of configuration lines
  3011. * for rendezvous services. */
  3012. config_line_t *HidServAuth; /**< List of configuration lines for client-side
  3013. * authorizations for hidden services */
  3014. char *ContactInfo; /**< Contact info to be published in the directory. */
  3015. int HeartbeatPeriod; /**< Log heartbeat messages after this many seconds
  3016. * have passed. */
  3017. char *HTTPProxy; /**< hostname[:port] to use as http proxy, if any. */
  3018. tor_addr_t HTTPProxyAddr; /**< Parsed IPv4 addr for http proxy, if any. */
  3019. uint16_t HTTPProxyPort; /**< Parsed port for http proxy, if any. */
  3020. char *HTTPProxyAuthenticator; /**< username:password string, if any. */
  3021. char *HTTPSProxy; /**< hostname[:port] to use as https proxy, if any. */
  3022. tor_addr_t HTTPSProxyAddr; /**< Parsed addr for https proxy, if any. */
  3023. uint16_t HTTPSProxyPort; /**< Parsed port for https proxy, if any. */
  3024. char *HTTPSProxyAuthenticator; /**< username:password string, if any. */
  3025. char *Socks4Proxy; /**< hostname:port to use as a SOCKS4 proxy, if any. */
  3026. tor_addr_t Socks4ProxyAddr; /**< Derived from Socks4Proxy. */
  3027. uint16_t Socks4ProxyPort; /**< Derived from Socks4Proxy. */
  3028. char *Socks5Proxy; /**< hostname:port to use as a SOCKS5 proxy, if any. */
  3029. tor_addr_t Socks5ProxyAddr; /**< Derived from Sock5Proxy. */
  3030. uint16_t Socks5ProxyPort; /**< Derived from Socks5Proxy. */
  3031. char *Socks5ProxyUsername; /**< Username for SOCKS5 authentication, if any */
  3032. char *Socks5ProxyPassword; /**< Password for SOCKS5 authentication, if any */
  3033. /** List of configuration lines for replacement directory authorities.
  3034. * If you just want to replace one class of authority at a time,
  3035. * use the "Alternate*Authority" options below instead. */
  3036. config_line_t *DirServers;
  3037. /** If set, use these main (currently v3) directory authorities and
  3038. * not the default ones. */
  3039. config_line_t *AlternateDirAuthority;
  3040. /** If set, use these bridge authorities and not the default one. */
  3041. config_line_t *AlternateBridgeAuthority;
  3042. /** If set, use these HS authorities and not the default ones. */
  3043. config_line_t *AlternateHSAuthority;
  3044. char *MyFamily; /**< Declared family for this OR. */
  3045. config_line_t *NodeFamilies; /**< List of config lines for
  3046. * node families */
  3047. smartlist_t *NodeFamilySets; /**< List of parsed NodeFamilies values. */
  3048. config_line_t *AuthDirBadDir; /**< Address policy for descriptors to
  3049. * mark as bad dir mirrors. */
  3050. config_line_t *AuthDirBadExit; /**< Address policy for descriptors to
  3051. * mark as bad exits. */
  3052. config_line_t *AuthDirReject; /**< Address policy for descriptors to
  3053. * reject. */
  3054. config_line_t *AuthDirInvalid; /**< Address policy for descriptors to
  3055. * never mark as valid. */
  3056. /** @name AuthDir...CC
  3057. *
  3058. * Lists of country codes to mark as BadDir, BadExit, or Invalid, or to
  3059. * reject entirely.
  3060. *
  3061. * @{
  3062. */
  3063. smartlist_t *AuthDirBadDirCCs;
  3064. smartlist_t *AuthDirBadExitCCs;
  3065. smartlist_t *AuthDirInvalidCCs;
  3066. smartlist_t *AuthDirRejectCCs;
  3067. /**@}*/
  3068. int AuthDirListBadDirs; /**< True iff we should list bad dirs,
  3069. * and vote for all other dir mirrors as good. */
  3070. int AuthDirListBadExits; /**< True iff we should list bad exits,
  3071. * and vote for all other exits as good. */
  3072. int AuthDirRejectUnlisted; /**< Boolean: do we reject all routers that
  3073. * aren't named in our fingerprint file? */
  3074. int AuthDirMaxServersPerAddr; /**< Do not permit more than this
  3075. * number of servers per IP address. */
  3076. int AuthDirMaxServersPerAuthAddr; /**< Do not permit more than this
  3077. * number of servers per IP address shared
  3078. * with an authority. */
  3079. int AuthDirHasIPv6Connectivity; /**< Boolean: are we on IPv6? */
  3080. /** If non-zero, always vote the Fast flag for any relay advertising
  3081. * this amount of capacity or more. */
  3082. uint64_t AuthDirFastGuarantee;
  3083. /** If non-zero, this advertised capacity or more is always sufficient
  3084. * to satisfy the bandwidth requirement for the Guard flag. */
  3085. uint64_t AuthDirGuardBWGuarantee;
  3086. char *AccountingStart; /**< How long is the accounting interval, and when
  3087. * does it start? */
  3088. uint64_t AccountingMax; /**< How many bytes do we allow per accounting
  3089. * interval before hibernation? 0 for "never
  3090. * hibernate." */
  3091. /** Base64-encoded hash of accepted passwords for the control system. */
  3092. config_line_t *HashedControlPassword;
  3093. /** As HashedControlPassword, but not saved. */
  3094. config_line_t *HashedControlSessionPassword;
  3095. int CookieAuthentication; /**< Boolean: do we enable cookie-based auth for
  3096. * the control system? */
  3097. char *CookieAuthFile; /**< Location of a cookie authentication file. */
  3098. int CookieAuthFileGroupReadable; /**< Boolean: Is the CookieAuthFile g+r? */
  3099. int LeaveStreamsUnattached; /**< Boolean: Does Tor attach new streams to
  3100. * circuits itself (0), or does it expect a controller
  3101. * to cope? (1) */
  3102. int DisablePredictedCircuits; /**< Boolean: does Tor preemptively
  3103. * make circuits in the background (0),
  3104. * or not (1)? */
  3105. /** Process specifier for a controller that ‘owns’ this Tor
  3106. * instance. Tor will terminate if its owning controller does. */
  3107. char *OwningControllerProcess;
  3108. int ShutdownWaitLength; /**< When we get a SIGINT and we're a server, how
  3109. * long do we wait before exiting? */
  3110. char *SafeLogging; /**< Contains "relay", "1", "0" (meaning no scrubbing). */
  3111. /* Derived from SafeLogging */
  3112. enum {
  3113. SAFELOG_SCRUB_ALL, SAFELOG_SCRUB_RELAY, SAFELOG_SCRUB_NONE
  3114. } SafeLogging_;
  3115. int SafeSocks; /**< Boolean: should we outright refuse application
  3116. * connections that use socks4 or socks5-with-local-dns? */
  3117. #define LOG_PROTOCOL_WARN (get_options()->ProtocolWarnings ? \
  3118. LOG_WARN : LOG_INFO)
  3119. int ProtocolWarnings; /**< Boolean: when other parties screw up the Tor
  3120. * protocol, is it a warn or an info in our logs? */
  3121. int TestSocks; /**< Boolean: when we get a socks connection, do we loudly
  3122. * log whether it was DNS-leaking or not? */
  3123. int HardwareAccel; /**< Boolean: Should we enable OpenSSL hardware
  3124. * acceleration where available? */
  3125. /** Token Bucket Refill resolution in milliseconds. */
  3126. int TokenBucketRefillInterval;
  3127. char *AccelName; /**< Optional hardware acceleration engine name. */
  3128. char *AccelDir; /**< Optional hardware acceleration engine search dir. */
  3129. int UseEntryGuards; /**< Boolean: Do we try to enter from a smallish number
  3130. * of fixed nodes? */
  3131. int NumEntryGuards; /**< How many entry guards do we try to establish? */
  3132. int RephistTrackTime; /**< How many seconds do we keep rephist info? */
  3133. int FastFirstHopPK; /**< If Tor believes it is safe, should we save a third
  3134. * of our PK time by sending CREATE_FAST cells? */
  3135. /** Should we always fetch our dir info on the mirror schedule (which
  3136. * means directly from the authorities) no matter our other config? */
  3137. int FetchDirInfoEarly;
  3138. /** Should we fetch our dir info at the start of the consensus period? */
  3139. int FetchDirInfoExtraEarly;
  3140. char *VirtualAddrNetwork; /**< Address and mask to hand out for virtual
  3141. * MAPADDRESS requests. */
  3142. int ServerDNSSearchDomains; /**< Boolean: If set, we don't force exit
  3143. * addresses to be FQDNs, but rather search for them in
  3144. * the local domains. */
  3145. int ServerDNSDetectHijacking; /**< Boolean: If true, check for DNS failure
  3146. * hijacking. */
  3147. int ServerDNSRandomizeCase; /**< Boolean: Use the 0x20-hack to prevent
  3148. * DNS poisoning attacks. */
  3149. char *ServerDNSResolvConfFile; /**< If provided, we configure our internal
  3150. * resolver from the file here rather than from
  3151. * /etc/resolv.conf (Unix) or the registry (Windows). */
  3152. char *DirPortFrontPage; /**< This is a full path to a file with an html
  3153. disclaimer. This allows a server administrator to show
  3154. that they're running Tor and anyone visiting their server
  3155. will know this without any specialized knowledge. */
  3156. int DisableDebuggerAttachment; /**< Currently Linux only specific attempt to
  3157. disable ptrace; needs BSD testing. */
  3158. /** Boolean: if set, we start even if our resolv.conf file is missing
  3159. * or broken. */
  3160. int ServerDNSAllowBrokenConfig;
  3161. /** Boolean: if set, then even connections to private addresses will get
  3162. * rate-limited. */
  3163. int CountPrivateBandwidth;
  3164. smartlist_t *ServerDNSTestAddresses; /**< A list of addresses that definitely
  3165. * should be resolvable. Used for
  3166. * testing our DNS server. */
  3167. int EnforceDistinctSubnets; /**< If true, don't allow multiple routers in the
  3168. * same network zone in the same circuit. */
  3169. int TunnelDirConns; /**< If true, use BEGIN_DIR rather than BEGIN when
  3170. * possible. */
  3171. int PreferTunneledDirConns; /**< If true, avoid dirservers that don't
  3172. * support BEGIN_DIR, when possible. */
  3173. int PortForwarding; /**< If true, use NAT-PMP or UPnP to automatically
  3174. * forward the DirPort and ORPort on the NAT device */
  3175. char *PortForwardingHelper; /** < Filename or full path of the port
  3176. forwarding helper executable */
  3177. int AllowNonRFC953Hostnames; /**< If true, we allow connections to hostnames
  3178. * with weird characters. */
  3179. /** If true, we try resolving hostnames with weird characters. */
  3180. int ServerDNSAllowNonRFC953Hostnames;
  3181. /** If true, we try to download extra-info documents (and we serve them,
  3182. * if we are a cache). For authorities, this is always true. */
  3183. int DownloadExtraInfo;
  3184. /** If true, and we are acting as a relay, allow exit circuits even when
  3185. * we are the first hop of a circuit. */
  3186. int AllowSingleHopExits;
  3187. /** If true, don't allow relays with AllowSingleHopExits=1 to be used in
  3188. * circuits that we build. */
  3189. int ExcludeSingleHopRelays;
  3190. /** If true, and the controller tells us to use a one-hop circuit, and the
  3191. * exit allows it, we use it. */
  3192. int AllowSingleHopCircuits;
  3193. /** If true, we convert "www.google.com.foo.exit" addresses on the
  3194. * socks/trans/natd ports into "www.google.com" addresses that
  3195. * exit from the node "foo". Disabled by default since attacking
  3196. * websites and exit relays can use it to manipulate your path
  3197. * selection. */
  3198. int AllowDotExit;
  3199. /** If true, we will warn if a user gives us only an IP address
  3200. * instead of a hostname. */
  3201. int WarnUnsafeSocks;
  3202. /** If true, the user wants us to collect statistics on clients
  3203. * requesting network statuses from us as directory. */
  3204. int DirReqStatistics;
  3205. /** If true, the user wants us to collect statistics on port usage. */
  3206. int ExitPortStatistics;
  3207. /** If true, the user wants us to collect connection statistics. */
  3208. int ConnDirectionStatistics;
  3209. /** If true, the user wants us to collect cell statistics. */
  3210. int CellStatistics;
  3211. /** If true, the user wants us to collect statistics as entry node. */
  3212. int EntryStatistics;
  3213. /** If true, include statistics file contents in extra-info documents. */
  3214. int ExtraInfoStatistics;
  3215. /** If true, do not believe anybody who tells us that a domain resolves
  3216. * to an internal address, or that an internal address has a PTR mapping.
  3217. * Helps avoid some cross-site attacks. */
  3218. int ClientDNSRejectInternalAddresses;
  3219. /** If true, do not accept any requests to connect to internal addresses
  3220. * over randomly chosen exits. */
  3221. int ClientRejectInternalAddresses;
  3222. /** If true, clients may connect over IPv6. XXX we don't really
  3223. enforce this -- clients _may_ set up outgoing IPv6 connections
  3224. even when this option is not set. */
  3225. int ClientUseIPv6;
  3226. /** If true, prefer an IPv6 OR port over an IPv4 one. */
  3227. int ClientPreferIPv6ORPort;
  3228. /** The length of time that we think a consensus should be fresh. */
  3229. int V3AuthVotingInterval;
  3230. /** The length of time we think it will take to distribute votes. */
  3231. int V3AuthVoteDelay;
  3232. /** The length of time we think it will take to distribute signatures. */
  3233. int V3AuthDistDelay;
  3234. /** The number of intervals we think a consensus should be valid. */
  3235. int V3AuthNIntervalsValid;
  3236. /** Should advertise and sign consensuses with a legacy key, for key
  3237. * migration purposes? */
  3238. int V3AuthUseLegacyKey;
  3239. /** Location of bandwidth measurement file */
  3240. char *V3BandwidthsFile;
  3241. /** Authority only: key=value pairs that we add to our networkstatus
  3242. * consensus vote on the 'params' line. */
  3243. char *ConsensusParams;
  3244. /** The length of time that we think an initial consensus should be fresh.
  3245. * Only altered on testing networks. */
  3246. int TestingV3AuthInitialVotingInterval;
  3247. /** The length of time we think it will take to distribute initial votes.
  3248. * Only altered on testing networks. */
  3249. int TestingV3AuthInitialVoteDelay;
  3250. /** The length of time we think it will take to distribute initial
  3251. * signatures. Only altered on testing networks.*/
  3252. int TestingV3AuthInitialDistDelay;
  3253. /** If an authority has been around for less than this amount of time, it
  3254. * does not believe its reachability information is accurate. Only
  3255. * altered on testing networks. */
  3256. int TestingAuthDirTimeToLearnReachability;
  3257. /** Clients don't download any descriptor this recent, since it will
  3258. * probably not have propagated to enough caches. Only altered on testing
  3259. * networks. */
  3260. int TestingEstimatedDescriptorPropagationTime;
  3261. /** If true, we take part in a testing network. Change the defaults of a
  3262. * couple of other configuration options and allow to change the values
  3263. * of certain configuration options. */
  3264. int TestingTorNetwork;
  3265. /** File to check for a consensus networkstatus, if we don't have one
  3266. * cached. */
  3267. char *FallbackNetworkstatusFile;
  3268. /** If true, and we have GeoIP data, and we're a bridge, keep a per-country
  3269. * count of how many client addresses have contacted us so that we can help
  3270. * the bridge authority guess which countries have blocked access to us. */
  3271. int BridgeRecordUsageByCountry;
  3272. /** Optionally, IPv4 and IPv6 GeoIP data. */
  3273. char *GeoIPFile;
  3274. char *GeoIPv6File;
  3275. /** If true, SIGHUP should reload the torrc. Sometimes controllers want
  3276. * to make this false. */
  3277. int ReloadTorrcOnSIGHUP;
  3278. /* The main parameter for picking circuits within a connection.
  3279. *
  3280. * If this value is positive, when picking a cell to relay on a connection,
  3281. * we always relay from the circuit whose weighted cell count is lowest.
  3282. * Cells are weighted exponentially such that if one cell is sent
  3283. * 'CircuitPriorityHalflife' seconds before another, it counts for half as
  3284. * much.
  3285. *
  3286. * If this value is zero, we're disabling the cell-EWMA algorithm.
  3287. *
  3288. * If this value is negative, we're using the default approach
  3289. * according to either Tor or a parameter set in the consensus.
  3290. */
  3291. double CircuitPriorityHalflife;
  3292. /** If true, do not enable IOCP on windows with bufferevents, even if
  3293. * we think we could. */
  3294. int DisableIOCP;
  3295. /** For testing only: will go away eventually. */
  3296. int UseFilteringSSLBufferevents;
  3297. /** Set to true if the TestingTorNetwork configuration option is set.
  3298. * This is used so that options_validate() has a chance to realize that
  3299. * the defaults have changed. */
  3300. int UsingTestNetworkDefaults_;
  3301. /** If 1, we try to use microdescriptors to build circuits. If 0, we don't.
  3302. * If -1, Tor decides. */
  3303. int UseMicrodescriptors;
  3304. /** File where we should write the ControlPort. */
  3305. char *ControlPortWriteToFile;
  3306. /** Should that file be group-readable? */
  3307. int ControlPortFileGroupReadable;
  3308. #define MAX_MAX_CLIENT_CIRCUITS_PENDING 1024
  3309. /** Maximum number of non-open general-purpose origin circuits to allow at
  3310. * once. */
  3311. int MaxClientCircuitsPending;
  3312. /** If 1, we always send optimistic data when it's supported. If 0, we
  3313. * never use it. If -1, we do what the consensus says. */
  3314. int OptimisticData;
  3315. /** If 1, and we are using IOCP, we set the kernel socket SNDBUF and RCVBUF
  3316. * to 0 to try to save kernel memory and avoid the dread "Out of buffers"
  3317. * issue. */
  3318. int UserspaceIOCPBuffers;
  3319. /** If 1, we accept and launch no external network connections, except on
  3320. * control ports. */
  3321. int DisableNetwork;
  3322. /**
  3323. * Parameters for path-bias detection.
  3324. * @{
  3325. */
  3326. int PathBiasCircThreshold;
  3327. double PathBiasNoticeRate;
  3328. double PathBiasDisableRate;
  3329. int PathBiasScaleThreshold;
  3330. int PathBiasScaleFactor;
  3331. /** @} */
  3332. int IPv6Exit; /**< Do we support exiting to IPv6 addresses? */
  3333. } or_options_t;
  3334. /** Persistent state for an onion router, as saved to disk. */
  3335. typedef struct {
  3336. uint32_t magic_;
  3337. /** The time at which we next plan to write the state to the disk. Equal to
  3338. * TIME_MAX if there are no savable changes, 0 if there are changes that
  3339. * should be saved right away. */
  3340. time_t next_write;
  3341. /** When was the state last written to disk? */
  3342. time_t LastWritten;
  3343. /** Fields for accounting bandwidth use. */
  3344. time_t AccountingIntervalStart;
  3345. uint64_t AccountingBytesReadInInterval;
  3346. uint64_t AccountingBytesWrittenInInterval;
  3347. int AccountingSecondsActive;
  3348. int AccountingSecondsToReachSoftLimit;
  3349. time_t AccountingSoftLimitHitAt;
  3350. uint64_t AccountingBytesAtSoftLimit;
  3351. uint64_t AccountingExpectedUsage;
  3352. /** A list of Entry Guard-related configuration lines. */
  3353. config_line_t *EntryGuards;
  3354. config_line_t *TransportProxies;
  3355. /** These fields hold information on the history of bandwidth usage for
  3356. * servers. The "Ends" fields hold the time when we last updated the
  3357. * bandwidth usage. The "Interval" fields hold the granularity, in seconds,
  3358. * of the entries of Values. The "Values" lists hold decimal string
  3359. * representations of the number of bytes read or written in each
  3360. * interval. The "Maxima" list holds decimal strings describing the highest
  3361. * rate achieved during the interval.
  3362. */
  3363. time_t BWHistoryReadEnds;
  3364. int BWHistoryReadInterval;
  3365. smartlist_t *BWHistoryReadValues;
  3366. smartlist_t *BWHistoryReadMaxima;
  3367. time_t BWHistoryWriteEnds;
  3368. int BWHistoryWriteInterval;
  3369. smartlist_t *BWHistoryWriteValues;
  3370. smartlist_t *BWHistoryWriteMaxima;
  3371. time_t BWHistoryDirReadEnds;
  3372. int BWHistoryDirReadInterval;
  3373. smartlist_t *BWHistoryDirReadValues;
  3374. smartlist_t *BWHistoryDirReadMaxima;
  3375. time_t BWHistoryDirWriteEnds;
  3376. int BWHistoryDirWriteInterval;
  3377. smartlist_t *BWHistoryDirWriteValues;
  3378. smartlist_t *BWHistoryDirWriteMaxima;
  3379. /** Build time histogram */
  3380. config_line_t * BuildtimeHistogram;
  3381. unsigned int TotalBuildTimes;
  3382. unsigned int CircuitBuildAbandonedCount;
  3383. /** What version of Tor wrote this state file? */
  3384. char *TorVersion;
  3385. /** Holds any unrecognized values we found in the state file, in the order
  3386. * in which we found them. */
  3387. config_line_t *ExtraLines;
  3388. /** When did we last rotate our onion key? "0" for 'no idea'. */
  3389. time_t LastRotatedOnionKey;
  3390. } or_state_t;
  3391. /** Change the next_write time of <b>state</b> to <b>when</b>, unless the
  3392. * state is already scheduled to be written to disk earlier than <b>when</b>.
  3393. */
  3394. static INLINE void or_state_mark_dirty(or_state_t *state, time_t when)
  3395. {
  3396. if (state->next_write > when)
  3397. state->next_write = when;
  3398. }
  3399. #define MAX_SOCKS_REPLY_LEN 1024
  3400. #define MAX_SOCKS_ADDR_LEN 256
  3401. #define SOCKS_NO_AUTH 0x00
  3402. #define SOCKS_USER_PASS 0x02
  3403. /** Please open a TCP connection to this addr:port. */
  3404. #define SOCKS_COMMAND_CONNECT 0x01
  3405. /** Please turn this FQDN into an IP address, privately. */
  3406. #define SOCKS_COMMAND_RESOLVE 0xF0
  3407. /** Please turn this IP address into an FQDN, privately. */
  3408. #define SOCKS_COMMAND_RESOLVE_PTR 0xF1
  3409. #define SOCKS_COMMAND_IS_CONNECT(c) ((c)==SOCKS_COMMAND_CONNECT)
  3410. #define SOCKS_COMMAND_IS_RESOLVE(c) ((c)==SOCKS_COMMAND_RESOLVE || \
  3411. (c)==SOCKS_COMMAND_RESOLVE_PTR)
  3412. /** State of a SOCKS request from a user to an OP. Also used to encode other
  3413. * information for non-socks user request (such as those on TransPort and
  3414. * DNSPort) */
  3415. struct socks_request_t {
  3416. /** Which version of SOCKS did the client use? One of "0, 4, 5" -- where
  3417. * 0 means that no socks handshake ever took place, and this is just a
  3418. * stub connection (e.g. see connection_ap_make_link()). */
  3419. uint8_t socks_version;
  3420. /** If using socks5 authentication, which authentication type did we
  3421. * negotiate? currently we support 0 (no authentication) and 2
  3422. * (username/password). */
  3423. uint8_t auth_type;
  3424. /** What is this stream's goal? One of the SOCKS_COMMAND_* values */
  3425. uint8_t command;
  3426. /** Which kind of listener created this stream? */
  3427. uint8_t listener_type;
  3428. size_t replylen; /**< Length of <b>reply</b>. */
  3429. uint8_t reply[MAX_SOCKS_REPLY_LEN]; /**< Write an entry into this string if
  3430. * we want to specify our own socks reply,
  3431. * rather than using the default socks4 or
  3432. * socks5 socks reply. We use this for the
  3433. * two-stage socks5 handshake.
  3434. */
  3435. char address[MAX_SOCKS_ADDR_LEN]; /**< What address did the client ask to
  3436. connect to/resolve? */
  3437. uint16_t port; /**< What port did the client ask to connect to? */
  3438. unsigned int has_finished : 1; /**< Has the SOCKS handshake finished? Used to
  3439. * make sure we send back a socks reply for
  3440. * every connection. */
  3441. unsigned int got_auth : 1; /**< Have we received any authentication data? */
  3442. /** Number of bytes in username; 0 if username is NULL */
  3443. size_t usernamelen;
  3444. /** Number of bytes in password; 0 if password is NULL */
  3445. uint8_t passwordlen;
  3446. /** The negotiated username value if any (for socks5), or the entire
  3447. * authentication string (for socks4). This value is NOT nul-terminated;
  3448. * see usernamelen for its length. */
  3449. char *username;
  3450. /** The negotiated password value if any (for socks5). This value is NOT
  3451. * nul-terminated; see passwordlen for its length. */
  3452. char *password;
  3453. };
  3454. /********************************* circuitbuild.c **********************/
  3455. /** How many hops does a general-purpose circuit have by default? */
  3456. #define DEFAULT_ROUTE_LEN 3
  3457. /* Circuit Build Timeout "public" structures. */
  3458. /** Precision multiplier for the Bw weights */
  3459. #define BW_WEIGHT_SCALE 10000
  3460. #define BW_MIN_WEIGHT_SCALE 1
  3461. #define BW_MAX_WEIGHT_SCALE INT32_MAX
  3462. /** Total size of the circuit timeout history to accumulate.
  3463. * 1000 is approx 2.5 days worth of continual-use circuits. */
  3464. #define CBT_NCIRCUITS_TO_OBSERVE 1000
  3465. /** Width of the histogram bins in milliseconds */
  3466. #define CBT_BIN_WIDTH ((build_time_t)50)
  3467. /** Number of modes to use in the weighted-avg computation of Xm */
  3468. #define CBT_DEFAULT_NUM_XM_MODES 3
  3469. #define CBT_MIN_NUM_XM_MODES 1
  3470. #define CBT_MAX_NUM_XM_MODES 20
  3471. /** A build_time_t is milliseconds */
  3472. typedef uint32_t build_time_t;
  3473. /**
  3474. * CBT_BUILD_ABANDONED is our flag value to represent a force-closed
  3475. * circuit (Aka a 'right-censored' pareto value).
  3476. */
  3477. #define CBT_BUILD_ABANDONED ((build_time_t)(INT32_MAX-1))
  3478. #define CBT_BUILD_TIME_MAX ((build_time_t)(INT32_MAX))
  3479. /** Save state every 10 circuits */
  3480. #define CBT_SAVE_STATE_EVERY 10
  3481. /* Circuit build times consensus parameters */
  3482. /**
  3483. * How long to wait before actually closing circuits that take too long to
  3484. * build in terms of CDF quantile.
  3485. */
  3486. #define CBT_DEFAULT_CLOSE_QUANTILE 95
  3487. #define CBT_MIN_CLOSE_QUANTILE CBT_MIN_QUANTILE_CUTOFF
  3488. #define CBT_MAX_CLOSE_QUANTILE CBT_MAX_QUANTILE_CUTOFF
  3489. /**
  3490. * How many circuits count as recent when considering if the
  3491. * connection has gone gimpy or changed.
  3492. */
  3493. #define CBT_DEFAULT_RECENT_CIRCUITS 20
  3494. #define CBT_MIN_RECENT_CIRCUITS 3
  3495. #define CBT_MAX_RECENT_CIRCUITS 1000
  3496. /**
  3497. * Maximum count of timeouts that finish the first hop in the past
  3498. * RECENT_CIRCUITS before calculating a new timeout.
  3499. *
  3500. * This tells us whether to abandon timeout history and set
  3501. * the timeout back to whatever circuit_build_times_get_initial_timeout()
  3502. * gives us.
  3503. */
  3504. #define CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT (CBT_DEFAULT_RECENT_CIRCUITS*9/10)
  3505. #define CBT_MIN_MAX_RECENT_TIMEOUT_COUNT 3
  3506. #define CBT_MAX_MAX_RECENT_TIMEOUT_COUNT 10000
  3507. /** Minimum circuits before estimating a timeout */
  3508. #define CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE 100
  3509. #define CBT_MIN_MIN_CIRCUITS_TO_OBSERVE 1
  3510. #define CBT_MAX_MIN_CIRCUITS_TO_OBSERVE 10000
  3511. /** Cutoff percentile on the CDF for our timeout estimation. */
  3512. #define CBT_DEFAULT_QUANTILE_CUTOFF 80
  3513. #define CBT_MIN_QUANTILE_CUTOFF 10
  3514. #define CBT_MAX_QUANTILE_CUTOFF 99
  3515. double circuit_build_times_quantile_cutoff(void);
  3516. /** How often in seconds should we build a test circuit */
  3517. #define CBT_DEFAULT_TEST_FREQUENCY 60
  3518. #define CBT_MIN_TEST_FREQUENCY 1
  3519. #define CBT_MAX_TEST_FREQUENCY INT32_MAX
  3520. /** Lowest allowable value for CircuitBuildTimeout in milliseconds */
  3521. #define CBT_DEFAULT_TIMEOUT_MIN_VALUE (1500)
  3522. #define CBT_MIN_TIMEOUT_MIN_VALUE 500
  3523. #define CBT_MAX_TIMEOUT_MIN_VALUE INT32_MAX
  3524. /** Initial circuit build timeout in milliseconds */
  3525. #define CBT_DEFAULT_TIMEOUT_INITIAL_VALUE (60*1000)
  3526. #define CBT_MIN_TIMEOUT_INITIAL_VALUE CBT_MIN_TIMEOUT_MIN_VALUE
  3527. #define CBT_MAX_TIMEOUT_INITIAL_VALUE INT32_MAX
  3528. int32_t circuit_build_times_initial_timeout(void);
  3529. #if CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT < CBT_MIN_MAX_RECENT_TIMEOUT_COUNT
  3530. #error "RECENT_CIRCUITS is set too low."
  3531. #endif
  3532. /** Information about the state of our local network connection */
  3533. typedef struct {
  3534. /** The timestamp we last completed a TLS handshake or received a cell */
  3535. time_t network_last_live;
  3536. /** If the network is not live, how many timeouts has this caused? */
  3537. int nonlive_timeouts;
  3538. /** Circular array of circuits that have made it to the first hop. Slot is
  3539. * 1 if circuit timed out, 0 if circuit succeeded */
  3540. int8_t *timeouts_after_firsthop;
  3541. /** Number of elements allocated for the above array */
  3542. int num_recent_circs;
  3543. /** Index into circular array. */
  3544. int after_firsthop_idx;
  3545. } network_liveness_t;
  3546. /** Structure for circuit build times history */
  3547. typedef struct {
  3548. /** The circular array of recorded build times in milliseconds */
  3549. build_time_t circuit_build_times[CBT_NCIRCUITS_TO_OBSERVE];
  3550. /** Current index in the circuit_build_times circular array */
  3551. int build_times_idx;
  3552. /** Total number of build times accumulated. Max CBT_NCIRCUITS_TO_OBSERVE */
  3553. int total_build_times;
  3554. /** Information about the state of our local network connection */
  3555. network_liveness_t liveness;
  3556. /** Last time we built a circuit. Used to decide to build new test circs */
  3557. time_t last_circ_at;
  3558. /** "Minimum" value of our pareto distribution (actually mode) */
  3559. build_time_t Xm;
  3560. /** alpha exponent for pareto dist. */
  3561. double alpha;
  3562. /** Have we computed a timeout? */
  3563. int have_computed_timeout;
  3564. /** The exact value for that timeout in milliseconds. Stored as a double
  3565. * to maintain precision from calculations to and from quantile value. */
  3566. double timeout_ms;
  3567. /** How long we wait before actually closing the circuit. */
  3568. double close_ms;
  3569. } circuit_build_times_t;
  3570. /********************************* config.c ***************************/
  3571. /** An error from options_trial_assign() or options_init_from_string(). */
  3572. typedef enum setopt_err_t {
  3573. SETOPT_OK = 0,
  3574. SETOPT_ERR_MISC = -1,
  3575. SETOPT_ERR_PARSE = -2,
  3576. SETOPT_ERR_TRANSITION = -3,
  3577. SETOPT_ERR_SETTING = -4,
  3578. } setopt_err_t;
  3579. /********************************* connection_edge.c *************************/
  3580. /** Enumerates possible origins of a client-side address mapping. */
  3581. typedef enum {
  3582. /** We're remapping this address because the controller told us to. */
  3583. ADDRMAPSRC_CONTROLLER,
  3584. /** We're remapping this address because of an AutomapHostsOnResolve
  3585. * configuration. */
  3586. ADDRMAPSRC_AUTOMAP,
  3587. /** We're remapping this address because our configuration (via torrc, the
  3588. * command line, or a SETCONF command) told us to. */
  3589. ADDRMAPSRC_TORRC,
  3590. /** We're remapping this address because we have TrackHostExit configured,
  3591. * and we want to remember to use the same exit next time. */
  3592. ADDRMAPSRC_TRACKEXIT,
  3593. /** We're remapping this address because we got a DNS resolution from a
  3594. * Tor server that told us what its value was. */
  3595. ADDRMAPSRC_DNS,
  3596. /** No remapping has occurred. This isn't a possible value for an
  3597. * addrmap_entry_t; it's used as a null value when we need to answer "Why
  3598. * did this remapping happen." */
  3599. ADDRMAPSRC_NONE
  3600. } addressmap_entry_source_t;
  3601. /********************************* control.c ***************************/
  3602. /** Used to indicate the type of a circuit event passed to the controller.
  3603. * The various types are defined in control-spec.txt */
  3604. typedef enum circuit_status_event_t {
  3605. CIRC_EVENT_LAUNCHED = 0,
  3606. CIRC_EVENT_BUILT = 1,
  3607. CIRC_EVENT_EXTENDED = 2,
  3608. CIRC_EVENT_FAILED = 3,
  3609. CIRC_EVENT_CLOSED = 4,
  3610. } circuit_status_event_t;
  3611. /** Used to indicate the type of a CIRC_MINOR event passed to the controller.
  3612. * The various types are defined in control-spec.txt . */
  3613. typedef enum circuit_status_minor_event_t {
  3614. CIRC_MINOR_EVENT_PURPOSE_CHANGED,
  3615. CIRC_MINOR_EVENT_CANNIBALIZED,
  3616. } circuit_status_minor_event_t;
  3617. /** Used to indicate the type of a stream event passed to the controller.
  3618. * The various types are defined in control-spec.txt */
  3619. typedef enum stream_status_event_t {
  3620. STREAM_EVENT_SENT_CONNECT = 0,
  3621. STREAM_EVENT_SENT_RESOLVE = 1,
  3622. STREAM_EVENT_SUCCEEDED = 2,
  3623. STREAM_EVENT_FAILED = 3,
  3624. STREAM_EVENT_CLOSED = 4,
  3625. STREAM_EVENT_NEW = 5,
  3626. STREAM_EVENT_NEW_RESOLVE = 6,
  3627. STREAM_EVENT_FAILED_RETRIABLE = 7,
  3628. STREAM_EVENT_REMAP = 8
  3629. } stream_status_event_t;
  3630. /** Used to indicate the type of an OR connection event passed to the
  3631. * controller. The various types are defined in control-spec.txt */
  3632. typedef enum or_conn_status_event_t {
  3633. OR_CONN_EVENT_LAUNCHED = 0,
  3634. OR_CONN_EVENT_CONNECTED = 1,
  3635. OR_CONN_EVENT_FAILED = 2,
  3636. OR_CONN_EVENT_CLOSED = 3,
  3637. OR_CONN_EVENT_NEW = 4,
  3638. } or_conn_status_event_t;
  3639. /** Used to indicate the type of a buildtime event */
  3640. typedef enum buildtimeout_set_event_t {
  3641. BUILDTIMEOUT_SET_EVENT_COMPUTED = 0,
  3642. BUILDTIMEOUT_SET_EVENT_RESET = 1,
  3643. BUILDTIMEOUT_SET_EVENT_SUSPENDED = 2,
  3644. BUILDTIMEOUT_SET_EVENT_DISCARD = 3,
  3645. BUILDTIMEOUT_SET_EVENT_RESUME = 4
  3646. } buildtimeout_set_event_t;
  3647. /** Execute the statement <b>stmt</b>, which may log events concerning the
  3648. * connection <b>conn</b>. To prevent infinite loops, disable log messages
  3649. * being sent to controllers if <b>conn</b> is a control connection.
  3650. *
  3651. * Stmt must not contain any return or goto statements.
  3652. */
  3653. #define CONN_LOG_PROTECT(conn, stmt) \
  3654. STMT_BEGIN \
  3655. int _log_conn_is_control; \
  3656. tor_assert(conn); \
  3657. _log_conn_is_control = (conn->type == CONN_TYPE_CONTROL); \
  3658. if (_log_conn_is_control) \
  3659. disable_control_logging(); \
  3660. STMT_BEGIN stmt; STMT_END; \
  3661. if (_log_conn_is_control) \
  3662. enable_control_logging(); \
  3663. STMT_END
  3664. /** Enum describing various stages of bootstrapping, for use with controller
  3665. * bootstrap status events. The values range from 0 to 100. */
  3666. typedef enum {
  3667. BOOTSTRAP_STATUS_UNDEF=-1,
  3668. BOOTSTRAP_STATUS_STARTING=0,
  3669. BOOTSTRAP_STATUS_CONN_DIR=5,
  3670. BOOTSTRAP_STATUS_HANDSHAKE=-2,
  3671. BOOTSTRAP_STATUS_HANDSHAKE_DIR=10,
  3672. BOOTSTRAP_STATUS_ONEHOP_CREATE=15,
  3673. BOOTSTRAP_STATUS_REQUESTING_STATUS=20,
  3674. BOOTSTRAP_STATUS_LOADING_STATUS=25,
  3675. BOOTSTRAP_STATUS_LOADING_KEYS=40,
  3676. BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS=45,
  3677. BOOTSTRAP_STATUS_LOADING_DESCRIPTORS=50,
  3678. BOOTSTRAP_STATUS_CONN_OR=80,
  3679. BOOTSTRAP_STATUS_HANDSHAKE_OR=85,
  3680. BOOTSTRAP_STATUS_CIRCUIT_CREATE=90,
  3681. BOOTSTRAP_STATUS_DONE=100
  3682. } bootstrap_status_t;
  3683. /********************************* directory.c ***************************/
  3684. /** A pair of digests created by dir_split_resource_info_fingerprint_pairs() */
  3685. typedef struct {
  3686. char first[DIGEST_LEN];
  3687. char second[DIGEST_LEN];
  3688. } fp_pair_t;
  3689. /********************************* dirserv.c ***************************/
  3690. /** An enum to describe what format we're generating a routerstatus line in.
  3691. */
  3692. typedef enum {
  3693. /** For use in a v2 opinion */
  3694. NS_V2,
  3695. /** For use in a consensus networkstatus document (ns flavor) */
  3696. NS_V3_CONSENSUS,
  3697. /** For use in a vote networkstatus document */
  3698. NS_V3_VOTE,
  3699. /** For passing to the controlport in response to a GETINFO request */
  3700. NS_CONTROL_PORT,
  3701. /** For use in a consensus networkstatus document (microdesc flavor) */
  3702. NS_V3_CONSENSUS_MICRODESC
  3703. } routerstatus_format_type_t;
  3704. #ifdef DIRSERV_PRIVATE
  3705. typedef struct measured_bw_line_t {
  3706. char node_id[DIGEST_LEN];
  3707. char node_hex[MAX_HEX_NICKNAME_LEN+1];
  3708. long int bw;
  3709. } measured_bw_line_t;
  3710. #endif
  3711. /********************************* dirvote.c ************************/
  3712. /** Describes the schedule by which votes should be generated. */
  3713. typedef struct vote_timing_t {
  3714. /** Length in seconds between one consensus becoming valid and the next
  3715. * becoming valid. */
  3716. int vote_interval;
  3717. /** For how many intervals is a consensus valid? */
  3718. int n_intervals_valid;
  3719. /** Time in seconds allowed to propagate votes */
  3720. int vote_delay;
  3721. /** Time in seconds allowed to propagate signatures */
  3722. int dist_delay;
  3723. } vote_timing_t;
  3724. /********************************* geoip.c **************************/
  3725. /** Round all GeoIP results to the next multiple of this value, to avoid
  3726. * leaking information. */
  3727. #define DIR_RECORD_USAGE_GRANULARITY 8
  3728. /** Time interval: Flush geoip data to disk this often. */
  3729. #define DIR_ENTRY_RECORD_USAGE_RETAIN_IPS (24*60*60)
  3730. /** How long do we have to have observed per-country request history before
  3731. * we are willing to talk about it? */
  3732. #define DIR_RECORD_USAGE_MIN_OBSERVATION_TIME (12*60*60)
  3733. /** Indicates an action that we might be noting geoip statistics on.
  3734. * Note that if we're noticing CONNECT, we're a bridge, and if we're noticing
  3735. * the others, we're not.
  3736. */
  3737. typedef enum {
  3738. /** We've noticed a connection as a bridge relay or entry guard. */
  3739. GEOIP_CLIENT_CONNECT = 0,
  3740. /** We've served a networkstatus consensus as a directory server. */
  3741. GEOIP_CLIENT_NETWORKSTATUS = 1,
  3742. /** We've served a v2 networkstatus consensus as a directory server. */
  3743. GEOIP_CLIENT_NETWORKSTATUS_V2 = 2,
  3744. } geoip_client_action_t;
  3745. /** Indicates either a positive reply or a reason for rejectng a network
  3746. * status request that will be included in geoip statistics. */
  3747. typedef enum {
  3748. /** Request is answered successfully. */
  3749. GEOIP_SUCCESS = 0,
  3750. /** V3 network status is not signed by a sufficient number of requested
  3751. * authorities. */
  3752. GEOIP_REJECT_NOT_ENOUGH_SIGS = 1,
  3753. /** Requested network status object is unavailable. */
  3754. GEOIP_REJECT_UNAVAILABLE = 2,
  3755. /** Requested network status not found. */
  3756. GEOIP_REJECT_NOT_FOUND = 3,
  3757. /** Network status has not been modified since If-Modified-Since time. */
  3758. GEOIP_REJECT_NOT_MODIFIED = 4,
  3759. /** Directory is busy. */
  3760. GEOIP_REJECT_BUSY = 5,
  3761. } geoip_ns_response_t;
  3762. #define GEOIP_NS_RESPONSE_NUM 6
  3763. /** Directory requests that we are measuring can be either direct or
  3764. * tunneled. */
  3765. typedef enum {
  3766. DIRREQ_DIRECT = 0,
  3767. DIRREQ_TUNNELED = 1,
  3768. } dirreq_type_t;
  3769. /** Possible states for either direct or tunneled directory requests that
  3770. * are relevant for determining network status download times. */
  3771. typedef enum {
  3772. /** Found that the client requests a network status; applies to both
  3773. * direct and tunneled requests; initial state of a request that we are
  3774. * measuring. */
  3775. DIRREQ_IS_FOR_NETWORK_STATUS = 0,
  3776. /** Finished writing a network status to the directory connection;
  3777. * applies to both direct and tunneled requests; completes a direct
  3778. * request. */
  3779. DIRREQ_FLUSHING_DIR_CONN_FINISHED = 1,
  3780. /** END cell sent to circuit that initiated a tunneled request. */
  3781. DIRREQ_END_CELL_SENT = 2,
  3782. /** Flushed last cell from queue of the circuit that initiated a
  3783. * tunneled request to the outbuf of the OR connection. */
  3784. DIRREQ_CIRC_QUEUE_FLUSHED = 3,
  3785. /** Flushed last byte from buffer of the channel belonging to the
  3786. * circuit that initiated a tunneled request; completes a tunneled
  3787. * request. */
  3788. DIRREQ_CHANNEL_BUFFER_FLUSHED = 4
  3789. } dirreq_state_t;
  3790. #define WRITE_STATS_INTERVAL (24*60*60)
  3791. /********************************* microdesc.c *************************/
  3792. typedef struct microdesc_cache_t microdesc_cache_t;
  3793. /********************************* networkstatus.c *********************/
  3794. /** Location where we found a v2 networkstatus. */
  3795. typedef enum {
  3796. NS_FROM_CACHE, NS_FROM_DIR_BY_FP, NS_FROM_DIR_ALL, NS_GENERATED
  3797. } v2_networkstatus_source_t;
  3798. /** Possible statuses of a version of Tor, given opinions from the directory
  3799. * servers. */
  3800. typedef enum version_status_t {
  3801. VS_RECOMMENDED=0, /**< This version is listed as recommended. */
  3802. VS_OLD=1, /**< This version is older than any recommended version. */
  3803. VS_NEW=2, /**< This version is newer than any recommended version. */
  3804. VS_NEW_IN_SERIES=3, /**< This version is newer than any recommended version
  3805. * in its series, but later recommended versions exist.
  3806. */
  3807. VS_UNRECOMMENDED=4, /**< This version is not recommended (general case). */
  3808. VS_EMPTY=5, /**< The version list was empty; no agreed-on versions. */
  3809. VS_UNKNOWN, /**< We have no idea. */
  3810. } version_status_t;
  3811. /********************************* policies.c ************************/
  3812. /** Outcome of applying an address policy to an address. */
  3813. typedef enum {
  3814. /** The address was accepted */
  3815. ADDR_POLICY_ACCEPTED=0,
  3816. /** The address was rejected */
  3817. ADDR_POLICY_REJECTED=-1,
  3818. /** Part of the address was unknown, but as far as we can tell, it was
  3819. * accepted. */
  3820. ADDR_POLICY_PROBABLY_ACCEPTED=1,
  3821. /** Part of the address was unknown, but as far as we can tell, it was
  3822. * rejected. */
  3823. ADDR_POLICY_PROBABLY_REJECTED=2,
  3824. } addr_policy_result_t;
  3825. /********************************* rephist.c ***************************/
  3826. /** Possible public/private key operations in Tor: used to keep track of where
  3827. * we're spending our time. */
  3828. typedef enum {
  3829. SIGN_DIR, SIGN_RTR,
  3830. VERIFY_DIR, VERIFY_RTR,
  3831. ENC_ONIONSKIN, DEC_ONIONSKIN,
  3832. TLS_HANDSHAKE_C, TLS_HANDSHAKE_S,
  3833. REND_CLIENT, REND_MID, REND_SERVER,
  3834. } pk_op_t;
  3835. /********************************* rendcommon.c ***************************/
  3836. /** Hidden-service side configuration of client authorization. */
  3837. typedef struct rend_authorized_client_t {
  3838. char *client_name;
  3839. char descriptor_cookie[REND_DESC_COOKIE_LEN];
  3840. crypto_pk_t *client_key;
  3841. } rend_authorized_client_t;
  3842. /** ASCII-encoded v2 hidden service descriptor. */
  3843. typedef struct rend_encoded_v2_service_descriptor_t {
  3844. char desc_id[DIGEST_LEN]; /**< Descriptor ID. */
  3845. char *desc_str; /**< Descriptor string. */
  3846. } rend_encoded_v2_service_descriptor_t;
  3847. /** The maximum number of non-circuit-build-timeout failures a hidden
  3848. * service client will tolerate while trying to build a circuit to an
  3849. * introduction point. See also rend_intro_point_t.unreachable_count. */
  3850. #define MAX_INTRO_POINT_REACHABILITY_FAILURES 5
  3851. /** The maximum number of distinct INTRODUCE2 cells which a hidden
  3852. * service's introduction point will receive before it begins to
  3853. * expire.
  3854. *
  3855. * XXX023 Is this number at all sane? */
  3856. #define INTRO_POINT_LIFETIME_INTRODUCTIONS 16384
  3857. /** The minimum number of seconds that an introduction point will last
  3858. * before expiring due to old age. (If it receives
  3859. * INTRO_POINT_LIFETIME_INTRODUCTIONS INTRODUCE2 cells, it may expire
  3860. * sooner.)
  3861. *
  3862. * XXX023 Should this be configurable? */
  3863. #define INTRO_POINT_LIFETIME_MIN_SECONDS 18*60*60
  3864. /** The maximum number of seconds that an introduction point will last
  3865. * before expiring due to old age.
  3866. *
  3867. * XXX023 Should this be configurable? */
  3868. #define INTRO_POINT_LIFETIME_MAX_SECONDS 24*60*60
  3869. /** Introduction point information. Used both in rend_service_t (on
  3870. * the service side) and in rend_service_descriptor_t (on both the
  3871. * client and service side). */
  3872. typedef struct rend_intro_point_t {
  3873. extend_info_t *extend_info; /**< Extend info of this introduction point. */
  3874. crypto_pk_t *intro_key; /**< Introduction key that replaces the service
  3875. * key, if this descriptor is V2. */
  3876. /** (Client side only) Flag indicating that a timeout has occurred
  3877. * after sending an INTRODUCE cell to this intro point. After a
  3878. * timeout, an intro point should not be tried again during the same
  3879. * hidden service connection attempt, but it may be tried again
  3880. * during a future connection attempt. */
  3881. unsigned int timed_out : 1;
  3882. /** (Client side only) The number of times we have failed to build a
  3883. * circuit to this intro point for some reason other than our
  3884. * circuit-build timeout. See also MAX_INTRO_POINT_REACHABILITY_FAILURES. */
  3885. unsigned int unreachable_count : 3;
  3886. /** (Service side only) Flag indicating that this intro point was
  3887. * included in the last HS descriptor we generated. */
  3888. unsigned int listed_in_last_desc : 1;
  3889. /** (Service side only) Flag indicating that
  3890. * rend_service_note_removing_intro_point has been called for this
  3891. * intro point. */
  3892. unsigned int rend_service_note_removing_intro_point_called : 1;
  3893. /** (Service side only) A replay cache recording the RSA-encrypted parts
  3894. * of INTRODUCE2 cells this intro point's circuit has received. This is
  3895. * used to prevent replay attacks. */
  3896. replaycache_t *accepted_intro_rsa_parts;
  3897. /** (Service side only) Count of INTRODUCE2 cells accepted from this
  3898. * intro point.
  3899. */
  3900. int accepted_introduce2_count;
  3901. /** (Service side only) The time at which this intro point was first
  3902. * published, or -1 if this intro point has not yet been
  3903. * published. */
  3904. time_t time_published;
  3905. /** (Service side only) The time at which this intro point should
  3906. * (start to) expire, or -1 if we haven't decided when this intro
  3907. * point should expire. */
  3908. time_t time_to_expire;
  3909. /** (Service side only) The time at which we decided that this intro
  3910. * point should start expiring, or -1 if this intro point is not yet
  3911. * expiring.
  3912. *
  3913. * This field also serves as a flag to indicate that we have decided
  3914. * to expire this intro point, in case intro_point_should_expire_now
  3915. * flaps (perhaps due to a clock jump; perhaps due to other
  3916. * weirdness, or even a (present or future) bug). */
  3917. time_t time_expiring;
  3918. } rend_intro_point_t;
  3919. #define REND_PROTOCOL_VERSION_BITMASK_WIDTH 16
  3920. /** Information used to connect to a hidden service. Used on both the
  3921. * service side and the client side. */
  3922. typedef struct rend_service_descriptor_t {
  3923. crypto_pk_t *pk; /**< This service's public key. */
  3924. int version; /**< Version of the descriptor format: 0 or 2. */
  3925. time_t timestamp; /**< Time when the descriptor was generated. */
  3926. /** Bitmask: which rendezvous protocols are supported?
  3927. * (We allow bits '0', '1', and '2' to be set.) */
  3928. int protocols : REND_PROTOCOL_VERSION_BITMASK_WIDTH;
  3929. /** List of the service's introduction points. Elements are removed if
  3930. * introduction attempts fail. */
  3931. smartlist_t *intro_nodes;
  3932. /** Has descriptor been uploaded to all hidden service directories? */
  3933. int all_uploads_performed;
  3934. /** List of hidden service directories to which an upload request for
  3935. * this descriptor could be sent. Smartlist exists only when at least one
  3936. * of the previous upload requests failed (otherwise it's not important
  3937. * to know which uploads succeeded and which not). */
  3938. smartlist_t *successful_uploads;
  3939. } rend_service_descriptor_t;
  3940. /** A cached rendezvous descriptor. */
  3941. typedef struct rend_cache_entry_t {
  3942. size_t len; /**< Length of <b>desc</b> */
  3943. time_t received; /**< When was the descriptor received? */
  3944. char *desc; /**< Service descriptor */
  3945. rend_service_descriptor_t *parsed; /**< Parsed value of 'desc' */
  3946. } rend_cache_entry_t;
  3947. /********************************* routerlist.c ***************************/
  3948. /** Represents information about a single trusted directory server. */
  3949. typedef struct trusted_dir_server_t {
  3950. char *description;
  3951. char *nickname;
  3952. char *address; /**< Hostname. */
  3953. uint32_t addr; /**< IPv4 address. */
  3954. uint16_t dir_port; /**< Directory port. */
  3955. uint16_t or_port; /**< OR port: Used for tunneling connections. */
  3956. char digest[DIGEST_LEN]; /**< Digest of identity key. */
  3957. char v3_identity_digest[DIGEST_LEN]; /**< Digest of v3 (authority only,
  3958. * high-security) identity key. */
  3959. unsigned int is_running:1; /**< True iff we think this server is running. */
  3960. /** True iff this server has accepted the most recent server descriptor
  3961. * we tried to upload to it. */
  3962. unsigned int has_accepted_serverdesc:1;
  3963. /** What kind of authority is this? (Bitfield.) */
  3964. dirinfo_type_t type;
  3965. download_status_t v2_ns_dl_status; /**< Status of downloading this server's
  3966. * v2 network status. */
  3967. time_t addr_current_at; /**< When was the document that we derived the
  3968. * address information from published? */
  3969. routerstatus_t fake_status; /**< Used when we need to pass this trusted
  3970. * dir_server_t to directory_initiate_command_*
  3971. * as a routerstatus_t. Not updated by the
  3972. * router-status management code!
  3973. **/
  3974. } trusted_dir_server_t;
  3975. #define ROUTER_REQUIRED_MIN_BANDWIDTH (20*1024)
  3976. #define ROUTER_MAX_DECLARED_BANDWIDTH INT32_MAX
  3977. /* Flags for pick_directory_server() and pick_trusteddirserver(). */
  3978. /** Flag to indicate that we should not automatically be willing to use
  3979. * ourself to answer a directory request.
  3980. * Passed to router_pick_directory_server (et al).*/
  3981. #define PDS_ALLOW_SELF (1<<0)
  3982. /** Flag to indicate that if no servers seem to be up, we should mark all
  3983. * directory servers as up and try again.
  3984. * Passed to router_pick_directory_server (et al).*/
  3985. #define PDS_RETRY_IF_NO_SERVERS (1<<1)
  3986. /** Flag to indicate that we should not exclude directory servers that
  3987. * our ReachableAddress settings would exclude. This usually means that
  3988. * we're going to connect to the server over Tor, and so we don't need to
  3989. * worry about our firewall telling us we can't.
  3990. * Passed to router_pick_directory_server (et al).*/
  3991. #define PDS_IGNORE_FASCISTFIREWALL (1<<2)
  3992. /** Flag to indicate that we should not use any directory authority to which
  3993. * we have an existing directory connection for downloading server descriptors
  3994. * or extrainfo documents.
  3995. *
  3996. * Passed to router_pick_directory_server (et al)
  3997. *
  3998. * [XXXX NOTE: This option is only implemented for pick_trusteddirserver,
  3999. * not pick_directory_server. If we make it work on pick_directory_server
  4000. * too, we could conservatively make it only prevent multiple fetches to
  4001. * the same authority, or we could aggressively make it prevent multiple
  4002. * fetches to _any_ single directory server.]
  4003. */
  4004. #define PDS_NO_EXISTING_SERVERDESC_FETCH (1<<3)
  4005. #define PDS_NO_EXISTING_MICRODESC_FETCH (1<<4)
  4006. #define PDS_PREFER_TUNNELED_DIR_CONNS_ (1<<16)
  4007. /** Possible ways to weight routers when choosing one randomly. See
  4008. * routerlist_sl_choose_by_bandwidth() for more information.*/
  4009. typedef enum bandwidth_weight_rule_t {
  4010. NO_WEIGHTING, WEIGHT_FOR_EXIT, WEIGHT_FOR_MID, WEIGHT_FOR_GUARD,
  4011. WEIGHT_FOR_DIR
  4012. } bandwidth_weight_rule_t;
  4013. /** Flags to be passed to control router_choose_random_node() to indicate what
  4014. * kind of nodes to pick according to what algorithm. */
  4015. typedef enum {
  4016. CRN_NEED_UPTIME = 1<<0,
  4017. CRN_NEED_CAPACITY = 1<<1,
  4018. CRN_NEED_GUARD = 1<<2,
  4019. CRN_ALLOW_INVALID = 1<<3,
  4020. /* XXXX not used, apparently. */
  4021. CRN_WEIGHT_AS_EXIT = 1<<5,
  4022. CRN_NEED_DESC = 1<<6
  4023. } router_crn_flags_t;
  4024. /** Return value for router_add_to_routerlist() and dirserv_add_descriptor() */
  4025. typedef enum was_router_added_t {
  4026. ROUTER_ADDED_SUCCESSFULLY = 1,
  4027. ROUTER_ADDED_NOTIFY_GENERATOR = 0,
  4028. ROUTER_BAD_EI = -1,
  4029. ROUTER_WAS_NOT_NEW = -2,
  4030. ROUTER_NOT_IN_CONSENSUS = -3,
  4031. ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS = -4,
  4032. ROUTER_AUTHDIR_REJECTS = -5,
  4033. ROUTER_WAS_NOT_WANTED = -6
  4034. } was_router_added_t;
  4035. /********************************* routerparse.c ************************/
  4036. #define MAX_STATUS_TAG_LEN 32
  4037. /** Structure to hold parsed Tor versions. This is a little messier
  4038. * than we would like it to be, because we changed version schemes with 0.1.0.
  4039. *
  4040. * See version-spec.txt for the whole business.
  4041. */
  4042. typedef struct tor_version_t {
  4043. int major;
  4044. int minor;
  4045. int micro;
  4046. /** Release status. For version in the post-0.1 format, this is always
  4047. * VER_RELEASE. */
  4048. enum { VER_PRE=0, VER_RC=1, VER_RELEASE=2, } status;
  4049. int patchlevel;
  4050. char status_tag[MAX_STATUS_TAG_LEN];
  4051. int svn_revision;
  4052. int git_tag_len;
  4053. char git_tag[DIGEST_LEN];
  4054. } tor_version_t;
  4055. #endif