or.h 168 KB

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