or.h 219 KB

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