or.h 149 KB

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