directory.c 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2013, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #include "or.h"
  6. #include "buffers.h"
  7. #include "circuitbuild.h"
  8. #include "config.h"
  9. #include "connection.h"
  10. #include "connection_edge.h"
  11. #include "control.h"
  12. #include "directory.h"
  13. #include "dirserv.h"
  14. #include "dirvote.h"
  15. #include "entrynodes.h"
  16. #include "geoip.h"
  17. #include "main.h"
  18. #include "microdesc.h"
  19. #include "networkstatus.h"
  20. #include "nodelist.h"
  21. #include "policies.h"
  22. #include "rendclient.h"
  23. #include "rendcommon.h"
  24. #include "rephist.h"
  25. #include "router.h"
  26. #include "routerlist.h"
  27. #include "routerparse.h"
  28. #include "routerset.h"
  29. #if defined(EXPORTMALLINFO) && defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
  30. #ifndef OPENBSD
  31. #include <malloc.h>
  32. #endif
  33. #endif
  34. /**
  35. * \file directory.c
  36. * \brief Code to send and fetch directories and router
  37. * descriptors via HTTP. Directories use dirserv.c to generate the
  38. * results; clients use routers.c to parse them.
  39. **/
  40. /* In-points to directory.c:
  41. *
  42. * - directory_post_to_dirservers(), called from
  43. * router_upload_dir_desc_to_dirservers() in router.c
  44. * upload_service_descriptor() in rendservice.c
  45. * - directory_get_from_dirserver(), called from
  46. * rend_client_refetch_renddesc() in rendclient.c
  47. * run_scheduled_events() in main.c
  48. * do_hup() in main.c
  49. * - connection_dir_process_inbuf(), called from
  50. * connection_process_inbuf() in connection.c
  51. * - connection_dir_finished_flushing(), called from
  52. * connection_finished_flushing() in connection.c
  53. * - connection_dir_finished_connecting(), called from
  54. * connection_finished_connecting() in connection.c
  55. */
  56. static void directory_send_command(dir_connection_t *conn,
  57. int purpose, int direct, const char *resource,
  58. const char *payload, size_t payload_len,
  59. time_t if_modified_since);
  60. static int directory_handle_command(dir_connection_t *conn);
  61. static int body_is_plausible(const char *body, size_t body_len, int purpose);
  62. static int purpose_needs_anonymity(uint8_t dir_purpose,
  63. uint8_t router_purpose);
  64. static char *http_get_header(const char *headers, const char *which);
  65. static void http_set_address_origin(const char *headers, connection_t *conn);
  66. static void connection_dir_download_routerdesc_failed(dir_connection_t *conn);
  67. static void connection_dir_bridge_routerdesc_failed(dir_connection_t *conn);
  68. static void connection_dir_download_cert_failed(
  69. dir_connection_t *conn, int status_code);
  70. static void connection_dir_retry_bridges(smartlist_t *descs);
  71. static void dir_routerdesc_download_failed(smartlist_t *failed,
  72. int status_code,
  73. int router_purpose,
  74. int was_extrainfo,
  75. int was_descriptor_digests);
  76. static void dir_microdesc_download_failed(smartlist_t *failed,
  77. int status_code);
  78. static void note_client_request(int purpose, int compressed, size_t bytes);
  79. static int client_likes_consensus(networkstatus_t *v, const char *want_url);
  80. static void directory_initiate_command_rend(const tor_addr_t *addr,
  81. uint16_t or_port,
  82. uint16_t dir_port,
  83. const char *digest,
  84. uint8_t dir_purpose,
  85. uint8_t router_purpose,
  86. dir_indirection_t indirection,
  87. const char *resource,
  88. const char *payload,
  89. size_t payload_len,
  90. time_t if_modified_since,
  91. const rend_data_t *rend_query);
  92. /********* START VARIABLES **********/
  93. /** How far in the future do we allow a directory server to tell us it is
  94. * before deciding that one of us has the wrong time? */
  95. #define ALLOW_DIRECTORY_TIME_SKEW (30*60)
  96. #define X_ADDRESS_HEADER "X-Your-Address-Is: "
  97. /** HTTP cache control: how long do we tell proxies they can cache each
  98. * kind of document we serve? */
  99. #define FULL_DIR_CACHE_LIFETIME (60*60)
  100. #define RUNNINGROUTERS_CACHE_LIFETIME (20*60)
  101. #define DIRPORTFRONTPAGE_CACHE_LIFETIME (20*60)
  102. #define NETWORKSTATUS_CACHE_LIFETIME (5*60)
  103. #define ROUTERDESC_CACHE_LIFETIME (30*60)
  104. #define ROUTERDESC_BY_DIGEST_CACHE_LIFETIME (48*60*60)
  105. #define ROBOTS_CACHE_LIFETIME (24*60*60)
  106. #define MICRODESC_CACHE_LIFETIME (48*60*60)
  107. /********* END VARIABLES ************/
  108. /** Return true iff the directory purpose <b>dir_purpose</b> (and if it's
  109. * fetching descriptors, it's fetching them for <b>router_purpose</b>)
  110. * must use an anonymous connection to a directory. */
  111. static int
  112. purpose_needs_anonymity(uint8_t dir_purpose, uint8_t router_purpose)
  113. {
  114. if (get_options()->AllDirActionsPrivate)
  115. return 1;
  116. if (router_purpose == ROUTER_PURPOSE_BRIDGE)
  117. return 1; /* if no circuits yet, this might break bootstrapping, but it's
  118. * needed to be safe. */
  119. if (dir_purpose == DIR_PURPOSE_UPLOAD_DIR ||
  120. dir_purpose == DIR_PURPOSE_UPLOAD_VOTE ||
  121. dir_purpose == DIR_PURPOSE_UPLOAD_SIGNATURES ||
  122. dir_purpose == DIR_PURPOSE_FETCH_STATUS_VOTE ||
  123. dir_purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES ||
  124. dir_purpose == DIR_PURPOSE_FETCH_CONSENSUS ||
  125. dir_purpose == DIR_PURPOSE_FETCH_CERTIFICATE ||
  126. dir_purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  127. dir_purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
  128. dir_purpose == DIR_PURPOSE_FETCH_MICRODESC)
  129. return 0;
  130. return 1;
  131. }
  132. /** Return a newly allocated string describing <b>auth</b>. Only describes
  133. * authority features. */
  134. static char *
  135. authdir_type_to_string(dirinfo_type_t auth)
  136. {
  137. char *result;
  138. smartlist_t *lst = smartlist_new();
  139. if (auth & V3_DIRINFO)
  140. smartlist_add(lst, (void*)"V3");
  141. if (auth & BRIDGE_DIRINFO)
  142. smartlist_add(lst, (void*)"Bridge");
  143. if (smartlist_len(lst)) {
  144. result = smartlist_join_strings(lst, ", ", 0, NULL);
  145. } else {
  146. result = tor_strdup("[Not an authority]");
  147. }
  148. smartlist_free(lst);
  149. return result;
  150. }
  151. /** Return a string describing a given directory connection purpose. */
  152. static const char *
  153. dir_conn_purpose_to_string(int purpose)
  154. {
  155. switch (purpose)
  156. {
  157. case DIR_PURPOSE_UPLOAD_DIR:
  158. return "server descriptor upload";
  159. case DIR_PURPOSE_UPLOAD_VOTE:
  160. return "server vote upload";
  161. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  162. return "consensus signature upload";
  163. case DIR_PURPOSE_FETCH_SERVERDESC:
  164. return "server descriptor fetch";
  165. case DIR_PURPOSE_FETCH_EXTRAINFO:
  166. return "extra-info fetch";
  167. case DIR_PURPOSE_FETCH_CONSENSUS:
  168. return "consensus network-status fetch";
  169. case DIR_PURPOSE_FETCH_CERTIFICATE:
  170. return "authority cert fetch";
  171. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  172. return "status vote fetch";
  173. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  174. return "consensus signature fetch";
  175. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  176. return "hidden-service v2 descriptor fetch";
  177. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  178. return "hidden-service v2 descriptor upload";
  179. case DIR_PURPOSE_FETCH_MICRODESC:
  180. return "microdescriptor fetch";
  181. }
  182. log_warn(LD_BUG, "Called with unknown purpose %d", purpose);
  183. return "(unknown)";
  184. }
  185. /** Return true iff <b>identity_digest</b> is the digest of a router we
  186. * believe to support extrainfo downloads. (If <b>is_authority</b> we do
  187. * additional checking that's only valid for authorities.) */
  188. int
  189. router_supports_extrainfo(const char *identity_digest, int is_authority)
  190. {
  191. const node_t *node = node_get_by_id(identity_digest);
  192. if (node && node->ri) {
  193. if (node->ri->caches_extra_info)
  194. return 1;
  195. }
  196. if (is_authority) {
  197. return 1;
  198. }
  199. return 0;
  200. }
  201. /** Return true iff any trusted directory authority has accepted our
  202. * server descriptor.
  203. *
  204. * We consider any authority sufficient because waiting for all of
  205. * them means it never happens while any authority is down; we don't
  206. * go for something more complex in the middle (like \>1/3 or \>1/2 or
  207. * \>=1/2) because that doesn't seem necessary yet.
  208. */
  209. int
  210. directories_have_accepted_server_descriptor(void)
  211. {
  212. const smartlist_t *servers = router_get_trusted_dir_servers();
  213. const or_options_t *options = get_options();
  214. SMARTLIST_FOREACH(servers, dir_server_t *, d, {
  215. if ((d->type & options->PublishServerDescriptor_) &&
  216. d->has_accepted_serverdesc) {
  217. return 1;
  218. }
  219. });
  220. return 0;
  221. }
  222. /** Start a connection to every suitable directory authority, using
  223. * connection purpose <b>dir_purpose</b> and uploading <b>payload</b>
  224. * (of length <b>payload_len</b>). The dir_purpose should be one of
  225. * 'DIR_PURPOSE_UPLOAD_{DIR|VOTE|SIGNATURES}'.
  226. *
  227. * <b>router_purpose</b> describes the type of descriptor we're
  228. * publishing, if we're publishing a descriptor -- e.g. general or bridge.
  229. *
  230. * <b>type</b> specifies what sort of dir authorities (V3,
  231. * BRIDGE, etc) we should upload to.
  232. *
  233. * If <b>extrainfo_len</b> is nonzero, the first <b>payload_len</b> bytes of
  234. * <b>payload</b> hold a router descriptor, and the next <b>extrainfo_len</b>
  235. * bytes of <b>payload</b> hold an extra-info document. Upload the descriptor
  236. * to all authorities, and the extra-info document to all authorities that
  237. * support it.
  238. */
  239. void
  240. directory_post_to_dirservers(uint8_t dir_purpose, uint8_t router_purpose,
  241. dirinfo_type_t type,
  242. const char *payload,
  243. size_t payload_len, size_t extrainfo_len)
  244. {
  245. const or_options_t *options = get_options();
  246. dir_indirection_t indirection;
  247. const smartlist_t *dirservers = router_get_trusted_dir_servers();
  248. int found = 0;
  249. const int exclude_self = (dir_purpose == DIR_PURPOSE_UPLOAD_VOTE ||
  250. dir_purpose == DIR_PURPOSE_UPLOAD_SIGNATURES);
  251. tor_assert(dirservers);
  252. /* This tries dirservers which we believe to be down, but ultimately, that's
  253. * harmless, and we may as well err on the side of getting things uploaded.
  254. */
  255. SMARTLIST_FOREACH_BEGIN(dirservers, dir_server_t *, ds) {
  256. routerstatus_t *rs = &(ds->fake_status);
  257. size_t upload_len = payload_len;
  258. tor_addr_t ds_addr;
  259. if ((type & ds->type) == 0)
  260. continue;
  261. if (exclude_self && router_digest_is_me(ds->digest)) {
  262. /* we don't upload to ourselves, but at least there's now at least
  263. * one authority of this type that has what we wanted to upload. */
  264. found = 1;
  265. continue;
  266. }
  267. if (options->StrictNodes &&
  268. routerset_contains_routerstatus(options->ExcludeNodes, rs, -1)) {
  269. log_warn(LD_DIR, "Wanted to contact authority '%s' for %s, but "
  270. "it's in our ExcludedNodes list and StrictNodes is set. "
  271. "Skipping.",
  272. ds->nickname,
  273. dir_conn_purpose_to_string(dir_purpose));
  274. continue;
  275. }
  276. found = 1; /* at least one authority of this type was listed */
  277. if (dir_purpose == DIR_PURPOSE_UPLOAD_DIR)
  278. ds->has_accepted_serverdesc = 0;
  279. if (extrainfo_len && router_supports_extrainfo(ds->digest, 1)) {
  280. upload_len += extrainfo_len;
  281. log_info(LD_DIR, "Uploading an extrainfo too (length %d)",
  282. (int) extrainfo_len);
  283. }
  284. tor_addr_from_ipv4h(&ds_addr, ds->addr);
  285. if (purpose_needs_anonymity(dir_purpose, router_purpose)) {
  286. indirection = DIRIND_ANONYMOUS;
  287. } else if (!fascist_firewall_allows_address_dir(&ds_addr,ds->dir_port)) {
  288. if (fascist_firewall_allows_address_or(&ds_addr,ds->or_port))
  289. indirection = DIRIND_ONEHOP;
  290. else
  291. indirection = DIRIND_ANONYMOUS;
  292. } else {
  293. indirection = DIRIND_DIRECT_CONN;
  294. }
  295. directory_initiate_command_routerstatus(rs, dir_purpose,
  296. router_purpose,
  297. indirection,
  298. NULL, payload, upload_len, 0);
  299. } SMARTLIST_FOREACH_END(ds);
  300. if (!found) {
  301. char *s = authdir_type_to_string(type);
  302. log_warn(LD_DIR, "Publishing server descriptor to directory authorities "
  303. "of type '%s', but no authorities of that type listed!", s);
  304. tor_free(s);
  305. }
  306. }
  307. /** Return true iff, according to the values in <b>options</b>, we should be
  308. * using directory guards for direct downloads of directory information. */
  309. static int
  310. should_use_directory_guards(const or_options_t *options)
  311. {
  312. /* Public (non-bridge) servers never use directory guards. */
  313. if (public_server_mode(options))
  314. return 0;
  315. /* If guards are disabled, or directory guards are disabled, we can't
  316. * use directory guards.
  317. */
  318. if (!options->UseEntryGuards || !options->UseEntryGuardsAsDirGuards)
  319. return 0;
  320. /* If we're configured to fetch directory info aggressively or of a
  321. * nonstandard type, don't use directory guards. */
  322. if (options->DownloadExtraInfo || options->FetchDirInfoEarly ||
  323. options->FetchDirInfoExtraEarly || options->FetchUselessDescriptors)
  324. return 0;
  325. return 1;
  326. }
  327. /** Pick an unconstrained directory server from among our guards, the latest
  328. * networkstatus, or the fallback dirservers, for use in downloading
  329. * information of type <b>type</b>, and return its routerstatus. */
  330. static const routerstatus_t *
  331. directory_pick_generic_dirserver(dirinfo_type_t type, int pds_flags,
  332. uint8_t dir_purpose)
  333. {
  334. const routerstatus_t *rs = NULL;
  335. const or_options_t *options = get_options();
  336. if (options->UseBridges)
  337. log_warn(LD_BUG, "Called when we have UseBridges set.");
  338. if (should_use_directory_guards(options)) {
  339. const node_t *node = choose_random_dirguard(type);
  340. if (node)
  341. rs = node->rs;
  342. } else {
  343. /* anybody with a non-zero dirport will do */
  344. rs = router_pick_directory_server(type, pds_flags);
  345. }
  346. if (!rs) {
  347. log_info(LD_DIR, "No router found for %s; falling back to "
  348. "dirserver list.", dir_conn_purpose_to_string(dir_purpose));
  349. rs = router_pick_fallback_dirserver(type, pds_flags);
  350. }
  351. return rs;
  352. }
  353. /** Start a connection to a random running directory server, using
  354. * connection purpose <b>dir_purpose</b>, intending to fetch descriptors
  355. * of purpose <b>router_purpose</b>, and requesting <b>resource</b>.
  356. * Use <b>pds_flags</b> as arguments to router_pick_directory_server()
  357. * or router_pick_trusteddirserver().
  358. */
  359. void
  360. directory_get_from_dirserver(uint8_t dir_purpose, uint8_t router_purpose,
  361. const char *resource, int pds_flags)
  362. {
  363. const routerstatus_t *rs = NULL;
  364. const or_options_t *options = get_options();
  365. int prefer_authority = directory_fetches_from_authorities(options);
  366. int require_authority = 0;
  367. int get_via_tor = purpose_needs_anonymity(dir_purpose, router_purpose);
  368. dirinfo_type_t type;
  369. time_t if_modified_since = 0;
  370. /* FFFF we could break this switch into its own function, and call
  371. * it elsewhere in directory.c. -RD */
  372. switch (dir_purpose) {
  373. case DIR_PURPOSE_FETCH_EXTRAINFO:
  374. type = EXTRAINFO_DIRINFO |
  375. (router_purpose == ROUTER_PURPOSE_BRIDGE ? BRIDGE_DIRINFO :
  376. V3_DIRINFO);
  377. break;
  378. case DIR_PURPOSE_FETCH_SERVERDESC:
  379. type = (router_purpose == ROUTER_PURPOSE_BRIDGE ? BRIDGE_DIRINFO :
  380. V3_DIRINFO);
  381. break;
  382. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  383. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  384. case DIR_PURPOSE_FETCH_CERTIFICATE:
  385. type = V3_DIRINFO;
  386. break;
  387. case DIR_PURPOSE_FETCH_CONSENSUS:
  388. type = V3_DIRINFO;
  389. if (resource && !strcmp(resource,"microdesc"))
  390. type |= MICRODESC_DIRINFO;
  391. break;
  392. case DIR_PURPOSE_FETCH_MICRODESC:
  393. type = MICRODESC_DIRINFO;
  394. break;
  395. default:
  396. log_warn(LD_BUG, "Unexpected purpose %d", (int)dir_purpose);
  397. return;
  398. }
  399. if (dir_purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
  400. int flav = FLAV_NS;
  401. networkstatus_t *v;
  402. if (resource)
  403. flav = networkstatus_parse_flavor_name(resource);
  404. if (flav != -1) {
  405. /* IF we have a parsed consensus of this type, we can do an
  406. * if-modified-time based on it. */
  407. v = networkstatus_get_latest_consensus_by_flavor(flav);
  408. if (v)
  409. if_modified_since = v->valid_after + 180;
  410. } else {
  411. /* Otherwise it might be a consensus we don't parse, but which we
  412. * do cache. Look at the cached copy, perhaps. */
  413. cached_dir_t *cd = dirserv_get_consensus(resource);
  414. if (cd)
  415. if_modified_since = cd->published + 180;
  416. }
  417. }
  418. if (!options->FetchServerDescriptors)
  419. return;
  420. if (!get_via_tor) {
  421. if (options->UseBridges && type != BRIDGE_DIRINFO) {
  422. /* We want to ask a running bridge for which we have a descriptor.
  423. *
  424. * When we ask choose_random_entry() for a bridge, we specify what
  425. * sort of dir fetch we'll be doing, so it won't return a bridge
  426. * that can't answer our question.
  427. */
  428. /* XXX024 Not all bridges handle conditional consensus downloading,
  429. * so, for now, never assume the server supports that. -PP */
  430. const node_t *node = choose_random_dirguard(type);
  431. if (node && node->ri) {
  432. /* every bridge has a routerinfo. */
  433. tor_addr_t addr;
  434. routerinfo_t *ri = node->ri;
  435. node_get_addr(node, &addr);
  436. directory_initiate_command(&addr,
  437. ri->or_port, 0/*no dirport*/,
  438. ri->cache_info.identity_digest,
  439. dir_purpose,
  440. router_purpose,
  441. DIRIND_ONEHOP,
  442. resource, NULL, 0, if_modified_since);
  443. } else
  444. log_notice(LD_DIR, "Ignoring directory request, since no bridge "
  445. "nodes are available yet.");
  446. return;
  447. } else {
  448. if (prefer_authority || type == BRIDGE_DIRINFO) {
  449. /* only ask authdirservers, and don't ask myself */
  450. rs = router_pick_trusteddirserver(type, pds_flags);
  451. if (rs == NULL && (pds_flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
  452. PDS_NO_EXISTING_MICRODESC_FETCH))) {
  453. /* We don't want to fetch from any authorities that we're currently
  454. * fetching server descriptors from, and we got no match. Did we
  455. * get no match because all the authorities have connections
  456. * fetching server descriptors (in which case we should just
  457. * return,) or because all the authorities are down or on fire or
  458. * unreachable or something (in which case we should go on with
  459. * our fallback code)? */
  460. pds_flags &= ~(PDS_NO_EXISTING_SERVERDESC_FETCH|
  461. PDS_NO_EXISTING_MICRODESC_FETCH);
  462. rs = router_pick_trusteddirserver(type, pds_flags);
  463. if (rs) {
  464. log_debug(LD_DIR, "Deferring serverdesc fetch: all authorities "
  465. "are in use.");
  466. return;
  467. }
  468. }
  469. if (rs == NULL && require_authority) {
  470. log_info(LD_DIR, "No authorities were available for %s: will try "
  471. "later.", dir_conn_purpose_to_string(dir_purpose));
  472. return;
  473. }
  474. }
  475. if (!rs && type != BRIDGE_DIRINFO) {
  476. /* */
  477. rs = directory_pick_generic_dirserver(type, pds_flags,
  478. dir_purpose);
  479. if (!rs) {
  480. /*XXXX024 I'm pretty sure this can never do any good, since
  481. * rs isn't set. */
  482. get_via_tor = 1; /* last resort: try routing it via Tor */
  483. }
  484. }
  485. }
  486. } else { /* get_via_tor */
  487. /* Never use fascistfirewall; we're going via Tor. */
  488. if (1) {
  489. /* anybody with a non-zero dirport will do. Disregard firewalls. */
  490. pds_flags |= PDS_IGNORE_FASCISTFIREWALL;
  491. rs = router_pick_directory_server(type, pds_flags);
  492. /* If we have any hope of building an indirect conn, we know some router
  493. * descriptors. If (rs==NULL), we can't build circuits anyway, so
  494. * there's no point in falling back to the authorities in this case. */
  495. }
  496. }
  497. if (rs) {
  498. const dir_indirection_t indirection =
  499. get_via_tor ? DIRIND_ANONYMOUS : DIRIND_ONEHOP;
  500. directory_initiate_command_routerstatus(rs, dir_purpose,
  501. router_purpose,
  502. indirection,
  503. resource, NULL, 0,
  504. if_modified_since);
  505. } else {
  506. log_notice(LD_DIR,
  507. "While fetching directory info, "
  508. "no running dirservers known. Will try again later. "
  509. "(purpose %d)", dir_purpose);
  510. if (!purpose_needs_anonymity(dir_purpose, router_purpose)) {
  511. /* remember we tried them all and failed. */
  512. directory_all_unreachable(time(NULL));
  513. }
  514. }
  515. }
  516. /** As directory_get_from_dirserver, but initiates a request to <i>every</i>
  517. * directory authority other than ourself. Only for use by authorities when
  518. * searching for missing information while voting. */
  519. void
  520. directory_get_from_all_authorities(uint8_t dir_purpose,
  521. uint8_t router_purpose,
  522. const char *resource)
  523. {
  524. tor_assert(dir_purpose == DIR_PURPOSE_FETCH_STATUS_VOTE ||
  525. dir_purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES);
  526. SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
  527. dir_server_t *, ds) {
  528. routerstatus_t *rs;
  529. if (router_digest_is_me(ds->digest))
  530. continue;
  531. if (!(ds->type & V3_DIRINFO))
  532. continue;
  533. rs = &ds->fake_status;
  534. directory_initiate_command_routerstatus(rs, dir_purpose, router_purpose,
  535. DIRIND_ONEHOP, resource, NULL,
  536. 0, 0);
  537. } SMARTLIST_FOREACH_END(ds);
  538. }
  539. /** Return true iff <b>ind</b> requires a multihop circuit. */
  540. static int
  541. dirind_is_anon(dir_indirection_t ind)
  542. {
  543. return ind == DIRIND_ANON_DIRPORT || ind == DIRIND_ANONYMOUS;
  544. }
  545. /** Same as directory_initiate_command_routerstatus(), but accepts
  546. * rendezvous data to fetch a hidden service descriptor. */
  547. void
  548. directory_initiate_command_routerstatus_rend(const routerstatus_t *status,
  549. uint8_t dir_purpose,
  550. uint8_t router_purpose,
  551. dir_indirection_t indirection,
  552. const char *resource,
  553. const char *payload,
  554. size_t payload_len,
  555. time_t if_modified_since,
  556. const rend_data_t *rend_query)
  557. {
  558. const or_options_t *options = get_options();
  559. const node_t *node;
  560. tor_addr_t addr;
  561. const int anonymized_connection = dirind_is_anon(indirection);
  562. node = node_get_by_id(status->identity_digest);
  563. if (!node && anonymized_connection) {
  564. log_info(LD_DIR, "Not sending anonymized request to directory '%s'; we "
  565. "don't have its router descriptor.",
  566. routerstatus_describe(status));
  567. return;
  568. }
  569. tor_addr_from_ipv4h(&addr, status->addr);
  570. if (options->ExcludeNodes && options->StrictNodes &&
  571. routerset_contains_routerstatus(options->ExcludeNodes, status, -1)) {
  572. log_warn(LD_DIR, "Wanted to contact directory mirror %s for %s, but "
  573. "it's in our ExcludedNodes list and StrictNodes is set. "
  574. "Skipping. This choice might make your Tor not work.",
  575. routerstatus_describe(status),
  576. dir_conn_purpose_to_string(dir_purpose));
  577. return;
  578. }
  579. directory_initiate_command_rend(&addr,
  580. status->or_port, status->dir_port,
  581. status->identity_digest,
  582. dir_purpose, router_purpose,
  583. indirection, resource,
  584. payload, payload_len, if_modified_since,
  585. rend_query);
  586. }
  587. /** Launch a new connection to the directory server <b>status</b> to
  588. * upload or download a server or rendezvous
  589. * descriptor. <b>dir_purpose</b> determines what
  590. * kind of directory connection we're launching, and must be one of
  591. * DIR_PURPOSE_{FETCH|UPLOAD}_{DIR|RENDDESC_V2}. <b>router_purpose</b>
  592. * specifies the descriptor purposes we have in mind (currently only
  593. * used for FETCH_DIR).
  594. *
  595. * When uploading, <b>payload</b> and <b>payload_len</b> determine the content
  596. * of the HTTP post. Otherwise, <b>payload</b> should be NULL.
  597. *
  598. * When fetching a rendezvous descriptor, <b>resource</b> is the service ID we
  599. * want to fetch.
  600. */
  601. void
  602. directory_initiate_command_routerstatus(const routerstatus_t *status,
  603. uint8_t dir_purpose,
  604. uint8_t router_purpose,
  605. dir_indirection_t indirection,
  606. const char *resource,
  607. const char *payload,
  608. size_t payload_len,
  609. time_t if_modified_since)
  610. {
  611. directory_initiate_command_routerstatus_rend(status, dir_purpose,
  612. router_purpose,
  613. indirection, resource,
  614. payload, payload_len,
  615. if_modified_since, NULL);
  616. }
  617. /** Return true iff <b>conn</b> is the client side of a directory connection
  618. * we launched to ourself in order to determine the reachability of our
  619. * dir_port. */
  620. static int
  621. directory_conn_is_self_reachability_test(dir_connection_t *conn)
  622. {
  623. if (conn->requested_resource &&
  624. !strcmpstart(conn->requested_resource,"authority")) {
  625. const routerinfo_t *me = router_get_my_routerinfo();
  626. if (me &&
  627. router_digest_is_me(conn->identity_digest) &&
  628. tor_addr_eq_ipv4h(&conn->base_.addr, me->addr) && /*XXXX prop 118*/
  629. me->dir_port == conn->base_.port)
  630. return 1;
  631. }
  632. return 0;
  633. }
  634. /** Called when we are unable to complete the client's request to a directory
  635. * server due to a network error: Mark the router as down and try again if
  636. * possible.
  637. */
  638. static void
  639. connection_dir_request_failed(dir_connection_t *conn)
  640. {
  641. if (directory_conn_is_self_reachability_test(conn)) {
  642. return; /* this was a test fetch. don't retry. */
  643. }
  644. if (!entry_list_is_constrained(get_options()))
  645. router_set_status(conn->identity_digest, 0); /* don't try him again */
  646. if (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  647. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO) {
  648. log_info(LD_DIR, "Giving up on serverdesc/extrainfo fetch from "
  649. "directory server at '%s'; retrying",
  650. conn->base_.address);
  651. if (conn->router_purpose == ROUTER_PURPOSE_BRIDGE)
  652. connection_dir_bridge_routerdesc_failed(conn);
  653. connection_dir_download_routerdesc_failed(conn);
  654. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
  655. if (conn->requested_resource)
  656. networkstatus_consensus_download_failed(0, conn->requested_resource);
  657. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE) {
  658. log_info(LD_DIR, "Giving up on certificate fetch from directory server "
  659. "at '%s'; retrying",
  660. conn->base_.address);
  661. connection_dir_download_cert_failed(conn, 0);
  662. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES) {
  663. log_info(LD_DIR, "Giving up downloading detached signatures from '%s'",
  664. conn->base_.address);
  665. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) {
  666. log_info(LD_DIR, "Giving up downloading votes from '%s'",
  667. conn->base_.address);
  668. } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  669. log_info(LD_DIR, "Giving up on downloading microdescriptors from "
  670. "directory server at '%s'; will retry", conn->base_.address);
  671. connection_dir_download_routerdesc_failed(conn);
  672. }
  673. }
  674. /** Helper: Attempt to fetch directly the descriptors of each bridge
  675. * listed in <b>failed</b>.
  676. */
  677. static void
  678. connection_dir_retry_bridges(smartlist_t *descs)
  679. {
  680. char digest[DIGEST_LEN];
  681. SMARTLIST_FOREACH(descs, const char *, cp,
  682. {
  683. if (base16_decode(digest, DIGEST_LEN, cp, strlen(cp))<0) {
  684. log_warn(LD_BUG, "Malformed fingerprint in list: %s",
  685. escaped(cp));
  686. continue;
  687. }
  688. retry_bridge_descriptor_fetch_directly(digest);
  689. });
  690. }
  691. /** Called when an attempt to download one or more router descriptors
  692. * or extra-info documents on connection <b>conn</b> failed.
  693. */
  694. static void
  695. connection_dir_download_routerdesc_failed(dir_connection_t *conn)
  696. {
  697. /* No need to increment the failure count for routerdescs, since
  698. * it's not their fault. */
  699. /* No need to relaunch descriptor downloads here: we already do it
  700. * every 10 or 60 seconds (FOO_DESCRIPTOR_RETRY_INTERVAL) in main.c. */
  701. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  702. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
  703. conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  704. (void) conn;
  705. }
  706. /** Called when an attempt to download a bridge's routerdesc from
  707. * one of the authorities failed due to a network error. If
  708. * possible attempt to download descriptors from the bridge directly.
  709. */
  710. static void
  711. connection_dir_bridge_routerdesc_failed(dir_connection_t *conn)
  712. {
  713. smartlist_t *which = NULL;
  714. /* Requests for bridge descriptors are in the form 'fp/', so ignore
  715. anything else. */
  716. if (!conn->requested_resource || strcmpstart(conn->requested_resource,"fp/"))
  717. return;
  718. which = smartlist_new();
  719. dir_split_resource_into_fingerprints(conn->requested_resource
  720. + strlen("fp/"),
  721. which, NULL, 0);
  722. tor_assert(conn->base_.purpose != DIR_PURPOSE_FETCH_EXTRAINFO);
  723. if (smartlist_len(which)) {
  724. connection_dir_retry_bridges(which);
  725. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  726. }
  727. smartlist_free(which);
  728. }
  729. /** Called when an attempt to fetch a certificate fails. */
  730. static void
  731. connection_dir_download_cert_failed(dir_connection_t *conn, int status)
  732. {
  733. const char *fp_pfx = "fp/";
  734. const char *fpsk_pfx = "fp-sk/";
  735. smartlist_t *failed;
  736. tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE);
  737. if (!conn->requested_resource)
  738. return;
  739. failed = smartlist_new();
  740. /*
  741. * We have two cases download by fingerprint (resource starts
  742. * with "fp/") or download by fingerprint/signing key pair
  743. * (resource starts with "fp-sk/").
  744. */
  745. if (!strcmpstart(conn->requested_resource, fp_pfx)) {
  746. /* Download by fingerprint case */
  747. dir_split_resource_into_fingerprints(conn->requested_resource +
  748. strlen(fp_pfx),
  749. failed, NULL, DSR_HEX);
  750. SMARTLIST_FOREACH_BEGIN(failed, char *, cp) {
  751. /* Null signing key digest indicates download by fp only */
  752. authority_cert_dl_failed(cp, NULL, status);
  753. tor_free(cp);
  754. } SMARTLIST_FOREACH_END(cp);
  755. } else if (!strcmpstart(conn->requested_resource, fpsk_pfx)) {
  756. /* Download by (fp,sk) pairs */
  757. dir_split_resource_into_fingerprint_pairs(conn->requested_resource +
  758. strlen(fpsk_pfx), failed);
  759. SMARTLIST_FOREACH_BEGIN(failed, fp_pair_t *, cp) {
  760. authority_cert_dl_failed(cp->first, cp->second, status);
  761. tor_free(cp);
  762. } SMARTLIST_FOREACH_END(cp);
  763. } else {
  764. log_warn(LD_DIR,
  765. "Don't know what to do with failure for cert fetch %s",
  766. conn->requested_resource);
  767. }
  768. smartlist_free(failed);
  769. update_certificate_downloads(time(NULL));
  770. }
  771. /** Evaluate the situation and decide if we should use an encrypted
  772. * "begindir-style" connection for this directory request.
  773. * 1) If or_port is 0, or it's a direct conn and or_port is firewalled
  774. * or we're a dir mirror, no.
  775. * 2) If we prefer to avoid begindir conns, and we're not fetching or
  776. * publishing a bridge relay descriptor, no.
  777. * 3) Else yes.
  778. */
  779. static int
  780. directory_command_should_use_begindir(const or_options_t *options,
  781. const tor_addr_t *addr,
  782. int or_port, uint8_t router_purpose,
  783. dir_indirection_t indirection)
  784. {
  785. (void) router_purpose;
  786. if (!or_port)
  787. return 0; /* We don't know an ORPort -- no chance. */
  788. if (indirection == DIRIND_DIRECT_CONN || indirection == DIRIND_ANON_DIRPORT)
  789. return 0;
  790. if (indirection == DIRIND_ONEHOP)
  791. if (!fascist_firewall_allows_address_or(addr, or_port) ||
  792. directory_fetches_from_authorities(options))
  793. return 0; /* We're firewalled or are acting like a relay -- also no. */
  794. return 1;
  795. }
  796. /** Helper for directory_initiate_command_routerstatus: send the
  797. * command to a server whose address is <b>address</b>, whose IP is
  798. * <b>addr</b>, whose directory port is <b>dir_port</b>, whose tor version
  799. * <b>supports_begindir</b>, and whose identity key digest is
  800. * <b>digest</b>. */
  801. void
  802. directory_initiate_command(const tor_addr_t *_addr,
  803. uint16_t or_port, uint16_t dir_port,
  804. const char *digest,
  805. uint8_t dir_purpose, uint8_t router_purpose,
  806. dir_indirection_t indirection, const char *resource,
  807. const char *payload, size_t payload_len,
  808. time_t if_modified_since)
  809. {
  810. directory_initiate_command_rend(_addr, or_port, dir_port,
  811. digest, dir_purpose,
  812. router_purpose, indirection,
  813. resource, payload, payload_len,
  814. if_modified_since, NULL);
  815. }
  816. /** Return non-zero iff a directory connection with purpose
  817. * <b>dir_purpose</b> reveals sensitive information about a Tor
  818. * instance's client activities. (Such connections must be performed
  819. * through normal three-hop Tor circuits.) */
  820. static int
  821. is_sensitive_dir_purpose(uint8_t dir_purpose)
  822. {
  823. return ((dir_purpose == DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2) ||
  824. (dir_purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2) ||
  825. (dir_purpose == DIR_PURPOSE_FETCH_RENDDESC_V2));
  826. }
  827. /** Same as directory_initiate_command(), but accepts rendezvous data to
  828. * fetch a hidden service descriptor. */
  829. static void
  830. directory_initiate_command_rend(const tor_addr_t *_addr,
  831. uint16_t or_port, uint16_t dir_port,
  832. const char *digest,
  833. uint8_t dir_purpose, uint8_t router_purpose,
  834. dir_indirection_t indirection,
  835. const char *resource,
  836. const char *payload, size_t payload_len,
  837. time_t if_modified_since,
  838. const rend_data_t *rend_query)
  839. {
  840. dir_connection_t *conn;
  841. const or_options_t *options = get_options();
  842. int socket_error = 0;
  843. int use_begindir = directory_command_should_use_begindir(options, _addr,
  844. or_port, router_purpose, indirection);
  845. const int anonymized_connection = dirind_is_anon(indirection);
  846. tor_addr_t addr;
  847. tor_assert(_addr);
  848. tor_assert(or_port || dir_port);
  849. tor_assert(digest);
  850. tor_addr_copy(&addr, _addr);
  851. log_debug(LD_DIR, "anonymized %d, use_begindir %d.",
  852. anonymized_connection, use_begindir);
  853. log_debug(LD_DIR, "Initiating %s", dir_conn_purpose_to_string(dir_purpose));
  854. #ifndef NON_ANONYMOUS_MODE_ENABLED
  855. tor_assert(!(is_sensitive_dir_purpose(dir_purpose) &&
  856. !anonymized_connection));
  857. #else
  858. (void)is_sensitive_dir_purpose;
  859. #endif
  860. /* ensure that we don't make direct connections when a SOCKS server is
  861. * configured. */
  862. if (!anonymized_connection && !use_begindir && !options->HTTPProxy &&
  863. (options->Socks4Proxy || options->Socks5Proxy)) {
  864. log_warn(LD_DIR, "Cannot connect to a directory server through a "
  865. "SOCKS proxy!");
  866. return;
  867. }
  868. conn = dir_connection_new(tor_addr_family(&addr));
  869. /* set up conn so it's got all the data we need to remember */
  870. tor_addr_copy(&conn->base_.addr, &addr);
  871. conn->base_.port = use_begindir ? or_port : dir_port;
  872. conn->base_.address = tor_dup_addr(&addr);
  873. memcpy(conn->identity_digest, digest, DIGEST_LEN);
  874. conn->base_.purpose = dir_purpose;
  875. conn->router_purpose = router_purpose;
  876. /* give it an initial state */
  877. conn->base_.state = DIR_CONN_STATE_CONNECTING;
  878. /* decide whether we can learn our IP address from this conn */
  879. /* XXXX This is a bad name for this field now. */
  880. conn->dirconn_direct = !anonymized_connection;
  881. /* copy rendezvous data, if any */
  882. if (rend_query)
  883. conn->rend_data = rend_data_dup(rend_query);
  884. if (!anonymized_connection && !use_begindir) {
  885. /* then we want to connect to dirport directly */
  886. if (options->HTTPProxy) {
  887. tor_addr_copy(&addr, &options->HTTPProxyAddr);
  888. dir_port = options->HTTPProxyPort;
  889. }
  890. switch (connection_connect(TO_CONN(conn), conn->base_.address, &addr,
  891. dir_port, &socket_error)) {
  892. case -1:
  893. connection_dir_request_failed(conn); /* retry if we want */
  894. /* XXX we only pass 'conn' above, not 'resource', 'payload',
  895. * etc. So in many situations it can't retry! -RD */
  896. connection_free(TO_CONN(conn));
  897. return;
  898. case 1:
  899. /* start flushing conn */
  900. conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
  901. /* fall through */
  902. case 0:
  903. /* queue the command on the outbuf */
  904. directory_send_command(conn, dir_purpose, 1, resource,
  905. payload, payload_len,
  906. if_modified_since);
  907. connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
  908. /* writable indicates finish, readable indicates broken link,
  909. error indicates broken link in windowsland. */
  910. }
  911. } else { /* we want to connect via a tor connection */
  912. entry_connection_t *linked_conn;
  913. /* Anonymized tunneled connections can never share a circuit.
  914. * One-hop directory connections can share circuits with each other
  915. * but nothing else. */
  916. int iso_flags = anonymized_connection ? ISO_STREAM : ISO_SESSIONGRP;
  917. /* If it's an anonymized connection, remember the fact that we
  918. * wanted it for later: maybe we'll want it again soon. */
  919. if (anonymized_connection && use_begindir)
  920. rep_hist_note_used_internal(time(NULL), 0, 1);
  921. else if (anonymized_connection && !use_begindir)
  922. rep_hist_note_used_port(time(NULL), conn->base_.port);
  923. /* make an AP connection
  924. * populate it and add it at the right state
  925. * hook up both sides
  926. */
  927. linked_conn =
  928. connection_ap_make_link(TO_CONN(conn),
  929. conn->base_.address, conn->base_.port,
  930. digest,
  931. SESSION_GROUP_DIRCONN, iso_flags,
  932. use_begindir, conn->dirconn_direct);
  933. if (!linked_conn) {
  934. log_warn(LD_NET,"Making tunnel to dirserver failed.");
  935. connection_mark_for_close(TO_CONN(conn));
  936. return;
  937. }
  938. if (connection_add(TO_CONN(conn)) < 0) {
  939. log_warn(LD_NET,"Unable to add connection for link to dirserver.");
  940. connection_mark_for_close(TO_CONN(conn));
  941. return;
  942. }
  943. conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
  944. /* queue the command on the outbuf */
  945. directory_send_command(conn, dir_purpose, 0, resource,
  946. payload, payload_len,
  947. if_modified_since);
  948. connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
  949. IF_HAS_BUFFEREVENT(ENTRY_TO_CONN(linked_conn), {
  950. connection_watch_events(ENTRY_TO_CONN(linked_conn),
  951. READ_EVENT|WRITE_EVENT);
  952. }) ELSE_IF_NO_BUFFEREVENT
  953. connection_start_reading(ENTRY_TO_CONN(linked_conn));
  954. }
  955. }
  956. /** Return true iff anything we say on <b>conn</b> is being encrypted before
  957. * we send it to the client/server. */
  958. int
  959. connection_dir_is_encrypted(dir_connection_t *conn)
  960. {
  961. /* Right now it's sufficient to see if conn is or has been linked, since
  962. * the only thing it could be linked to is an edge connection on a
  963. * circuit, and the only way it could have been unlinked is at the edge
  964. * connection getting closed.
  965. */
  966. return TO_CONN(conn)->linked;
  967. }
  968. /** Helper for sorting
  969. *
  970. * sort strings alphabetically
  971. */
  972. static int
  973. compare_strs_(const void **a, const void **b)
  974. {
  975. const char *s1 = *a, *s2 = *b;
  976. return strcmp(s1, s2);
  977. }
  978. #define CONDITIONAL_CONSENSUS_FPR_LEN 3
  979. #if (CONDITIONAL_CONSENSUS_FPR_LEN > DIGEST_LEN)
  980. #error "conditional consensus fingerprint length is larger than digest length"
  981. #endif
  982. /** Return the URL we should use for a consensus download.
  983. *
  984. * This url depends on whether or not the server we go to
  985. * is sufficiently new to support conditional consensus downloading,
  986. * i.e. GET .../consensus/<b>fpr</b>+<b>fpr</b>+<b>fpr</b>
  987. *
  988. * If 'resource' is provided, it is the name of a consensus flavor to request.
  989. */
  990. static char *
  991. directory_get_consensus_url(const char *resource)
  992. {
  993. char *url = NULL;
  994. const char *hyphen, *flavor;
  995. if (resource==NULL || strcmp(resource, "ns")==0) {
  996. flavor = ""; /* Request ns consensuses as "", so older servers will work*/
  997. hyphen = "";
  998. } else {
  999. flavor = resource;
  1000. hyphen = "-";
  1001. }
  1002. {
  1003. char *authority_id_list;
  1004. smartlist_t *authority_digests = smartlist_new();
  1005. SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
  1006. dir_server_t *, ds) {
  1007. char *hex;
  1008. if (!(ds->type & V3_DIRINFO))
  1009. continue;
  1010. hex = tor_malloc(2*CONDITIONAL_CONSENSUS_FPR_LEN+1);
  1011. base16_encode(hex, 2*CONDITIONAL_CONSENSUS_FPR_LEN+1,
  1012. ds->v3_identity_digest, CONDITIONAL_CONSENSUS_FPR_LEN);
  1013. smartlist_add(authority_digests, hex);
  1014. } SMARTLIST_FOREACH_END(ds);
  1015. smartlist_sort(authority_digests, compare_strs_);
  1016. authority_id_list = smartlist_join_strings(authority_digests,
  1017. "+", 0, NULL);
  1018. tor_asprintf(&url, "/tor/status-vote/current/consensus%s%s/%s.z",
  1019. hyphen, flavor, authority_id_list);
  1020. SMARTLIST_FOREACH(authority_digests, char *, cp, tor_free(cp));
  1021. smartlist_free(authority_digests);
  1022. tor_free(authority_id_list);
  1023. }
  1024. return url;
  1025. }
  1026. /** Queue an appropriate HTTP command on conn-\>outbuf. The other args
  1027. * are as in directory_initiate_command().
  1028. */
  1029. static void
  1030. directory_send_command(dir_connection_t *conn,
  1031. int purpose, int direct, const char *resource,
  1032. const char *payload, size_t payload_len,
  1033. time_t if_modified_since)
  1034. {
  1035. char proxystring[256];
  1036. char hoststring[128];
  1037. smartlist_t *headers = smartlist_new();
  1038. char *url;
  1039. char request[8192];
  1040. const char *httpcommand = NULL;
  1041. tor_assert(conn);
  1042. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  1043. tor_free(conn->requested_resource);
  1044. if (resource)
  1045. conn->requested_resource = tor_strdup(resource);
  1046. /* come up with a string for which Host: we want */
  1047. if (conn->base_.port == 80) {
  1048. strlcpy(hoststring, conn->base_.address, sizeof(hoststring));
  1049. } else {
  1050. tor_snprintf(hoststring, sizeof(hoststring),"%s:%d",
  1051. conn->base_.address, conn->base_.port);
  1052. }
  1053. /* Format if-modified-since */
  1054. if (if_modified_since) {
  1055. char b[RFC1123_TIME_LEN+1];
  1056. format_rfc1123_time(b, if_modified_since);
  1057. smartlist_add_asprintf(headers, "If-Modified-Since: %s\r\n", b);
  1058. }
  1059. /* come up with some proxy lines, if we're using one. */
  1060. if (direct && get_options()->HTTPProxy) {
  1061. char *base64_authenticator=NULL;
  1062. const char *authenticator = get_options()->HTTPProxyAuthenticator;
  1063. tor_snprintf(proxystring, sizeof(proxystring),"http://%s", hoststring);
  1064. if (authenticator) {
  1065. base64_authenticator = alloc_http_authenticator(authenticator);
  1066. if (!base64_authenticator)
  1067. log_warn(LD_BUG, "Encoding http authenticator failed");
  1068. }
  1069. if (base64_authenticator) {
  1070. smartlist_add_asprintf(headers,
  1071. "Proxy-Authorization: Basic %s\r\n",
  1072. base64_authenticator);
  1073. tor_free(base64_authenticator);
  1074. }
  1075. } else {
  1076. proxystring[0] = 0;
  1077. }
  1078. switch (purpose) {
  1079. case DIR_PURPOSE_FETCH_CONSENSUS:
  1080. /* resource is optional. If present, it's a flavor name */
  1081. tor_assert(!payload);
  1082. httpcommand = "GET";
  1083. url = directory_get_consensus_url(resource);
  1084. log_info(LD_DIR, "Downloading consensus from %s using %s",
  1085. hoststring, url);
  1086. break;
  1087. case DIR_PURPOSE_FETCH_CERTIFICATE:
  1088. tor_assert(resource);
  1089. tor_assert(!payload);
  1090. httpcommand = "GET";
  1091. tor_asprintf(&url, "/tor/keys/%s", resource);
  1092. break;
  1093. case DIR_PURPOSE_FETCH_STATUS_VOTE:
  1094. tor_assert(resource);
  1095. tor_assert(!payload);
  1096. httpcommand = "GET";
  1097. tor_asprintf(&url, "/tor/status-vote/next/%s.z", resource);
  1098. break;
  1099. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
  1100. tor_assert(!resource);
  1101. tor_assert(!payload);
  1102. httpcommand = "GET";
  1103. url = tor_strdup("/tor/status-vote/next/consensus-signatures.z");
  1104. break;
  1105. case DIR_PURPOSE_FETCH_SERVERDESC:
  1106. tor_assert(resource);
  1107. httpcommand = "GET";
  1108. tor_asprintf(&url, "/tor/server/%s", resource);
  1109. break;
  1110. case DIR_PURPOSE_FETCH_EXTRAINFO:
  1111. tor_assert(resource);
  1112. httpcommand = "GET";
  1113. tor_asprintf(&url, "/tor/extra/%s", resource);
  1114. break;
  1115. case DIR_PURPOSE_FETCH_MICRODESC:
  1116. tor_assert(resource);
  1117. httpcommand = "GET";
  1118. tor_asprintf(&url, "/tor/micro/%s", resource);
  1119. break;
  1120. case DIR_PURPOSE_UPLOAD_DIR: {
  1121. const char *why = router_get_descriptor_gen_reason();
  1122. tor_assert(!resource);
  1123. tor_assert(payload);
  1124. httpcommand = "POST";
  1125. url = tor_strdup("/tor/");
  1126. if (why) {
  1127. smartlist_add_asprintf(headers, "X-Desc-Gen-Reason: %s\r\n", why);
  1128. }
  1129. break;
  1130. }
  1131. case DIR_PURPOSE_UPLOAD_VOTE:
  1132. tor_assert(!resource);
  1133. tor_assert(payload);
  1134. httpcommand = "POST";
  1135. url = tor_strdup("/tor/post/vote");
  1136. break;
  1137. case DIR_PURPOSE_UPLOAD_SIGNATURES:
  1138. tor_assert(!resource);
  1139. tor_assert(payload);
  1140. httpcommand = "POST";
  1141. url = tor_strdup("/tor/post/consensus-signature");
  1142. break;
  1143. case DIR_PURPOSE_FETCH_RENDDESC_V2:
  1144. tor_assert(resource);
  1145. tor_assert(strlen(resource) <= REND_DESC_ID_V2_LEN_BASE32);
  1146. tor_assert(!payload);
  1147. httpcommand = "GET";
  1148. tor_asprintf(&url, "/tor/rendezvous2/%s", resource);
  1149. break;
  1150. case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
  1151. tor_assert(!resource);
  1152. tor_assert(payload);
  1153. httpcommand = "POST";
  1154. url = tor_strdup("/tor/rendezvous2/publish");
  1155. break;
  1156. default:
  1157. tor_assert(0);
  1158. return;
  1159. }
  1160. if (strlen(proxystring) + strlen(url) >= 4096) {
  1161. log_warn(LD_BUG,
  1162. "Squid does not like URLs longer than 4095 bytes, and this "
  1163. "one is %d bytes long: %s%s",
  1164. (int)(strlen(proxystring) + strlen(url)), proxystring, url);
  1165. }
  1166. tor_snprintf(request, sizeof(request), "%s %s", httpcommand, proxystring);
  1167. connection_write_to_buf(request, strlen(request), TO_CONN(conn));
  1168. connection_write_to_buf(url, strlen(url), TO_CONN(conn));
  1169. tor_free(url);
  1170. if (!strcmp(httpcommand, "POST") || payload) {
  1171. smartlist_add_asprintf(headers, "Content-Length: %lu\r\n",
  1172. payload ? (unsigned long)payload_len : 0);
  1173. }
  1174. {
  1175. char *header = smartlist_join_strings(headers, "", 0, NULL);
  1176. tor_snprintf(request, sizeof(request), " HTTP/1.0\r\nHost: %s\r\n%s\r\n",
  1177. hoststring, header);
  1178. tor_free(header);
  1179. }
  1180. connection_write_to_buf(request, strlen(request), TO_CONN(conn));
  1181. if (payload) {
  1182. /* then send the payload afterwards too */
  1183. connection_write_to_buf(payload, payload_len, TO_CONN(conn));
  1184. }
  1185. SMARTLIST_FOREACH(headers, char *, h, tor_free(h));
  1186. smartlist_free(headers);
  1187. }
  1188. /** Parse an HTTP request string <b>headers</b> of the form
  1189. * \verbatim
  1190. * "\%s [http[s]://]\%s HTTP/1..."
  1191. * \endverbatim
  1192. * If it's well-formed, strdup the second \%s into *<b>url</b>, and
  1193. * nul-terminate it. If the url doesn't start with "/tor/", rewrite it
  1194. * so it does. Return 0.
  1195. * Otherwise, return -1.
  1196. */
  1197. STATIC int
  1198. parse_http_url(const char *headers, char **url)
  1199. {
  1200. char *s, *start, *tmp;
  1201. s = (char *)eat_whitespace_no_nl(headers);
  1202. if (!*s) return -1;
  1203. s = (char *)find_whitespace(s); /* get past GET/POST */
  1204. if (!*s) return -1;
  1205. s = (char *)eat_whitespace_no_nl(s);
  1206. if (!*s) return -1;
  1207. start = s; /* this is it, assuming it's valid */
  1208. s = (char *)find_whitespace(start);
  1209. if (!*s) return -1;
  1210. /* tolerate the http[s] proxy style of putting the hostname in the url */
  1211. if (s-start >= 4 && !strcmpstart(start,"http")) {
  1212. tmp = start + 4;
  1213. if (*tmp == 's')
  1214. tmp++;
  1215. if (s-tmp >= 3 && !strcmpstart(tmp,"://")) {
  1216. tmp = strchr(tmp+3, '/');
  1217. if (tmp && tmp < s) {
  1218. log_debug(LD_DIR,"Skipping over 'http[s]://hostname/' string");
  1219. start = tmp;
  1220. }
  1221. }
  1222. }
  1223. /* Check if the header is well formed (next sequence
  1224. * should be HTTP/1.X\r\n). Assumes we're supporting 1.0? */
  1225. {
  1226. unsigned minor_ver;
  1227. char ch;
  1228. char *e = (char *)eat_whitespace_no_nl(s);
  1229. if (2 != tor_sscanf(e, "HTTP/1.%u%c", &minor_ver, &ch)) {
  1230. return -1;
  1231. }
  1232. if (ch != '\r')
  1233. return -1;
  1234. }
  1235. if (s-start < 5 || strcmpstart(start,"/tor/")) { /* need to rewrite it */
  1236. *url = tor_malloc(s - start + 5);
  1237. strlcpy(*url,"/tor", s-start+5);
  1238. strlcat((*url)+4, start, s-start+1);
  1239. } else {
  1240. *url = tor_strndup(start, s-start);
  1241. }
  1242. return 0;
  1243. }
  1244. /** Return a copy of the first HTTP header in <b>headers</b> whose key is
  1245. * <b>which</b>. The key should be given with a terminating colon and space;
  1246. * this function copies everything after, up to but not including the
  1247. * following \\r\\n. */
  1248. static char *
  1249. http_get_header(const char *headers, const char *which)
  1250. {
  1251. const char *cp = headers;
  1252. while (cp) {
  1253. if (!strcasecmpstart(cp, which)) {
  1254. char *eos;
  1255. cp += strlen(which);
  1256. if ((eos = strchr(cp,'\r')))
  1257. return tor_strndup(cp, eos-cp);
  1258. else
  1259. return tor_strdup(cp);
  1260. }
  1261. cp = strchr(cp, '\n');
  1262. if (cp)
  1263. ++cp;
  1264. }
  1265. return NULL;
  1266. }
  1267. /** If <b>headers</b> indicates that a proxy was involved, then rewrite
  1268. * <b>conn</b>-\>address to describe our best guess of the address that
  1269. * originated this HTTP request. */
  1270. static void
  1271. http_set_address_origin(const char *headers, connection_t *conn)
  1272. {
  1273. char *fwd;
  1274. fwd = http_get_header(headers, "Forwarded-For: ");
  1275. if (!fwd)
  1276. fwd = http_get_header(headers, "X-Forwarded-For: ");
  1277. if (fwd) {
  1278. tor_addr_t toraddr;
  1279. if (tor_addr_parse(&toraddr,fwd) == -1 ||
  1280. tor_addr_is_internal(&toraddr,0)) {
  1281. log_debug(LD_DIR, "Ignoring local/internal IP %s", escaped(fwd));
  1282. tor_free(fwd);
  1283. return;
  1284. }
  1285. tor_free(conn->address);
  1286. conn->address = tor_strdup(fwd);
  1287. tor_free(fwd);
  1288. }
  1289. }
  1290. /** Parse an HTTP response string <b>headers</b> of the form
  1291. * \verbatim
  1292. * "HTTP/1.\%d \%d\%s\r\n...".
  1293. * \endverbatim
  1294. *
  1295. * If it's well-formed, assign the status code to *<b>code</b> and
  1296. * return 0. Otherwise, return -1.
  1297. *
  1298. * On success: If <b>date</b> is provided, set *date to the Date
  1299. * header in the http headers, or 0 if no such header is found. If
  1300. * <b>compression</b> is provided, set *<b>compression</b> to the
  1301. * compression method given in the Content-Encoding header, or 0 if no
  1302. * such header is found, or -1 if the value of the header is not
  1303. * recognized. If <b>reason</b> is provided, strdup the reason string
  1304. * into it.
  1305. */
  1306. int
  1307. parse_http_response(const char *headers, int *code, time_t *date,
  1308. compress_method_t *compression, char **reason)
  1309. {
  1310. unsigned n1, n2;
  1311. char datestr[RFC1123_TIME_LEN+1];
  1312. smartlist_t *parsed_headers;
  1313. tor_assert(headers);
  1314. tor_assert(code);
  1315. while (TOR_ISSPACE(*headers)) headers++; /* tolerate leading whitespace */
  1316. if (tor_sscanf(headers, "HTTP/1.%u %u", &n1, &n2) < 2 ||
  1317. (n1 != 0 && n1 != 1) ||
  1318. (n2 < 100 || n2 >= 600)) {
  1319. log_warn(LD_HTTP,"Failed to parse header %s",escaped(headers));
  1320. return -1;
  1321. }
  1322. *code = n2;
  1323. parsed_headers = smartlist_new();
  1324. smartlist_split_string(parsed_headers, headers, "\n",
  1325. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  1326. if (reason) {
  1327. smartlist_t *status_line_elements = smartlist_new();
  1328. tor_assert(smartlist_len(parsed_headers));
  1329. smartlist_split_string(status_line_elements,
  1330. smartlist_get(parsed_headers, 0),
  1331. " ", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  1332. tor_assert(smartlist_len(status_line_elements) <= 3);
  1333. if (smartlist_len(status_line_elements) == 3) {
  1334. *reason = smartlist_get(status_line_elements, 2);
  1335. smartlist_set(status_line_elements, 2, NULL); /* Prevent free */
  1336. }
  1337. SMARTLIST_FOREACH(status_line_elements, char *, cp, tor_free(cp));
  1338. smartlist_free(status_line_elements);
  1339. }
  1340. if (date) {
  1341. *date = 0;
  1342. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  1343. if (!strcmpstart(s, "Date: ")) {
  1344. strlcpy(datestr, s+6, sizeof(datestr));
  1345. /* This will do nothing on failure, so we don't need to check
  1346. the result. We shouldn't warn, since there are many other valid
  1347. date formats besides the one we use. */
  1348. parse_rfc1123_time(datestr, date);
  1349. break;
  1350. });
  1351. }
  1352. if (compression) {
  1353. const char *enc = NULL;
  1354. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  1355. if (!strcmpstart(s, "Content-Encoding: ")) {
  1356. enc = s+18; break;
  1357. });
  1358. if (!enc || !strcmp(enc, "identity")) {
  1359. *compression = NO_METHOD;
  1360. } else if (!strcmp(enc, "deflate") || !strcmp(enc, "x-deflate")) {
  1361. *compression = ZLIB_METHOD;
  1362. } else if (!strcmp(enc, "gzip") || !strcmp(enc, "x-gzip")) {
  1363. *compression = GZIP_METHOD;
  1364. } else {
  1365. log_info(LD_HTTP, "Unrecognized content encoding: %s. Trying to deal.",
  1366. escaped(enc));
  1367. *compression = UNKNOWN_METHOD;
  1368. }
  1369. }
  1370. SMARTLIST_FOREACH(parsed_headers, char *, s, tor_free(s));
  1371. smartlist_free(parsed_headers);
  1372. return 0;
  1373. }
  1374. /** Return true iff <b>body</b> doesn't start with a plausible router or
  1375. * network-status or microdescriptor opening. This is a sign of possible
  1376. * compression. */
  1377. static int
  1378. body_is_plausible(const char *body, size_t len, int purpose)
  1379. {
  1380. int i;
  1381. if (len == 0)
  1382. return 1; /* empty bodies don't need decompression */
  1383. if (len < 32)
  1384. return 0;
  1385. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  1386. return (!strcmpstart(body,"onion-key"));
  1387. }
  1388. if (1) {
  1389. if (!strcmpstart(body,"router") ||
  1390. !strcmpstart(body,"network-status"))
  1391. return 1;
  1392. for (i=0;i<32;++i) {
  1393. if (!TOR_ISPRINT(body[i]) && !TOR_ISSPACE(body[i]))
  1394. return 0;
  1395. }
  1396. }
  1397. return 1;
  1398. }
  1399. /** Called when we've just fetched a bunch of router descriptors in
  1400. * <b>body</b>. The list <b>which</b>, if present, holds digests for
  1401. * descriptors we requested: descriptor digests if <b>descriptor_digests</b>
  1402. * is true, or identity digests otherwise. Parse the descriptors, validate
  1403. * them, and annotate them as having purpose <b>purpose</b> and as having been
  1404. * downloaded from <b>source</b>.
  1405. *
  1406. * Return the number of routers actually added. */
  1407. static int
  1408. load_downloaded_routers(const char *body, smartlist_t *which,
  1409. int descriptor_digests,
  1410. int router_purpose,
  1411. const char *source)
  1412. {
  1413. char buf[256];
  1414. char time_buf[ISO_TIME_LEN+1];
  1415. int added = 0;
  1416. int general = router_purpose == ROUTER_PURPOSE_GENERAL;
  1417. format_iso_time(time_buf, time(NULL));
  1418. tor_assert(source);
  1419. if (tor_snprintf(buf, sizeof(buf),
  1420. "@downloaded-at %s\n"
  1421. "@source %s\n"
  1422. "%s%s%s", time_buf, escaped(source),
  1423. !general ? "@purpose " : "",
  1424. !general ? router_purpose_to_string(router_purpose) : "",
  1425. !general ? "\n" : "")<0)
  1426. return added;
  1427. added = router_load_routers_from_string(body, NULL, SAVED_NOWHERE, which,
  1428. descriptor_digests, buf);
  1429. if (general)
  1430. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  1431. count_loading_descriptors_progress());
  1432. return added;
  1433. }
  1434. /** We are a client, and we've finished reading the server's
  1435. * response. Parse it and act appropriately.
  1436. *
  1437. * If we're still happy with using this directory server in the future, return
  1438. * 0. Otherwise return -1; and the caller should consider trying the request
  1439. * again.
  1440. *
  1441. * The caller will take care of marking the connection for close.
  1442. */
  1443. static int
  1444. connection_dir_client_reached_eof(dir_connection_t *conn)
  1445. {
  1446. char *body;
  1447. char *headers;
  1448. char *reason = NULL;
  1449. size_t body_len = 0, orig_len = 0;
  1450. int status_code;
  1451. time_t date_header = 0;
  1452. long delta;
  1453. compress_method_t compression;
  1454. int plausible;
  1455. int skewed = 0;
  1456. int allow_partial = (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  1457. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
  1458. conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
  1459. int was_compressed = 0;
  1460. time_t now = time(NULL);
  1461. int src_code;
  1462. switch (connection_fetch_from_buf_http(TO_CONN(conn),
  1463. &headers, MAX_HEADERS_SIZE,
  1464. &body, &body_len, MAX_DIR_DL_SIZE,
  1465. allow_partial)) {
  1466. case -1: /* overflow */
  1467. log_warn(LD_PROTOCOL,
  1468. "'fetch' response too large (server '%s:%d'). Closing.",
  1469. conn->base_.address, conn->base_.port);
  1470. return -1;
  1471. case 0:
  1472. log_info(LD_HTTP,
  1473. "'fetch' response not all here, but we're at eof. Closing.");
  1474. return -1;
  1475. /* case 1, fall through */
  1476. }
  1477. orig_len = body_len;
  1478. if (parse_http_response(headers, &status_code, &date_header,
  1479. &compression, &reason) < 0) {
  1480. log_warn(LD_HTTP,"Unparseable headers (server '%s:%d'). Closing.",
  1481. conn->base_.address, conn->base_.port);
  1482. tor_free(body); tor_free(headers);
  1483. return -1;
  1484. }
  1485. if (!reason) reason = tor_strdup("[no reason given]");
  1486. log_debug(LD_DIR,
  1487. "Received response from directory server '%s:%d': %d %s "
  1488. "(purpose: %d)",
  1489. conn->base_.address, conn->base_.port, status_code,
  1490. escaped(reason),
  1491. conn->base_.purpose);
  1492. /* now check if it's got any hints for us about our IP address. */
  1493. if (conn->dirconn_direct) {
  1494. char *guess = http_get_header(headers, X_ADDRESS_HEADER);
  1495. if (guess) {
  1496. router_new_address_suggestion(guess, conn);
  1497. tor_free(guess);
  1498. }
  1499. }
  1500. if (date_header > 0) {
  1501. /* The date header was written very soon after we sent our request,
  1502. * so compute the skew as the difference between sending the request
  1503. * and the date header. (We used to check now-date_header, but that's
  1504. * inaccurate if we spend a lot of time downloading.)
  1505. */
  1506. delta = conn->base_.timestamp_lastwritten - date_header;
  1507. if (labs(delta)>ALLOW_DIRECTORY_TIME_SKEW) {
  1508. char dbuf[64];
  1509. int trusted = router_digest_is_trusted_dir(conn->identity_digest);
  1510. format_time_interval(dbuf, sizeof(dbuf), delta);
  1511. log_fn(trusted ? LOG_WARN : LOG_INFO,
  1512. LD_HTTP,
  1513. "Received directory with skewed time (server '%s:%d'): "
  1514. "It seems that our clock is %s by %s, or that theirs is %s. "
  1515. "Tor requires an accurate clock to work: please check your time, "
  1516. "timezone, and date settings.",
  1517. conn->base_.address, conn->base_.port,
  1518. delta>0 ? "ahead" : "behind", dbuf,
  1519. delta>0 ? "behind" : "ahead");
  1520. skewed = 1; /* don't check the recommended-versions line */
  1521. if (trusted)
  1522. control_event_general_status(LOG_WARN,
  1523. "CLOCK_SKEW SKEW=%ld SOURCE=DIRSERV:%s:%d",
  1524. delta, conn->base_.address, conn->base_.port);
  1525. } else {
  1526. log_debug(LD_HTTP, "Time on received directory is within tolerance; "
  1527. "we are %ld seconds skewed. (That's okay.)", delta);
  1528. }
  1529. }
  1530. (void) skewed; /* skewed isn't used yet. */
  1531. if (status_code == 503) {
  1532. routerstatus_t *rs;
  1533. dir_server_t *ds;
  1534. const char *id_digest = conn->identity_digest;
  1535. log_info(LD_DIR,"Received http status code %d (%s) from server "
  1536. "'%s:%d'. I'll try again soon.",
  1537. status_code, escaped(reason), conn->base_.address,
  1538. conn->base_.port);
  1539. if ((rs = router_get_mutable_consensus_status_by_id(id_digest)))
  1540. rs->last_dir_503_at = now;
  1541. if ((ds = router_get_fallback_dirserver_by_digest(id_digest)))
  1542. ds->fake_status.last_dir_503_at = now;
  1543. tor_free(body); tor_free(headers); tor_free(reason);
  1544. return -1;
  1545. }
  1546. plausible = body_is_plausible(body, body_len, conn->base_.purpose);
  1547. if (compression != NO_METHOD || !plausible) {
  1548. char *new_body = NULL;
  1549. size_t new_len = 0;
  1550. compress_method_t guessed = detect_compression_method(body, body_len);
  1551. if (compression == UNKNOWN_METHOD || guessed != compression) {
  1552. /* Tell the user if we don't believe what we're told about compression.*/
  1553. const char *description1, *description2;
  1554. if (compression == ZLIB_METHOD)
  1555. description1 = "as deflated";
  1556. else if (compression == GZIP_METHOD)
  1557. description1 = "as gzipped";
  1558. else if (compression == NO_METHOD)
  1559. description1 = "as uncompressed";
  1560. else
  1561. description1 = "with an unknown Content-Encoding";
  1562. if (guessed == ZLIB_METHOD)
  1563. description2 = "deflated";
  1564. else if (guessed == GZIP_METHOD)
  1565. description2 = "gzipped";
  1566. else if (!plausible)
  1567. description2 = "confusing binary junk";
  1568. else
  1569. description2 = "uncompressed";
  1570. log_info(LD_HTTP, "HTTP body from server '%s:%d' was labeled %s, "
  1571. "but it seems to be %s.%s",
  1572. conn->base_.address, conn->base_.port, description1,
  1573. description2,
  1574. (compression>0 && guessed>0)?" Trying both.":"");
  1575. }
  1576. /* Try declared compression first if we can. */
  1577. if (compression == GZIP_METHOD || compression == ZLIB_METHOD)
  1578. tor_gzip_uncompress(&new_body, &new_len, body, body_len, compression,
  1579. !allow_partial, LOG_PROTOCOL_WARN);
  1580. /* Okay, if that didn't work, and we think that it was compressed
  1581. * differently, try that. */
  1582. if (!new_body &&
  1583. (guessed == GZIP_METHOD || guessed == ZLIB_METHOD) &&
  1584. compression != guessed)
  1585. tor_gzip_uncompress(&new_body, &new_len, body, body_len, guessed,
  1586. !allow_partial, LOG_PROTOCOL_WARN);
  1587. /* If we're pretty sure that we have a compressed directory, and
  1588. * we didn't manage to uncompress it, then warn and bail. */
  1589. if (!plausible && !new_body) {
  1590. log_fn(LOG_PROTOCOL_WARN, LD_HTTP,
  1591. "Unable to decompress HTTP body (server '%s:%d').",
  1592. conn->base_.address, conn->base_.port);
  1593. tor_free(body); tor_free(headers); tor_free(reason);
  1594. return -1;
  1595. }
  1596. if (new_body) {
  1597. tor_free(body);
  1598. body = new_body;
  1599. body_len = new_len;
  1600. was_compressed = 1;
  1601. }
  1602. }
  1603. if (conn->base_.purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
  1604. int r;
  1605. const char *flavname = conn->requested_resource;
  1606. if (status_code != 200) {
  1607. int severity = (status_code == 304) ? LOG_INFO : LOG_WARN;
  1608. tor_log(severity, LD_DIR,
  1609. "Received http status code %d (%s) from server "
  1610. "'%s:%d' while fetching consensus directory.",
  1611. status_code, escaped(reason), conn->base_.address,
  1612. conn->base_.port);
  1613. tor_free(body); tor_free(headers); tor_free(reason);
  1614. networkstatus_consensus_download_failed(status_code, flavname);
  1615. return -1;
  1616. }
  1617. log_info(LD_DIR,"Received consensus directory (size %d) from server "
  1618. "'%s:%d'", (int)body_len, conn->base_.address, conn->base_.port);
  1619. if ((r=networkstatus_set_current_consensus(body, flavname, 0))<0) {
  1620. log_fn(r<-1?LOG_WARN:LOG_INFO, LD_DIR,
  1621. "Unable to load %s consensus directory downloaded from "
  1622. "server '%s:%d'. I'll try again soon.",
  1623. flavname, conn->base_.address, conn->base_.port);
  1624. tor_free(body); tor_free(headers); tor_free(reason);
  1625. networkstatus_consensus_download_failed(0, flavname);
  1626. return -1;
  1627. }
  1628. /* launches router downloads as needed */
  1629. routers_update_all_from_networkstatus(now, 3);
  1630. update_microdescs_from_networkstatus(now);
  1631. update_microdesc_downloads(now);
  1632. directory_info_has_arrived(now, 0);
  1633. log_info(LD_DIR, "Successfully loaded consensus.");
  1634. }
  1635. if (conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE) {
  1636. if (status_code != 200) {
  1637. log_warn(LD_DIR,
  1638. "Received http status code %d (%s) from server "
  1639. "'%s:%d' while fetching \"/tor/keys/%s\".",
  1640. status_code, escaped(reason), conn->base_.address,
  1641. conn->base_.port, conn->requested_resource);
  1642. connection_dir_download_cert_failed(conn, status_code);
  1643. tor_free(body); tor_free(headers); tor_free(reason);
  1644. return -1;
  1645. }
  1646. log_info(LD_DIR,"Received authority certificates (size %d) from server "
  1647. "'%s:%d'", (int)body_len, conn->base_.address, conn->base_.port);
  1648. /*
  1649. * Tell trusted_dirs_load_certs_from_string() whether it was by fp
  1650. * or fp-sk pair.
  1651. */
  1652. src_code = -1;
  1653. if (!strcmpstart(conn->requested_resource, "fp/")) {
  1654. src_code = TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST;
  1655. } else if (!strcmpstart(conn->requested_resource, "fp-sk/")) {
  1656. src_code = TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_SK_DIGEST;
  1657. }
  1658. if (src_code != -1) {
  1659. if (trusted_dirs_load_certs_from_string(body, src_code, 1)<0) {
  1660. log_warn(LD_DIR, "Unable to parse fetched certificates");
  1661. /* if we fetched more than one and only some failed, the successful
  1662. * ones got flushed to disk so it's safe to call this on them */
  1663. connection_dir_download_cert_failed(conn, status_code);
  1664. } else {
  1665. directory_info_has_arrived(now, 0);
  1666. log_info(LD_DIR, "Successfully loaded certificates from fetch.");
  1667. }
  1668. } else {
  1669. log_warn(LD_DIR,
  1670. "Couldn't figure out what to do with fetched certificates for "
  1671. "unknown resource %s",
  1672. conn->requested_resource);
  1673. connection_dir_download_cert_failed(conn, status_code);
  1674. }
  1675. }
  1676. if (conn->base_.purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) {
  1677. const char *msg;
  1678. int st;
  1679. log_info(LD_DIR,"Got votes (size %d) from server %s:%d",
  1680. (int)body_len, conn->base_.address, conn->base_.port);
  1681. if (status_code != 200) {
  1682. log_warn(LD_DIR,
  1683. "Received http status code %d (%s) from server "
  1684. "'%s:%d' while fetching \"/tor/status-vote/next/%s.z\".",
  1685. status_code, escaped(reason), conn->base_.address,
  1686. conn->base_.port, conn->requested_resource);
  1687. tor_free(body); tor_free(headers); tor_free(reason);
  1688. return -1;
  1689. }
  1690. dirvote_add_vote(body, &msg, &st);
  1691. if (st > 299) {
  1692. log_warn(LD_DIR, "Error adding retrieved vote: %s", msg);
  1693. } else {
  1694. log_info(LD_DIR, "Added vote(s) successfully [msg: %s]", msg);
  1695. }
  1696. }
  1697. if (conn->base_.purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES) {
  1698. const char *msg = NULL;
  1699. log_info(LD_DIR,"Got detached signatures (size %d) from server %s:%d",
  1700. (int)body_len, conn->base_.address, conn->base_.port);
  1701. if (status_code != 200) {
  1702. log_warn(LD_DIR,
  1703. "Received http status code %d (%s) from server '%s:%d' while fetching "
  1704. "\"/tor/status-vote/next/consensus-signatures.z\".",
  1705. status_code, escaped(reason), conn->base_.address,
  1706. conn->base_.port);
  1707. tor_free(body); tor_free(headers); tor_free(reason);
  1708. return -1;
  1709. }
  1710. if (dirvote_add_signatures(body, conn->base_.address, &msg)<0) {
  1711. log_warn(LD_DIR, "Problem adding detached signatures from %s:%d: %s",
  1712. conn->base_.address, conn->base_.port, msg?msg:"???");
  1713. }
  1714. }
  1715. if (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  1716. conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO) {
  1717. int was_ei = conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO;
  1718. smartlist_t *which = NULL;
  1719. int n_asked_for = 0;
  1720. int descriptor_digests = conn->requested_resource &&
  1721. !strcmpstart(conn->requested_resource,"d/");
  1722. log_info(LD_DIR,"Received %s (size %d) from server '%s:%d'",
  1723. was_ei ? "extra server info" : "server info",
  1724. (int)body_len, conn->base_.address, conn->base_.port);
  1725. if (conn->requested_resource &&
  1726. (!strcmpstart(conn->requested_resource,"d/") ||
  1727. !strcmpstart(conn->requested_resource,"fp/"))) {
  1728. which = smartlist_new();
  1729. dir_split_resource_into_fingerprints(conn->requested_resource +
  1730. (descriptor_digests ? 2 : 3),
  1731. which, NULL, 0);
  1732. n_asked_for = smartlist_len(which);
  1733. }
  1734. if (status_code != 200) {
  1735. int dir_okay = status_code == 404 ||
  1736. (status_code == 400 && !strcmp(reason, "Servers unavailable."));
  1737. /* 404 means that it didn't have them; no big deal.
  1738. * Older (pre-0.1.1.8) servers said 400 Servers unavailable instead. */
  1739. log_fn(dir_okay ? LOG_INFO : LOG_WARN, LD_DIR,
  1740. "Received http status code %d (%s) from server '%s:%d' "
  1741. "while fetching \"/tor/server/%s\". I'll try again soon.",
  1742. status_code, escaped(reason), conn->base_.address,
  1743. conn->base_.port, conn->requested_resource);
  1744. if (!which) {
  1745. connection_dir_download_routerdesc_failed(conn);
  1746. } else {
  1747. dir_routerdesc_download_failed(which, status_code,
  1748. conn->router_purpose,
  1749. was_ei, descriptor_digests);
  1750. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  1751. smartlist_free(which);
  1752. }
  1753. tor_free(body); tor_free(headers); tor_free(reason);
  1754. return dir_okay ? 0 : -1;
  1755. }
  1756. /* Learn the routers, assuming we requested by fingerprint or "all"
  1757. * or "authority".
  1758. *
  1759. * We use "authority" to fetch our own descriptor for
  1760. * testing, and to fetch bridge descriptors for bootstrapping. Ignore
  1761. * the output of "authority" requests unless we are using bridges,
  1762. * since otherwise they'll be the response from reachability tests,
  1763. * and we don't really want to add that to our routerlist. */
  1764. if (which || (conn->requested_resource &&
  1765. (!strcmpstart(conn->requested_resource, "all") ||
  1766. (!strcmpstart(conn->requested_resource, "authority") &&
  1767. get_options()->UseBridges)))) {
  1768. /* as we learn from them, we remove them from 'which' */
  1769. if (was_ei) {
  1770. router_load_extrainfo_from_string(body, NULL, SAVED_NOWHERE, which,
  1771. descriptor_digests);
  1772. } else {
  1773. //router_load_routers_from_string(body, NULL, SAVED_NOWHERE, which,
  1774. // descriptor_digests, conn->router_purpose);
  1775. if (load_downloaded_routers(body, which, descriptor_digests,
  1776. conn->router_purpose,
  1777. conn->base_.address))
  1778. directory_info_has_arrived(now, 0);
  1779. }
  1780. }
  1781. if (which) { /* mark remaining ones as failed */
  1782. log_info(LD_DIR, "Received %d/%d %s requested from %s:%d",
  1783. n_asked_for-smartlist_len(which), n_asked_for,
  1784. was_ei ? "extra-info documents" : "router descriptors",
  1785. conn->base_.address, (int)conn->base_.port);
  1786. if (smartlist_len(which)) {
  1787. dir_routerdesc_download_failed(which, status_code,
  1788. conn->router_purpose,
  1789. was_ei, descriptor_digests);
  1790. }
  1791. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  1792. smartlist_free(which);
  1793. }
  1794. if (directory_conn_is_self_reachability_test(conn))
  1795. router_dirport_found_reachable();
  1796. }
  1797. if (conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  1798. smartlist_t *which = NULL;
  1799. log_info(LD_DIR,"Received answer to microdescriptor request (status %d, "
  1800. "size %d) from server '%s:%d'",
  1801. status_code, (int)body_len, conn->base_.address,
  1802. conn->base_.port);
  1803. tor_assert(conn->requested_resource &&
  1804. !strcmpstart(conn->requested_resource, "d/"));
  1805. which = smartlist_new();
  1806. dir_split_resource_into_fingerprints(conn->requested_resource+2,
  1807. which, NULL,
  1808. DSR_DIGEST256|DSR_BASE64);
  1809. if (status_code != 200) {
  1810. log_info(LD_DIR, "Received status code %d (%s) from server "
  1811. "'%s:%d' while fetching \"/tor/micro/%s\". I'll try again "
  1812. "soon.",
  1813. status_code, escaped(reason), conn->base_.address,
  1814. (int)conn->base_.port, conn->requested_resource);
  1815. dir_microdesc_download_failed(which, status_code);
  1816. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  1817. smartlist_free(which);
  1818. tor_free(body); tor_free(headers); tor_free(reason);
  1819. return 0;
  1820. } else {
  1821. smartlist_t *mds;
  1822. mds = microdescs_add_to_cache(get_microdesc_cache(),
  1823. body, body+body_len, SAVED_NOWHERE, 0,
  1824. now, which);
  1825. if (smartlist_len(which)) {
  1826. /* Mark remaining ones as failed. */
  1827. dir_microdesc_download_failed(which, status_code);
  1828. }
  1829. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  1830. count_loading_descriptors_progress());
  1831. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  1832. smartlist_free(which);
  1833. smartlist_free(mds);
  1834. }
  1835. }
  1836. if (conn->base_.purpose == DIR_PURPOSE_UPLOAD_DIR) {
  1837. switch (status_code) {
  1838. case 200: {
  1839. dir_server_t *ds =
  1840. router_get_trusteddirserver_by_digest(conn->identity_digest);
  1841. char *rejected_hdr = http_get_header(headers,
  1842. "X-Descriptor-Not-New: ");
  1843. if (rejected_hdr) {
  1844. if (!strcmp(rejected_hdr, "Yes")) {
  1845. log_info(LD_GENERAL,
  1846. "Authority '%s' declined our descriptor (not new)",
  1847. ds->nickname);
  1848. /* XXXX use this information; be sure to upload next one
  1849. * sooner. -NM */
  1850. /* XXXX023 On further thought, the task above implies that we're
  1851. * basing our regenerate-descriptor time on when we uploaded the
  1852. * last descriptor, not on the published time of the last
  1853. * descriptor. If those are different, that's a bad thing to
  1854. * do. -NM */
  1855. }
  1856. tor_free(rejected_hdr);
  1857. }
  1858. log_info(LD_GENERAL,"eof (status 200) after uploading server "
  1859. "descriptor: finished.");
  1860. control_event_server_status(
  1861. LOG_NOTICE, "ACCEPTED_SERVER_DESCRIPTOR DIRAUTH=%s:%d",
  1862. conn->base_.address, conn->base_.port);
  1863. ds->has_accepted_serverdesc = 1;
  1864. if (directories_have_accepted_server_descriptor())
  1865. control_event_server_status(LOG_NOTICE, "GOOD_SERVER_DESCRIPTOR");
  1866. }
  1867. break;
  1868. case 400:
  1869. log_warn(LD_GENERAL,"http status 400 (%s) response from "
  1870. "dirserver '%s:%d'. Please correct.",
  1871. escaped(reason), conn->base_.address, conn->base_.port);
  1872. control_event_server_status(LOG_WARN,
  1873. "BAD_SERVER_DESCRIPTOR DIRAUTH=%s:%d REASON=\"%s\"",
  1874. conn->base_.address, conn->base_.port, escaped(reason));
  1875. break;
  1876. default:
  1877. log_warn(LD_GENERAL,
  1878. "http status %d (%s) reason unexpected while uploading "
  1879. "descriptor to server '%s:%d').",
  1880. status_code, escaped(reason), conn->base_.address,
  1881. conn->base_.port);
  1882. break;
  1883. }
  1884. /* return 0 in all cases, since we don't want to mark any
  1885. * dirservers down just because they don't like us. */
  1886. }
  1887. if (conn->base_.purpose == DIR_PURPOSE_UPLOAD_VOTE) {
  1888. switch (status_code) {
  1889. case 200: {
  1890. log_notice(LD_DIR,"Uploaded a vote to dirserver %s:%d",
  1891. conn->base_.address, conn->base_.port);
  1892. }
  1893. break;
  1894. case 400:
  1895. log_warn(LD_DIR,"http status 400 (%s) response after uploading "
  1896. "vote to dirserver '%s:%d'. Please correct.",
  1897. escaped(reason), conn->base_.address, conn->base_.port);
  1898. break;
  1899. default:
  1900. log_warn(LD_GENERAL,
  1901. "http status %d (%s) reason unexpected while uploading "
  1902. "vote to server '%s:%d').",
  1903. status_code, escaped(reason), conn->base_.address,
  1904. conn->base_.port);
  1905. break;
  1906. }
  1907. /* return 0 in all cases, since we don't want to mark any
  1908. * dirservers down just because they don't like us. */
  1909. }
  1910. if (conn->base_.purpose == DIR_PURPOSE_UPLOAD_SIGNATURES) {
  1911. switch (status_code) {
  1912. case 200: {
  1913. log_notice(LD_DIR,"Uploaded signature(s) to dirserver %s:%d",
  1914. conn->base_.address, conn->base_.port);
  1915. }
  1916. break;
  1917. case 400:
  1918. log_warn(LD_DIR,"http status 400 (%s) response after uploading "
  1919. "signatures to dirserver '%s:%d'. Please correct.",
  1920. escaped(reason), conn->base_.address, conn->base_.port);
  1921. break;
  1922. default:
  1923. log_warn(LD_GENERAL,
  1924. "http status %d (%s) reason unexpected while uploading "
  1925. "signatures to server '%s:%d').",
  1926. status_code, escaped(reason), conn->base_.address,
  1927. conn->base_.port);
  1928. break;
  1929. }
  1930. /* return 0 in all cases, since we don't want to mark any
  1931. * dirservers down just because they don't like us. */
  1932. }
  1933. if (conn->base_.purpose == DIR_PURPOSE_FETCH_RENDDESC_V2) {
  1934. #define SEND_HS_DESC_FAILED_EVENT() ( \
  1935. control_event_hs_descriptor_failed(conn->rend_data, \
  1936. conn->identity_digest) )
  1937. tor_assert(conn->rend_data);
  1938. log_info(LD_REND,"Received rendezvous descriptor (size %d, status %d "
  1939. "(%s))",
  1940. (int)body_len, status_code, escaped(reason));
  1941. switch (status_code) {
  1942. case 200:
  1943. switch (rend_cache_store_v2_desc_as_client(body, conn->rend_data)) {
  1944. case RCS_BADDESC:
  1945. case RCS_NOTDIR: /* Impossible */
  1946. log_warn(LD_REND,"Fetching v2 rendezvous descriptor failed. "
  1947. "Retrying at another directory.");
  1948. /* We'll retry when connection_about_to_close_connection()
  1949. * cleans this dir conn up. */
  1950. SEND_HS_DESC_FAILED_EVENT();
  1951. break;
  1952. case RCS_OKAY:
  1953. default:
  1954. /* success. notify pending connections about this. */
  1955. log_info(LD_REND, "Successfully fetched v2 rendezvous "
  1956. "descriptor.");
  1957. control_event_hs_descriptor_received(conn->rend_data,
  1958. conn->identity_digest);
  1959. conn->base_.purpose = DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2;
  1960. rend_client_desc_trynow(conn->rend_data->onion_address);
  1961. break;
  1962. }
  1963. break;
  1964. case 404:
  1965. /* Not there. We'll retry when
  1966. * connection_about_to_close_connection() cleans this conn up. */
  1967. log_info(LD_REND,"Fetching v2 rendezvous descriptor failed: "
  1968. "Retrying at another directory.");
  1969. SEND_HS_DESC_FAILED_EVENT();
  1970. break;
  1971. case 400:
  1972. log_warn(LD_REND, "Fetching v2 rendezvous descriptor failed: "
  1973. "http status 400 (%s). Dirserver didn't like our "
  1974. "v2 rendezvous query? Retrying at another directory.",
  1975. escaped(reason));
  1976. SEND_HS_DESC_FAILED_EVENT();
  1977. break;
  1978. default:
  1979. log_warn(LD_REND, "Fetching v2 rendezvous descriptor failed: "
  1980. "http status %d (%s) response unexpected while "
  1981. "fetching v2 hidden service descriptor (server '%s:%d'). "
  1982. "Retrying at another directory.",
  1983. status_code, escaped(reason), conn->base_.address,
  1984. conn->base_.port);
  1985. SEND_HS_DESC_FAILED_EVENT();
  1986. break;
  1987. }
  1988. }
  1989. if (conn->base_.purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2) {
  1990. log_info(LD_REND,"Uploaded rendezvous descriptor (status %d "
  1991. "(%s))",
  1992. status_code, escaped(reason));
  1993. switch (status_code) {
  1994. case 200:
  1995. log_info(LD_REND,
  1996. "Uploading rendezvous descriptor: finished with status "
  1997. "200 (%s)", escaped(reason));
  1998. break;
  1999. case 400:
  2000. log_warn(LD_REND,"http status 400 (%s) response from dirserver "
  2001. "'%s:%d'. Malformed rendezvous descriptor?",
  2002. escaped(reason), conn->base_.address, conn->base_.port);
  2003. break;
  2004. default:
  2005. log_warn(LD_REND,"http status %d (%s) response unexpected (server "
  2006. "'%s:%d').",
  2007. status_code, escaped(reason), conn->base_.address,
  2008. conn->base_.port);
  2009. break;
  2010. }
  2011. }
  2012. note_client_request(conn->base_.purpose, was_compressed, orig_len);
  2013. tor_free(body); tor_free(headers); tor_free(reason);
  2014. return 0;
  2015. }
  2016. /** Called when a directory connection reaches EOF. */
  2017. int
  2018. connection_dir_reached_eof(dir_connection_t *conn)
  2019. {
  2020. int retval;
  2021. if (conn->base_.state != DIR_CONN_STATE_CLIENT_READING) {
  2022. log_info(LD_HTTP,"conn reached eof, not reading. [state=%d] Closing.",
  2023. conn->base_.state);
  2024. connection_close_immediate(TO_CONN(conn)); /* error: give up on flushing */
  2025. connection_mark_for_close(TO_CONN(conn));
  2026. return -1;
  2027. }
  2028. retval = connection_dir_client_reached_eof(conn);
  2029. if (retval == 0) /* success */
  2030. conn->base_.state = DIR_CONN_STATE_CLIENT_FINISHED;
  2031. connection_mark_for_close(TO_CONN(conn));
  2032. return retval;
  2033. }
  2034. /** If any directory object is arriving, and it's over 10MB large, we're
  2035. * getting DoS'd. (As of 0.1.2.x, raw directories are about 1MB, and we never
  2036. * ask for more than 96 router descriptors at a time.)
  2037. */
  2038. #define MAX_DIRECTORY_OBJECT_SIZE (10*(1<<20))
  2039. /** Read handler for directory connections. (That's connections <em>to</em>
  2040. * directory servers and connections <em>at</em> directory servers.)
  2041. */
  2042. int
  2043. connection_dir_process_inbuf(dir_connection_t *conn)
  2044. {
  2045. tor_assert(conn);
  2046. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  2047. /* Directory clients write, then read data until they receive EOF;
  2048. * directory servers read data until they get an HTTP command, then
  2049. * write their response (when it's finished flushing, they mark for
  2050. * close).
  2051. */
  2052. /* If we're on the dirserver side, look for a command. */
  2053. if (conn->base_.state == DIR_CONN_STATE_SERVER_COMMAND_WAIT) {
  2054. if (directory_handle_command(conn) < 0) {
  2055. connection_mark_for_close(TO_CONN(conn));
  2056. return -1;
  2057. }
  2058. return 0;
  2059. }
  2060. if (connection_get_inbuf_len(TO_CONN(conn)) > MAX_DIRECTORY_OBJECT_SIZE) {
  2061. log_warn(LD_HTTP, "Too much data received from directory connection: "
  2062. "denial of service attempt, or you need to upgrade?");
  2063. connection_mark_for_close(TO_CONN(conn));
  2064. return -1;
  2065. }
  2066. if (!conn->base_.inbuf_reached_eof)
  2067. log_debug(LD_HTTP,"Got data, not eof. Leaving on inbuf.");
  2068. return 0;
  2069. }
  2070. /** Called when we're about to finally unlink and free a directory connection:
  2071. * perform necessary accounting and cleanup */
  2072. void
  2073. connection_dir_about_to_close(dir_connection_t *dir_conn)
  2074. {
  2075. connection_t *conn = TO_CONN(dir_conn);
  2076. if (conn->state < DIR_CONN_STATE_CLIENT_FINISHED) {
  2077. /* It's a directory connection and connecting or fetching
  2078. * failed: forget about this router, and maybe try again. */
  2079. connection_dir_request_failed(dir_conn);
  2080. }
  2081. /* If we were trying to fetch a v2 rend desc and did not succeed,
  2082. * retry as needed. (If a fetch is successful, the connection state
  2083. * is changed to DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2 to mark that
  2084. * refetching is unnecessary.) */
  2085. if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2 &&
  2086. dir_conn->rend_data &&
  2087. strlen(dir_conn->rend_data->onion_address) == REND_SERVICE_ID_LEN_BASE32)
  2088. rend_client_refetch_v2_renddesc(dir_conn->rend_data);
  2089. }
  2090. /** Create an http response for the client <b>conn</b> out of
  2091. * <b>status</b> and <b>reason_phrase</b>. Write it to <b>conn</b>.
  2092. */
  2093. static void
  2094. write_http_status_line(dir_connection_t *conn, int status,
  2095. const char *reason_phrase)
  2096. {
  2097. char buf[256];
  2098. if (tor_snprintf(buf, sizeof(buf), "HTTP/1.0 %d %s\r\n\r\n",
  2099. status, reason_phrase ? reason_phrase : "OK") < 0) {
  2100. log_warn(LD_BUG,"status line too long.");
  2101. return;
  2102. }
  2103. connection_write_to_buf(buf, strlen(buf), TO_CONN(conn));
  2104. }
  2105. /** Write the header for an HTTP/1.0 response onto <b>conn</b>-\>outbuf,
  2106. * with <b>type</b> as the Content-Type.
  2107. *
  2108. * If <b>length</b> is nonnegative, it is the Content-Length.
  2109. * If <b>encoding</b> is provided, it is the Content-Encoding.
  2110. * If <b>cache_lifetime</b> is greater than 0, the content may be cached for
  2111. * up to cache_lifetime seconds. Otherwise, the content may not be cached. */
  2112. static void
  2113. write_http_response_header_impl(dir_connection_t *conn, ssize_t length,
  2114. const char *type, const char *encoding,
  2115. const char *extra_headers,
  2116. long cache_lifetime)
  2117. {
  2118. char date[RFC1123_TIME_LEN+1];
  2119. char tmp[1024];
  2120. char *cp;
  2121. time_t now = time(NULL);
  2122. tor_assert(conn);
  2123. format_rfc1123_time(date, now);
  2124. cp = tmp;
  2125. tor_snprintf(cp, sizeof(tmp),
  2126. "HTTP/1.0 200 OK\r\nDate: %s\r\n",
  2127. date);
  2128. cp += strlen(tmp);
  2129. if (type) {
  2130. tor_snprintf(cp, sizeof(tmp)-(cp-tmp), "Content-Type: %s\r\n", type);
  2131. cp += strlen(cp);
  2132. }
  2133. if (!is_local_addr(&conn->base_.addr)) {
  2134. /* Don't report the source address for a nearby/private connection.
  2135. * Otherwise we tend to mis-report in cases where incoming ports are
  2136. * being forwarded to a Tor server running behind the firewall. */
  2137. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  2138. X_ADDRESS_HEADER "%s\r\n", conn->base_.address);
  2139. cp += strlen(cp);
  2140. }
  2141. if (encoding) {
  2142. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  2143. "Content-Encoding: %s\r\n", encoding);
  2144. cp += strlen(cp);
  2145. }
  2146. if (length >= 0) {
  2147. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  2148. "Content-Length: %ld\r\n", (long)length);
  2149. cp += strlen(cp);
  2150. }
  2151. if (cache_lifetime > 0) {
  2152. char expbuf[RFC1123_TIME_LEN+1];
  2153. format_rfc1123_time(expbuf, (time_t)(now + cache_lifetime));
  2154. /* We could say 'Cache-control: max-age=%d' here if we start doing
  2155. * http/1.1 */
  2156. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  2157. "Expires: %s\r\n", expbuf);
  2158. cp += strlen(cp);
  2159. } else if (cache_lifetime == 0) {
  2160. /* We could say 'Cache-control: no-cache' here if we start doing
  2161. * http/1.1 */
  2162. strlcpy(cp, "Pragma: no-cache\r\n", sizeof(tmp)-(cp-tmp));
  2163. cp += strlen(cp);
  2164. }
  2165. if (extra_headers) {
  2166. strlcpy(cp, extra_headers, sizeof(tmp)-(cp-tmp));
  2167. cp += strlen(cp);
  2168. }
  2169. if (sizeof(tmp)-(cp-tmp) > 3)
  2170. memcpy(cp, "\r\n", 3);
  2171. else
  2172. tor_assert(0);
  2173. connection_write_to_buf(tmp, strlen(tmp), TO_CONN(conn));
  2174. }
  2175. /** As write_http_response_header_impl, but sets encoding and content-typed
  2176. * based on whether the response will be <b>compressed</b> or not. */
  2177. static void
  2178. write_http_response_header(dir_connection_t *conn, ssize_t length,
  2179. int compressed, long cache_lifetime)
  2180. {
  2181. write_http_response_header_impl(conn, length,
  2182. compressed?"application/octet-stream":"text/plain",
  2183. compressed?"deflate":"identity",
  2184. NULL,
  2185. cache_lifetime);
  2186. }
  2187. #if defined(INSTRUMENT_DOWNLOADS) || defined(RUNNING_DOXYGEN)
  2188. /* DOCDOC */
  2189. typedef struct request_t {
  2190. uint64_t bytes; /**< How many bytes have we transferred? */
  2191. uint64_t count; /**< How many requests have we made? */
  2192. } request_t;
  2193. /** Map used to keep track of how much data we've up/downloaded in what kind
  2194. * of request. Maps from request type to pointer to request_t. */
  2195. static strmap_t *request_map = NULL;
  2196. /** Record that a client request of <b>purpose</b> was made, and that
  2197. * <b>bytes</b> bytes of possibly <b>compressed</b> data were sent/received.
  2198. * Used to keep track of how much we've up/downloaded in what kind of
  2199. * request. */
  2200. static void
  2201. note_client_request(int purpose, int compressed, size_t bytes)
  2202. {
  2203. char *key;
  2204. const char *kind = NULL;
  2205. switch (purpose) {
  2206. case DIR_PURPOSE_FETCH_CONSENSUS: kind = "dl/consensus"; break;
  2207. case DIR_PURPOSE_FETCH_CERTIFICATE: kind = "dl/cert"; break;
  2208. case DIR_PURPOSE_FETCH_STATUS_VOTE: kind = "dl/vote"; break;
  2209. case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES: kind = "dl/detached_sig";
  2210. break;
  2211. case DIR_PURPOSE_FETCH_SERVERDESC: kind = "dl/server"; break;
  2212. case DIR_PURPOSE_FETCH_EXTRAINFO: kind = "dl/extra"; break;
  2213. case DIR_PURPOSE_UPLOAD_DIR: kind = "dl/ul-dir"; break;
  2214. case DIR_PURPOSE_UPLOAD_VOTE: kind = "dl/ul-vote"; break;
  2215. case DIR_PURPOSE_UPLOAD_SIGNATURES: kind = "dl/ul-sig"; break;
  2216. case DIR_PURPOSE_FETCH_RENDDESC_V2: kind = "dl/rend2"; break;
  2217. case DIR_PURPOSE_UPLOAD_RENDDESC_V2: kind = "dl/ul-rend2"; break;
  2218. }
  2219. if (kind) {
  2220. tor_asprintf(&key, "%s%s", kind, compressed?".z":"");
  2221. } else {
  2222. tor_asprintf(&key, "unknown purpose (%d)%s",
  2223. purpose, compressed?".z":"");
  2224. }
  2225. note_request(key, bytes);
  2226. tor_free(key);
  2227. }
  2228. /** Helper: initialize the request map to instrument downloads. */
  2229. static void
  2230. ensure_request_map_initialized(void)
  2231. {
  2232. if (!request_map)
  2233. request_map = strmap_new();
  2234. }
  2235. /** Called when we just transmitted or received <b>bytes</b> worth of data
  2236. * because of a request of type <b>key</b> (an arbitrary identifier): adds
  2237. * <b>bytes</b> to the total associated with key. */
  2238. void
  2239. note_request(const char *key, size_t bytes)
  2240. {
  2241. request_t *r;
  2242. ensure_request_map_initialized();
  2243. r = strmap_get(request_map, key);
  2244. if (!r) {
  2245. r = tor_malloc_zero(sizeof(request_t));
  2246. strmap_set(request_map, key, r);
  2247. }
  2248. r->bytes += bytes;
  2249. r->count++;
  2250. }
  2251. /** Return a newly allocated string holding a summary of bytes used per
  2252. * request type. */
  2253. char *
  2254. directory_dump_request_log(void)
  2255. {
  2256. smartlist_t *lines;
  2257. char *result;
  2258. strmap_iter_t *iter;
  2259. ensure_request_map_initialized();
  2260. lines = smartlist_new();
  2261. for (iter = strmap_iter_init(request_map);
  2262. !strmap_iter_done(iter);
  2263. iter = strmap_iter_next(request_map, iter)) {
  2264. const char *key;
  2265. void *val;
  2266. request_t *r;
  2267. strmap_iter_get(iter, &key, &val);
  2268. r = val;
  2269. smartlist_add_asprintf(lines, "%s "U64_FORMAT" "U64_FORMAT"\n",
  2270. key, U64_PRINTF_ARG(r->bytes), U64_PRINTF_ARG(r->count));
  2271. }
  2272. smartlist_sort_strings(lines);
  2273. result = smartlist_join_strings(lines, "", 0, NULL);
  2274. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  2275. smartlist_free(lines);
  2276. return result;
  2277. }
  2278. #else
  2279. static void
  2280. note_client_request(int purpose, int compressed, size_t bytes)
  2281. {
  2282. (void)purpose;
  2283. (void)compressed;
  2284. (void)bytes;
  2285. }
  2286. void
  2287. note_request(const char *key, size_t bytes)
  2288. {
  2289. (void)key;
  2290. (void)bytes;
  2291. }
  2292. char *
  2293. directory_dump_request_log(void)
  2294. {
  2295. return tor_strdup("Not supported.");
  2296. }
  2297. #endif
  2298. /** Decide whether a client would accept the consensus we have.
  2299. *
  2300. * Clients can say they only want a consensus if it's signed by more
  2301. * than half the authorities in a list. They pass this list in
  2302. * the url as "...consensus/<b>fpr</b>+<b>fpr</b>+<b>fpr</b>".
  2303. *
  2304. * <b>fpr</b> may be an abbreviated fingerprint, i.e. only a left substring
  2305. * of the full authority identity digest. (Only strings of even length,
  2306. * i.e. encodings of full bytes, are handled correctly. In the case
  2307. * of an odd number of hex digits the last one is silently ignored.)
  2308. *
  2309. * Returns 1 if more than half of the requested authorities signed the
  2310. * consensus, 0 otherwise.
  2311. */
  2312. int
  2313. client_likes_consensus(networkstatus_t *v, const char *want_url)
  2314. {
  2315. smartlist_t *want_authorities = smartlist_new();
  2316. int need_at_least;
  2317. int have = 0;
  2318. dir_split_resource_into_fingerprints(want_url, want_authorities, NULL, 0);
  2319. need_at_least = smartlist_len(want_authorities)/2+1;
  2320. SMARTLIST_FOREACH_BEGIN(want_authorities, const char *, d) {
  2321. char want_digest[DIGEST_LEN];
  2322. size_t want_len = strlen(d)/2;
  2323. if (want_len > DIGEST_LEN)
  2324. want_len = DIGEST_LEN;
  2325. if (base16_decode(want_digest, DIGEST_LEN, d, want_len*2) < 0) {
  2326. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  2327. "Failed to decode requested authority digest %s.", escaped(d));
  2328. continue;
  2329. };
  2330. SMARTLIST_FOREACH_BEGIN(v->voters, networkstatus_voter_info_t *, vi) {
  2331. if (smartlist_len(vi->sigs) &&
  2332. tor_memeq(vi->identity_digest, want_digest, want_len)) {
  2333. have++;
  2334. break;
  2335. };
  2336. } SMARTLIST_FOREACH_END(vi);
  2337. /* early exit, if we already have enough */
  2338. if (have >= need_at_least)
  2339. break;
  2340. } SMARTLIST_FOREACH_END(d);
  2341. SMARTLIST_FOREACH(want_authorities, char *, d, tor_free(d));
  2342. smartlist_free(want_authorities);
  2343. return (have >= need_at_least);
  2344. }
  2345. /** Helper function: called when a dirserver gets a complete HTTP GET
  2346. * request. Look for a request for a directory or for a rendezvous
  2347. * service descriptor. On finding one, write a response into
  2348. * conn-\>outbuf. If the request is unrecognized, send a 400.
  2349. * Always return 0. */
  2350. static int
  2351. directory_handle_command_get(dir_connection_t *conn, const char *headers,
  2352. const char *req_body, size_t req_body_len)
  2353. {
  2354. size_t dlen;
  2355. char *url, *url_mem, *header;
  2356. const or_options_t *options = get_options();
  2357. time_t if_modified_since = 0;
  2358. int compressed;
  2359. size_t url_len;
  2360. /* We ignore the body of a GET request. */
  2361. (void)req_body;
  2362. (void)req_body_len;
  2363. log_debug(LD_DIRSERV,"Received GET command.");
  2364. conn->base_.state = DIR_CONN_STATE_SERVER_WRITING;
  2365. if (parse_http_url(headers, &url) < 0) {
  2366. write_http_status_line(conn, 400, "Bad request");
  2367. return 0;
  2368. }
  2369. if ((header = http_get_header(headers, "If-Modified-Since: "))) {
  2370. struct tm tm;
  2371. if (parse_http_time(header, &tm) == 0) {
  2372. if (tor_timegm(&tm, &if_modified_since)<0)
  2373. if_modified_since = 0;
  2374. }
  2375. /* The correct behavior on a malformed If-Modified-Since header is to
  2376. * act as if no If-Modified-Since header had been given. */
  2377. tor_free(header);
  2378. }
  2379. log_debug(LD_DIRSERV,"rewritten url as '%s'.", escaped(url));
  2380. url_mem = url;
  2381. url_len = strlen(url);
  2382. compressed = url_len > 2 && !strcmp(url+url_len-2, ".z");
  2383. if (compressed) {
  2384. url[url_len-2] = '\0';
  2385. url_len -= 2;
  2386. }
  2387. if (!strcmp(url,"/tor/")) {
  2388. const char *frontpage = get_dirportfrontpage();
  2389. if (frontpage) {
  2390. dlen = strlen(frontpage);
  2391. /* Let's return a disclaimer page (users shouldn't use V1 anymore,
  2392. and caches don't fetch '/', so this is safe). */
  2393. /* [We don't check for write_bucket_low here, since we want to serve
  2394. * this page no matter what.] */
  2395. note_request(url, dlen);
  2396. write_http_response_header_impl(conn, dlen, "text/html", "identity",
  2397. NULL, DIRPORTFRONTPAGE_CACHE_LIFETIME);
  2398. connection_write_to_buf(frontpage, dlen, TO_CONN(conn));
  2399. goto done;
  2400. }
  2401. /* if no disclaimer file, fall through and continue */
  2402. }
  2403. if (!strcmpstart(url, "/tor/status-vote/current/consensus")) {
  2404. /* v3 network status fetch. */
  2405. smartlist_t *dir_fps = smartlist_new();
  2406. const char *request_type = NULL;
  2407. long lifetime = NETWORKSTATUS_CACHE_LIFETIME;
  2408. if (1) {
  2409. networkstatus_t *v;
  2410. time_t now = time(NULL);
  2411. const char *want_fps = NULL;
  2412. char *flavor = NULL;
  2413. int flav = FLAV_NS;
  2414. #define CONSENSUS_URL_PREFIX "/tor/status-vote/current/consensus/"
  2415. #define CONSENSUS_FLAVORED_PREFIX "/tor/status-vote/current/consensus-"
  2416. /* figure out the flavor if any, and who we wanted to sign the thing */
  2417. if (!strcmpstart(url, CONSENSUS_FLAVORED_PREFIX)) {
  2418. const char *f, *cp;
  2419. f = url + strlen(CONSENSUS_FLAVORED_PREFIX);
  2420. cp = strchr(f, '/');
  2421. if (cp) {
  2422. want_fps = cp+1;
  2423. flavor = tor_strndup(f, cp-f);
  2424. } else {
  2425. flavor = tor_strdup(f);
  2426. }
  2427. flav = networkstatus_parse_flavor_name(flavor);
  2428. if (flav < 0)
  2429. flav = FLAV_NS;
  2430. } else {
  2431. if (!strcmpstart(url, CONSENSUS_URL_PREFIX))
  2432. want_fps = url+strlen(CONSENSUS_URL_PREFIX);
  2433. }
  2434. v = networkstatus_get_latest_consensus_by_flavor(flav);
  2435. if (v && want_fps &&
  2436. !client_likes_consensus(v, want_fps)) {
  2437. write_http_status_line(conn, 404, "Consensus not signed by sufficient "
  2438. "number of requested authorities");
  2439. smartlist_free(dir_fps);
  2440. geoip_note_ns_response(GEOIP_REJECT_NOT_ENOUGH_SIGS);
  2441. tor_free(flavor);
  2442. goto done;
  2443. }
  2444. {
  2445. char *fp = tor_malloc_zero(DIGEST_LEN);
  2446. if (flavor)
  2447. strlcpy(fp, flavor, DIGEST_LEN);
  2448. tor_free(flavor);
  2449. smartlist_add(dir_fps, fp);
  2450. }
  2451. request_type = compressed?"v3.z":"v3";
  2452. lifetime = (v && v->fresh_until > now) ? v->fresh_until - now : 0;
  2453. }
  2454. if (!smartlist_len(dir_fps)) { /* we failed to create/cache cp */
  2455. write_http_status_line(conn, 503, "Network status object unavailable");
  2456. smartlist_free(dir_fps);
  2457. geoip_note_ns_response(GEOIP_REJECT_UNAVAILABLE);
  2458. goto done;
  2459. }
  2460. if (!dirserv_remove_old_statuses(dir_fps, if_modified_since)) {
  2461. write_http_status_line(conn, 404, "Not found");
  2462. SMARTLIST_FOREACH(dir_fps, char *, cp, tor_free(cp));
  2463. smartlist_free(dir_fps);
  2464. geoip_note_ns_response(GEOIP_REJECT_NOT_FOUND);
  2465. goto done;
  2466. } else if (!smartlist_len(dir_fps)) {
  2467. write_http_status_line(conn, 304, "Not modified");
  2468. SMARTLIST_FOREACH(dir_fps, char *, cp, tor_free(cp));
  2469. smartlist_free(dir_fps);
  2470. geoip_note_ns_response(GEOIP_REJECT_NOT_MODIFIED);
  2471. goto done;
  2472. }
  2473. dlen = dirserv_estimate_data_size(dir_fps, 0, compressed);
  2474. if (global_write_bucket_low(TO_CONN(conn), dlen, 2)) {
  2475. log_debug(LD_DIRSERV,
  2476. "Client asked for network status lists, but we've been "
  2477. "writing too many bytes lately. Sending 503 Dir busy.");
  2478. write_http_status_line(conn, 503, "Directory busy, try again later");
  2479. SMARTLIST_FOREACH(dir_fps, char *, fp, tor_free(fp));
  2480. smartlist_free(dir_fps);
  2481. geoip_note_ns_response(GEOIP_REJECT_BUSY);
  2482. goto done;
  2483. }
  2484. if (1) {
  2485. struct in_addr in;
  2486. tor_addr_t addr;
  2487. if (tor_inet_aton((TO_CONN(conn))->address, &in)) {
  2488. tor_addr_from_ipv4h(&addr, ntohl(in.s_addr));
  2489. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS,
  2490. &addr, NULL,
  2491. time(NULL));
  2492. geoip_note_ns_response(GEOIP_SUCCESS);
  2493. /* Note that a request for a network status has started, so that we
  2494. * can measure the download time later on. */
  2495. if (conn->dirreq_id)
  2496. geoip_start_dirreq(conn->dirreq_id, dlen, DIRREQ_TUNNELED);
  2497. else
  2498. geoip_start_dirreq(TO_CONN(conn)->global_identifier, dlen,
  2499. DIRREQ_DIRECT);
  2500. }
  2501. }
  2502. // note_request(request_type,dlen);
  2503. (void) request_type;
  2504. write_http_response_header(conn, -1, compressed,
  2505. smartlist_len(dir_fps) == 1 ? lifetime : 0);
  2506. conn->fingerprint_stack = dir_fps;
  2507. if (! compressed)
  2508. conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
  2509. /* Prime the connection with some data. */
  2510. conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
  2511. connection_dirserv_flushed_some(conn);
  2512. goto done;
  2513. }
  2514. if (!strcmpstart(url,"/tor/status-vote/current/") ||
  2515. !strcmpstart(url,"/tor/status-vote/next/")) {
  2516. /* XXXX If-modified-since is only implemented for the current
  2517. * consensus: that's probably fine, since it's the only vote document
  2518. * people fetch much. */
  2519. int current;
  2520. ssize_t body_len = 0;
  2521. ssize_t estimated_len = 0;
  2522. smartlist_t *items = smartlist_new();
  2523. smartlist_t *dir_items = smartlist_new();
  2524. int lifetime = 60; /* XXXX023 should actually use vote intervals. */
  2525. url += strlen("/tor/status-vote/");
  2526. current = !strcmpstart(url, "current/");
  2527. url = strchr(url, '/');
  2528. tor_assert(url);
  2529. ++url;
  2530. if (!strcmp(url, "consensus")) {
  2531. const char *item;
  2532. tor_assert(!current); /* we handle current consensus specially above,
  2533. * since it wants to be spooled. */
  2534. if ((item = dirvote_get_pending_consensus(FLAV_NS)))
  2535. smartlist_add(items, (char*)item);
  2536. } else if (!current && !strcmp(url, "consensus-signatures")) {
  2537. /* XXXX the spec says that we should implement
  2538. * current/consensus-signatures too. It doesn't seem to be needed,
  2539. * though. */
  2540. const char *item;
  2541. if ((item=dirvote_get_pending_detached_signatures()))
  2542. smartlist_add(items, (char*)item);
  2543. } else if (!strcmp(url, "authority")) {
  2544. const cached_dir_t *d;
  2545. int flags = DGV_BY_ID |
  2546. (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
  2547. if ((d=dirvote_get_vote(NULL, flags)))
  2548. smartlist_add(dir_items, (cached_dir_t*)d);
  2549. } else {
  2550. const cached_dir_t *d;
  2551. smartlist_t *fps = smartlist_new();
  2552. int flags;
  2553. if (!strcmpstart(url, "d/")) {
  2554. url += 2;
  2555. flags = DGV_INCLUDE_PENDING | DGV_INCLUDE_PREVIOUS;
  2556. } else {
  2557. flags = DGV_BY_ID |
  2558. (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
  2559. }
  2560. dir_split_resource_into_fingerprints(url, fps, NULL,
  2561. DSR_HEX|DSR_SORT_UNIQ);
  2562. SMARTLIST_FOREACH(fps, char *, fp, {
  2563. if ((d = dirvote_get_vote(fp, flags)))
  2564. smartlist_add(dir_items, (cached_dir_t*)d);
  2565. tor_free(fp);
  2566. });
  2567. smartlist_free(fps);
  2568. }
  2569. if (!smartlist_len(dir_items) && !smartlist_len(items)) {
  2570. write_http_status_line(conn, 404, "Not found");
  2571. goto vote_done;
  2572. }
  2573. SMARTLIST_FOREACH(dir_items, cached_dir_t *, d,
  2574. body_len += compressed ? d->dir_z_len : d->dir_len);
  2575. estimated_len += body_len;
  2576. SMARTLIST_FOREACH(items, const char *, item, {
  2577. size_t ln = strlen(item);
  2578. if (compressed) {
  2579. estimated_len += ln/2;
  2580. } else {
  2581. body_len += ln; estimated_len += ln;
  2582. }
  2583. });
  2584. if (global_write_bucket_low(TO_CONN(conn), estimated_len, 2)) {
  2585. write_http_status_line(conn, 503, "Directory busy, try again later.");
  2586. goto vote_done;
  2587. }
  2588. write_http_response_header(conn, body_len ? body_len : -1, compressed,
  2589. lifetime);
  2590. if (smartlist_len(items)) {
  2591. if (compressed) {
  2592. conn->zlib_state = tor_zlib_new(1, ZLIB_METHOD);
  2593. SMARTLIST_FOREACH(items, const char *, c,
  2594. connection_write_to_buf_zlib(c, strlen(c), conn, 0));
  2595. connection_write_to_buf_zlib("", 0, conn, 1);
  2596. } else {
  2597. SMARTLIST_FOREACH(items, const char *, c,
  2598. connection_write_to_buf(c, strlen(c), TO_CONN(conn)));
  2599. }
  2600. } else {
  2601. SMARTLIST_FOREACH(dir_items, cached_dir_t *, d,
  2602. connection_write_to_buf(compressed ? d->dir_z : d->dir,
  2603. compressed ? d->dir_z_len : d->dir_len,
  2604. TO_CONN(conn)));
  2605. }
  2606. vote_done:
  2607. smartlist_free(items);
  2608. smartlist_free(dir_items);
  2609. goto done;
  2610. }
  2611. if (!strcmpstart(url, "/tor/micro/d/")) {
  2612. smartlist_t *fps = smartlist_new();
  2613. dir_split_resource_into_fingerprints(url+strlen("/tor/micro/d/"),
  2614. fps, NULL,
  2615. DSR_DIGEST256|DSR_BASE64|DSR_SORT_UNIQ);
  2616. if (!dirserv_have_any_microdesc(fps)) {
  2617. write_http_status_line(conn, 404, "Not found");
  2618. SMARTLIST_FOREACH(fps, char *, fp, tor_free(fp));
  2619. smartlist_free(fps);
  2620. goto done;
  2621. }
  2622. dlen = dirserv_estimate_microdesc_size(fps, compressed);
  2623. if (global_write_bucket_low(TO_CONN(conn), dlen, 2)) {
  2624. log_info(LD_DIRSERV,
  2625. "Client asked for server descriptors, but we've been "
  2626. "writing too many bytes lately. Sending 503 Dir busy.");
  2627. write_http_status_line(conn, 503, "Directory busy, try again later");
  2628. SMARTLIST_FOREACH(fps, char *, fp, tor_free(fp));
  2629. smartlist_free(fps);
  2630. goto done;
  2631. }
  2632. write_http_response_header(conn, -1, compressed, MICRODESC_CACHE_LIFETIME);
  2633. conn->dir_spool_src = DIR_SPOOL_MICRODESC;
  2634. conn->fingerprint_stack = fps;
  2635. if (compressed)
  2636. conn->zlib_state = tor_zlib_new(1, ZLIB_METHOD);
  2637. connection_dirserv_flushed_some(conn);
  2638. goto done;
  2639. }
  2640. if (!strcmpstart(url,"/tor/server/") ||
  2641. (!options->BridgeAuthoritativeDir &&
  2642. !options->BridgeRelay && !strcmpstart(url,"/tor/extra/"))) {
  2643. int res;
  2644. const char *msg;
  2645. const char *request_type = NULL;
  2646. int cache_lifetime = 0;
  2647. int is_extra = !strcmpstart(url,"/tor/extra/");
  2648. url += is_extra ? strlen("/tor/extra/") : strlen("/tor/server/");
  2649. conn->fingerprint_stack = smartlist_new();
  2650. res = dirserv_get_routerdesc_fingerprints(conn->fingerprint_stack, url,
  2651. &msg,
  2652. !connection_dir_is_encrypted(conn),
  2653. is_extra);
  2654. if (!strcmpstart(url, "fp/")) {
  2655. request_type = compressed?"/tor/server/fp.z":"/tor/server/fp";
  2656. if (smartlist_len(conn->fingerprint_stack) == 1)
  2657. cache_lifetime = ROUTERDESC_CACHE_LIFETIME;
  2658. } else if (!strcmpstart(url, "authority")) {
  2659. request_type = compressed?"/tor/server/authority.z":
  2660. "/tor/server/authority";
  2661. cache_lifetime = ROUTERDESC_CACHE_LIFETIME;
  2662. } else if (!strcmpstart(url, "all")) {
  2663. request_type = compressed?"/tor/server/all.z":"/tor/server/all";
  2664. cache_lifetime = FULL_DIR_CACHE_LIFETIME;
  2665. } else if (!strcmpstart(url, "d/")) {
  2666. request_type = compressed?"/tor/server/d.z":"/tor/server/d";
  2667. if (smartlist_len(conn->fingerprint_stack) == 1)
  2668. cache_lifetime = ROUTERDESC_BY_DIGEST_CACHE_LIFETIME;
  2669. } else {
  2670. request_type = "/tor/server/?";
  2671. }
  2672. (void) request_type; /* usable for note_request. */
  2673. if (!strcmpstart(url, "d/"))
  2674. conn->dir_spool_src =
  2675. is_extra ? DIR_SPOOL_EXTRA_BY_DIGEST : DIR_SPOOL_SERVER_BY_DIGEST;
  2676. else
  2677. conn->dir_spool_src =
  2678. is_extra ? DIR_SPOOL_EXTRA_BY_FP : DIR_SPOOL_SERVER_BY_FP;
  2679. if (!dirserv_have_any_serverdesc(conn->fingerprint_stack,
  2680. conn->dir_spool_src)) {
  2681. res = -1;
  2682. msg = "Not found";
  2683. }
  2684. if (res < 0)
  2685. write_http_status_line(conn, 404, msg);
  2686. else {
  2687. dlen = dirserv_estimate_data_size(conn->fingerprint_stack,
  2688. 1, compressed);
  2689. if (global_write_bucket_low(TO_CONN(conn), dlen, 2)) {
  2690. log_info(LD_DIRSERV,
  2691. "Client asked for server descriptors, but we've been "
  2692. "writing too many bytes lately. Sending 503 Dir busy.");
  2693. write_http_status_line(conn, 503, "Directory busy, try again later");
  2694. conn->dir_spool_src = DIR_SPOOL_NONE;
  2695. goto done;
  2696. }
  2697. write_http_response_header(conn, -1, compressed, cache_lifetime);
  2698. if (compressed)
  2699. conn->zlib_state = tor_zlib_new(1, ZLIB_METHOD);
  2700. /* Prime the connection with some data. */
  2701. connection_dirserv_flushed_some(conn);
  2702. }
  2703. goto done;
  2704. }
  2705. if (!strcmpstart(url,"/tor/keys/")) {
  2706. smartlist_t *certs = smartlist_new();
  2707. ssize_t len = -1;
  2708. if (!strcmp(url, "/tor/keys/all")) {
  2709. authority_cert_get_all(certs);
  2710. } else if (!strcmp(url, "/tor/keys/authority")) {
  2711. authority_cert_t *cert = get_my_v3_authority_cert();
  2712. if (cert)
  2713. smartlist_add(certs, cert);
  2714. } else if (!strcmpstart(url, "/tor/keys/fp/")) {
  2715. smartlist_t *fps = smartlist_new();
  2716. dir_split_resource_into_fingerprints(url+strlen("/tor/keys/fp/"),
  2717. fps, NULL,
  2718. DSR_HEX|DSR_SORT_UNIQ);
  2719. SMARTLIST_FOREACH(fps, char *, d, {
  2720. authority_cert_t *c = authority_cert_get_newest_by_id(d);
  2721. if (c) smartlist_add(certs, c);
  2722. tor_free(d);
  2723. });
  2724. smartlist_free(fps);
  2725. } else if (!strcmpstart(url, "/tor/keys/sk/")) {
  2726. smartlist_t *fps = smartlist_new();
  2727. dir_split_resource_into_fingerprints(url+strlen("/tor/keys/sk/"),
  2728. fps, NULL,
  2729. DSR_HEX|DSR_SORT_UNIQ);
  2730. SMARTLIST_FOREACH(fps, char *, d, {
  2731. authority_cert_t *c = authority_cert_get_by_sk_digest(d);
  2732. if (c) smartlist_add(certs, c);
  2733. tor_free(d);
  2734. });
  2735. smartlist_free(fps);
  2736. } else if (!strcmpstart(url, "/tor/keys/fp-sk/")) {
  2737. smartlist_t *fp_sks = smartlist_new();
  2738. dir_split_resource_into_fingerprint_pairs(url+strlen("/tor/keys/fp-sk/"),
  2739. fp_sks);
  2740. SMARTLIST_FOREACH(fp_sks, fp_pair_t *, pair, {
  2741. authority_cert_t *c = authority_cert_get_by_digests(pair->first,
  2742. pair->second);
  2743. if (c) smartlist_add(certs, c);
  2744. tor_free(pair);
  2745. });
  2746. smartlist_free(fp_sks);
  2747. } else {
  2748. write_http_status_line(conn, 400, "Bad request");
  2749. goto keys_done;
  2750. }
  2751. if (!smartlist_len(certs)) {
  2752. write_http_status_line(conn, 404, "Not found");
  2753. goto keys_done;
  2754. }
  2755. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  2756. if (c->cache_info.published_on < if_modified_since)
  2757. SMARTLIST_DEL_CURRENT(certs, c));
  2758. if (!smartlist_len(certs)) {
  2759. write_http_status_line(conn, 304, "Not modified");
  2760. goto keys_done;
  2761. }
  2762. len = 0;
  2763. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  2764. len += c->cache_info.signed_descriptor_len);
  2765. if (global_write_bucket_low(TO_CONN(conn), compressed?len/2:len, 2)) {
  2766. write_http_status_line(conn, 503, "Directory busy, try again later.");
  2767. goto keys_done;
  2768. }
  2769. write_http_response_header(conn, compressed?-1:len, compressed, 60*60);
  2770. if (compressed) {
  2771. conn->zlib_state = tor_zlib_new(1, ZLIB_METHOD);
  2772. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  2773. connection_write_to_buf_zlib(c->cache_info.signed_descriptor_body,
  2774. c->cache_info.signed_descriptor_len,
  2775. conn, 0));
  2776. connection_write_to_buf_zlib("", 0, conn, 1);
  2777. } else {
  2778. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  2779. connection_write_to_buf(c->cache_info.signed_descriptor_body,
  2780. c->cache_info.signed_descriptor_len,
  2781. TO_CONN(conn)));
  2782. }
  2783. keys_done:
  2784. smartlist_free(certs);
  2785. goto done;
  2786. }
  2787. if (options->HidServDirectoryV2 &&
  2788. connection_dir_is_encrypted(conn) &&
  2789. !strcmpstart(url,"/tor/rendezvous2/")) {
  2790. /* Handle v2 rendezvous descriptor fetch request. */
  2791. const char *descp;
  2792. const char *query = url + strlen("/tor/rendezvous2/");
  2793. if (strlen(query) == REND_DESC_ID_V2_LEN_BASE32) {
  2794. log_info(LD_REND, "Got a v2 rendezvous descriptor request for ID '%s'",
  2795. safe_str(escaped(query)));
  2796. switch (rend_cache_lookup_v2_desc_as_dir(query, &descp)) {
  2797. case 1: /* valid */
  2798. write_http_response_header(conn, strlen(descp), 0, 0);
  2799. connection_write_to_buf(descp, strlen(descp), TO_CONN(conn));
  2800. break;
  2801. case 0: /* well-formed but not present */
  2802. write_http_status_line(conn, 404, "Not found");
  2803. break;
  2804. case -1: /* not well-formed */
  2805. write_http_status_line(conn, 400, "Bad request");
  2806. break;
  2807. }
  2808. } else { /* not well-formed */
  2809. write_http_status_line(conn, 400, "Bad request");
  2810. }
  2811. goto done;
  2812. }
  2813. if (options->BridgeAuthoritativeDir &&
  2814. options->BridgePassword_AuthDigest_ &&
  2815. connection_dir_is_encrypted(conn) &&
  2816. !strcmp(url,"/tor/networkstatus-bridges")) {
  2817. char *status;
  2818. char digest[DIGEST256_LEN];
  2819. header = http_get_header(headers, "Authorization: Basic ");
  2820. if (header)
  2821. crypto_digest256(digest, header, strlen(header), DIGEST_SHA256);
  2822. /* now make sure the password is there and right */
  2823. if (!header ||
  2824. tor_memneq(digest,
  2825. options->BridgePassword_AuthDigest_, DIGEST256_LEN)) {
  2826. write_http_status_line(conn, 404, "Not found");
  2827. tor_free(header);
  2828. goto done;
  2829. }
  2830. tor_free(header);
  2831. /* all happy now. send an answer. */
  2832. status = networkstatus_getinfo_by_purpose("bridge", time(NULL));
  2833. dlen = strlen(status);
  2834. write_http_response_header(conn, dlen, 0, 0);
  2835. connection_write_to_buf(status, dlen, TO_CONN(conn));
  2836. tor_free(status);
  2837. goto done;
  2838. }
  2839. if (!strcmpstart(url,"/tor/bytes.txt")) {
  2840. char *bytes = directory_dump_request_log();
  2841. size_t len = strlen(bytes);
  2842. write_http_response_header(conn, len, 0, 0);
  2843. connection_write_to_buf(bytes, len, TO_CONN(conn));
  2844. tor_free(bytes);
  2845. goto done;
  2846. }
  2847. if (!strcmp(url,"/tor/robots.txt")) { /* /robots.txt will have been
  2848. rewritten to /tor/robots.txt */
  2849. char robots[] = "User-agent: *\r\nDisallow: /\r\n";
  2850. size_t len = strlen(robots);
  2851. write_http_response_header(conn, len, 0, ROBOTS_CACHE_LIFETIME);
  2852. connection_write_to_buf(robots, len, TO_CONN(conn));
  2853. goto done;
  2854. }
  2855. #if defined(EXPORTMALLINFO) && defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
  2856. #define ADD_MALLINFO_LINE(x) do { \
  2857. smartlist_add_asprintf(lines, "%s %d\n", #x, mi.x); \
  2858. }while(0);
  2859. if (!strcmp(url,"/tor/mallinfo.txt") &&
  2860. (tor_addr_eq_ipv4h(&conn->base_.addr, 0x7f000001ul))) {
  2861. char *result;
  2862. size_t len;
  2863. struct mallinfo mi;
  2864. smartlist_t *lines;
  2865. memset(&mi, 0, sizeof(mi));
  2866. mi = mallinfo();
  2867. lines = smartlist_new();
  2868. ADD_MALLINFO_LINE(arena)
  2869. ADD_MALLINFO_LINE(ordblks)
  2870. ADD_MALLINFO_LINE(smblks)
  2871. ADD_MALLINFO_LINE(hblks)
  2872. ADD_MALLINFO_LINE(hblkhd)
  2873. ADD_MALLINFO_LINE(usmblks)
  2874. ADD_MALLINFO_LINE(fsmblks)
  2875. ADD_MALLINFO_LINE(uordblks)
  2876. ADD_MALLINFO_LINE(fordblks)
  2877. ADD_MALLINFO_LINE(keepcost)
  2878. result = smartlist_join_strings(lines, "", 0, NULL);
  2879. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  2880. smartlist_free(lines);
  2881. len = strlen(result);
  2882. write_http_response_header(conn, len, 0, 0);
  2883. connection_write_to_buf(result, len, TO_CONN(conn));
  2884. tor_free(result);
  2885. goto done;
  2886. }
  2887. #endif
  2888. /* we didn't recognize the url */
  2889. write_http_status_line(conn, 404, "Not found");
  2890. done:
  2891. tor_free(url_mem);
  2892. return 0;
  2893. }
  2894. /** Helper function: called when a dirserver gets a complete HTTP POST
  2895. * request. Look for an uploaded server descriptor or rendezvous
  2896. * service descriptor. On finding one, process it and write a
  2897. * response into conn-\>outbuf. If the request is unrecognized, send a
  2898. * 400. Always return 0. */
  2899. static int
  2900. directory_handle_command_post(dir_connection_t *conn, const char *headers,
  2901. const char *body, size_t body_len)
  2902. {
  2903. char *url = NULL;
  2904. const or_options_t *options = get_options();
  2905. log_debug(LD_DIRSERV,"Received POST command.");
  2906. conn->base_.state = DIR_CONN_STATE_SERVER_WRITING;
  2907. if (parse_http_url(headers, &url) < 0) {
  2908. write_http_status_line(conn, 400, "Bad request");
  2909. return 0;
  2910. }
  2911. log_debug(LD_DIRSERV,"rewritten url as '%s'.", escaped(url));
  2912. /* Handle v2 rendezvous service publish request. */
  2913. if (options->HidServDirectoryV2 &&
  2914. connection_dir_is_encrypted(conn) &&
  2915. !strcmpstart(url,"/tor/rendezvous2/publish")) {
  2916. switch (rend_cache_store_v2_desc_as_dir(body)) {
  2917. case RCS_NOTDIR:
  2918. log_info(LD_REND, "Rejected v2 rend descriptor (length %d) from %s "
  2919. "since we're not currently a hidden service directory.",
  2920. (int)body_len, conn->base_.address);
  2921. write_http_status_line(conn, 503, "Currently not acting as v2 "
  2922. "hidden service directory");
  2923. break;
  2924. case RCS_BADDESC:
  2925. log_warn(LD_REND, "Rejected v2 rend descriptor (length %d) from %s.",
  2926. (int)body_len, conn->base_.address);
  2927. write_http_status_line(conn, 400,
  2928. "Invalid v2 service descriptor rejected");
  2929. break;
  2930. case RCS_OKAY:
  2931. default:
  2932. write_http_status_line(conn, 200, "Service descriptor (v2) stored");
  2933. log_info(LD_REND, "Handled v2 rendezvous descriptor post: accepted");
  2934. }
  2935. goto done;
  2936. }
  2937. if (!authdir_mode(options)) {
  2938. /* we just provide cached directories; we don't want to
  2939. * receive anything. */
  2940. write_http_status_line(conn, 400, "Nonauthoritative directory does not "
  2941. "accept posted server descriptors");
  2942. goto done;
  2943. }
  2944. if (authdir_mode_handles_descs(options, -1) &&
  2945. !strcmp(url,"/tor/")) { /* server descriptor post */
  2946. const char *msg = "[None]";
  2947. uint8_t purpose = authdir_mode_bridge(options) ?
  2948. ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
  2949. was_router_added_t r = dirserv_add_multiple_descriptors(body, purpose,
  2950. conn->base_.address, &msg);
  2951. tor_assert(msg);
  2952. if (r == ROUTER_ADDED_NOTIFY_GENERATOR) {
  2953. /* Accepted with a message. */
  2954. log_info(LD_DIRSERV,
  2955. "Problematic router descriptor or extra-info from %s "
  2956. "(\"%s\").",
  2957. conn->base_.address, msg);
  2958. write_http_status_line(conn, 400, msg);
  2959. } else if (r == ROUTER_ADDED_SUCCESSFULLY) {
  2960. write_http_status_line(conn, 200, msg);
  2961. } else if (WRA_WAS_OUTDATED(r)) {
  2962. write_http_response_header_impl(conn, -1, NULL, NULL,
  2963. "X-Descriptor-Not-New: Yes\r\n", -1);
  2964. } else {
  2965. log_info(LD_DIRSERV,
  2966. "Rejected router descriptor or extra-info from %s "
  2967. "(\"%s\").",
  2968. conn->base_.address, msg);
  2969. write_http_status_line(conn, 400, msg);
  2970. }
  2971. goto done;
  2972. }
  2973. if (authdir_mode_v3(options) &&
  2974. !strcmp(url,"/tor/post/vote")) { /* v3 networkstatus vote */
  2975. const char *msg = "OK";
  2976. int status;
  2977. if (dirvote_add_vote(body, &msg, &status)) {
  2978. write_http_status_line(conn, status, "Vote stored");
  2979. } else {
  2980. tor_assert(msg);
  2981. log_warn(LD_DIRSERV, "Rejected vote from %s (\"%s\").",
  2982. conn->base_.address, msg);
  2983. write_http_status_line(conn, status, msg);
  2984. }
  2985. goto done;
  2986. }
  2987. if (authdir_mode_v3(options) &&
  2988. !strcmp(url,"/tor/post/consensus-signature")) { /* sigs on consensus. */
  2989. const char *msg = NULL;
  2990. if (dirvote_add_signatures(body, conn->base_.address, &msg)>=0) {
  2991. write_http_status_line(conn, 200, msg?msg:"Signatures stored");
  2992. } else {
  2993. log_warn(LD_DIR, "Unable to store signatures posted by %s: %s",
  2994. conn->base_.address, msg?msg:"???");
  2995. write_http_status_line(conn, 400, msg?msg:"Unable to store signatures");
  2996. }
  2997. goto done;
  2998. }
  2999. /* we didn't recognize the url */
  3000. write_http_status_line(conn, 404, "Not found");
  3001. done:
  3002. tor_free(url);
  3003. return 0;
  3004. }
  3005. /** Called when a dirserver receives data on a directory connection;
  3006. * looks for an HTTP request. If the request is complete, remove it
  3007. * from the inbuf, try to process it; otherwise, leave it on the
  3008. * buffer. Return a 0 on success, or -1 on error.
  3009. */
  3010. static int
  3011. directory_handle_command(dir_connection_t *conn)
  3012. {
  3013. char *headers=NULL, *body=NULL;
  3014. size_t body_len=0;
  3015. int r;
  3016. tor_assert(conn);
  3017. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  3018. switch (connection_fetch_from_buf_http(TO_CONN(conn),
  3019. &headers, MAX_HEADERS_SIZE,
  3020. &body, &body_len, MAX_DIR_UL_SIZE, 0)) {
  3021. case -1: /* overflow */
  3022. log_warn(LD_DIRSERV,
  3023. "Request too large from address '%s' to DirPort. Closing.",
  3024. safe_str(conn->base_.address));
  3025. return -1;
  3026. case 0:
  3027. log_debug(LD_DIRSERV,"command not all here yet.");
  3028. return 0;
  3029. /* case 1, fall through */
  3030. }
  3031. http_set_address_origin(headers, TO_CONN(conn));
  3032. // we should escape headers here as well,
  3033. // but we can't call escaped() twice, as it uses the same buffer
  3034. //log_debug(LD_DIRSERV,"headers %s, body %s.", headers, escaped(body));
  3035. if (!strncasecmp(headers,"GET",3))
  3036. r = directory_handle_command_get(conn, headers, body, body_len);
  3037. else if (!strncasecmp(headers,"POST",4))
  3038. r = directory_handle_command_post(conn, headers, body, body_len);
  3039. else {
  3040. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  3041. "Got headers %s with unknown command. Closing.",
  3042. escaped(headers));
  3043. r = -1;
  3044. }
  3045. tor_free(headers); tor_free(body);
  3046. return r;
  3047. }
  3048. /** Write handler for directory connections; called when all data has
  3049. * been flushed. Close the connection or wait for a response as
  3050. * appropriate.
  3051. */
  3052. int
  3053. connection_dir_finished_flushing(dir_connection_t *conn)
  3054. {
  3055. tor_assert(conn);
  3056. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  3057. /* Note that we have finished writing the directory response. For direct
  3058. * connections this means we're done, for tunneled connections its only
  3059. * an intermediate step. */
  3060. if (conn->dirreq_id)
  3061. geoip_change_dirreq_state(conn->dirreq_id, DIRREQ_TUNNELED,
  3062. DIRREQ_FLUSHING_DIR_CONN_FINISHED);
  3063. else
  3064. geoip_change_dirreq_state(TO_CONN(conn)->global_identifier,
  3065. DIRREQ_DIRECT,
  3066. DIRREQ_FLUSHING_DIR_CONN_FINISHED);
  3067. switch (conn->base_.state) {
  3068. case DIR_CONN_STATE_CONNECTING:
  3069. case DIR_CONN_STATE_CLIENT_SENDING:
  3070. log_debug(LD_DIR,"client finished sending command.");
  3071. conn->base_.state = DIR_CONN_STATE_CLIENT_READING;
  3072. return 0;
  3073. case DIR_CONN_STATE_SERVER_WRITING:
  3074. if (conn->dir_spool_src != DIR_SPOOL_NONE) {
  3075. #ifdef USE_BUFFEREVENTS
  3076. /* This can happen with paired bufferevents, since a paired connection
  3077. * can flush immediately when you write to it, making the subsequent
  3078. * check in connection_handle_write_cb() decide that the connection
  3079. * is flushed. */
  3080. log_debug(LD_DIRSERV, "Emptied a dirserv buffer, but still spooling.");
  3081. #else
  3082. log_warn(LD_BUG, "Emptied a dirserv buffer, but it's still spooling!");
  3083. connection_mark_for_close(TO_CONN(conn));
  3084. #endif
  3085. } else {
  3086. log_debug(LD_DIRSERV, "Finished writing server response. Closing.");
  3087. connection_mark_for_close(TO_CONN(conn));
  3088. }
  3089. return 0;
  3090. default:
  3091. log_warn(LD_BUG,"called in unexpected state %d.",
  3092. conn->base_.state);
  3093. tor_fragile_assert();
  3094. return -1;
  3095. }
  3096. return 0;
  3097. }
  3098. /** Connected handler for directory connections: begin sending data to the
  3099. * server */
  3100. int
  3101. connection_dir_finished_connecting(dir_connection_t *conn)
  3102. {
  3103. tor_assert(conn);
  3104. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  3105. tor_assert(conn->base_.state == DIR_CONN_STATE_CONNECTING);
  3106. log_debug(LD_HTTP,"Dir connection to router %s:%u established.",
  3107. conn->base_.address,conn->base_.port);
  3108. conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING; /* start flushing conn */
  3109. return 0;
  3110. }
  3111. /** Decide which download schedule we want to use based on descriptor type
  3112. * in <b>dls</b> and whether we are acting as directory <b>server</b>, and
  3113. * then return a list of int pointers defining download delays in seconds.
  3114. * Helper function for download_status_increment_failure() and
  3115. * download_status_reset(). */
  3116. static const smartlist_t *
  3117. find_dl_schedule_and_len(download_status_t *dls, int server)
  3118. {
  3119. switch (dls->schedule) {
  3120. case DL_SCHED_GENERIC:
  3121. if (server)
  3122. return get_options()->TestingServerDownloadSchedule;
  3123. else
  3124. return get_options()->TestingClientDownloadSchedule;
  3125. case DL_SCHED_CONSENSUS:
  3126. if (server)
  3127. return get_options()->TestingServerConsensusDownloadSchedule;
  3128. else
  3129. return get_options()->TestingClientConsensusDownloadSchedule;
  3130. case DL_SCHED_BRIDGE:
  3131. return get_options()->TestingBridgeDownloadSchedule;
  3132. default:
  3133. tor_assert(0);
  3134. }
  3135. }
  3136. /** Called when an attempt to download <b>dls</b> has failed with HTTP status
  3137. * <b>status_code</b>. Increment the failure count (if the code indicates a
  3138. * real failure) and set <b>dls</b>-\>next_attempt_at to an appropriate time
  3139. * in the future. */
  3140. time_t
  3141. download_status_increment_failure(download_status_t *dls, int status_code,
  3142. const char *item, int server, time_t now)
  3143. {
  3144. const smartlist_t *schedule;
  3145. int increment;
  3146. tor_assert(dls);
  3147. if (status_code != 503 || server) {
  3148. if (dls->n_download_failures < IMPOSSIBLE_TO_DOWNLOAD-1)
  3149. ++dls->n_download_failures;
  3150. }
  3151. schedule = find_dl_schedule_and_len(dls, server);
  3152. if (dls->n_download_failures < smartlist_len(schedule))
  3153. increment = *(int *)smartlist_get(schedule, dls->n_download_failures);
  3154. else if (dls->n_download_failures == IMPOSSIBLE_TO_DOWNLOAD)
  3155. increment = INT_MAX;
  3156. else
  3157. increment = *(int *)smartlist_get(schedule, smartlist_len(schedule) - 1);
  3158. if (increment < INT_MAX)
  3159. dls->next_attempt_at = now+increment;
  3160. else
  3161. dls->next_attempt_at = TIME_MAX;
  3162. if (item) {
  3163. if (increment == 0)
  3164. log_debug(LD_DIR, "%s failed %d time(s); I'll try again immediately.",
  3165. item, (int)dls->n_download_failures);
  3166. else if (dls->next_attempt_at < TIME_MAX)
  3167. log_debug(LD_DIR, "%s failed %d time(s); I'll try again in %d seconds.",
  3168. item, (int)dls->n_download_failures,
  3169. (int)(dls->next_attempt_at-now));
  3170. else
  3171. log_debug(LD_DIR, "%s failed %d time(s); Giving up for a while.",
  3172. item, (int)dls->n_download_failures);
  3173. }
  3174. return dls->next_attempt_at;
  3175. }
  3176. /** Reset <b>dls</b> so that it will be considered downloadable
  3177. * immediately, and/or to show that we don't need it anymore.
  3178. *
  3179. * (We find the zeroth element of the download schedule, and set
  3180. * next_attempt_at to be the appropriate offset from 'now'. In most
  3181. * cases this means setting it to 'now', so the item will be immediately
  3182. * downloadable; in the case of bridge descriptors, the zeroth element
  3183. * is an hour from now.) */
  3184. void
  3185. download_status_reset(download_status_t *dls)
  3186. {
  3187. const smartlist_t *schedule = find_dl_schedule_and_len(
  3188. dls, get_options()->DirPort_set);
  3189. dls->n_download_failures = 0;
  3190. dls->next_attempt_at = time(NULL) + *(int *)smartlist_get(schedule, 0);
  3191. }
  3192. /** Return the number of failures on <b>dls</b> since the last success (if
  3193. * any). */
  3194. int
  3195. download_status_get_n_failures(const download_status_t *dls)
  3196. {
  3197. return dls->n_download_failures;
  3198. }
  3199. /** Called when one or more routerdesc (or extrainfo, if <b>was_extrainfo</b>)
  3200. * fetches have failed (with uppercase fingerprints listed in <b>failed</b>,
  3201. * either as descriptor digests or as identity digests based on
  3202. * <b>was_descriptor_digests</b>).
  3203. */
  3204. static void
  3205. dir_routerdesc_download_failed(smartlist_t *failed, int status_code,
  3206. int router_purpose,
  3207. int was_extrainfo, int was_descriptor_digests)
  3208. {
  3209. char digest[DIGEST_LEN];
  3210. time_t now = time(NULL);
  3211. int server = directory_fetches_from_authorities(get_options());
  3212. if (!was_descriptor_digests) {
  3213. if (router_purpose == ROUTER_PURPOSE_BRIDGE) {
  3214. tor_assert(!was_extrainfo);
  3215. connection_dir_retry_bridges(failed);
  3216. }
  3217. return; /* FFFF should implement for other-than-router-purpose someday */
  3218. }
  3219. SMARTLIST_FOREACH_BEGIN(failed, const char *, cp) {
  3220. download_status_t *dls = NULL;
  3221. if (base16_decode(digest, DIGEST_LEN, cp, strlen(cp)) < 0) {
  3222. log_warn(LD_BUG, "Malformed fingerprint in list: %s", escaped(cp));
  3223. continue;
  3224. }
  3225. if (was_extrainfo) {
  3226. signed_descriptor_t *sd =
  3227. router_get_by_extrainfo_digest(digest);
  3228. if (sd)
  3229. dls = &sd->ei_dl_status;
  3230. } else {
  3231. dls = router_get_dl_status_by_descriptor_digest(digest);
  3232. }
  3233. if (!dls || dls->n_download_failures >=
  3234. get_options()->TestingDescriptorMaxDownloadTries)
  3235. continue;
  3236. download_status_increment_failure(dls, status_code, cp, server, now);
  3237. } SMARTLIST_FOREACH_END(cp);
  3238. /* No need to relaunch descriptor downloads here: we already do it
  3239. * every 10 or 60 seconds (FOO_DESCRIPTOR_RETRY_INTERVAL) in main.c. */
  3240. }
  3241. /** Called when a connection to download microdescriptors has failed in whole
  3242. * or in part. <b>failed</b> is a list of every microdesc digest we didn't
  3243. * get. <b>status_code</b> is the http status code we received. Reschedule the
  3244. * microdesc downloads as appropriate. */
  3245. static void
  3246. dir_microdesc_download_failed(smartlist_t *failed,
  3247. int status_code)
  3248. {
  3249. networkstatus_t *consensus
  3250. = networkstatus_get_latest_consensus_by_flavor(FLAV_MICRODESC);
  3251. routerstatus_t *rs;
  3252. download_status_t *dls;
  3253. time_t now = time(NULL);
  3254. int server = directory_fetches_from_authorities(get_options());
  3255. if (! consensus)
  3256. return;
  3257. SMARTLIST_FOREACH_BEGIN(failed, const char *, d) {
  3258. rs = router_get_mutable_consensus_status_by_descriptor_digest(consensus,d);
  3259. if (!rs)
  3260. continue;
  3261. dls = &rs->dl_status;
  3262. if (dls->n_download_failures >=
  3263. get_options()->TestingMicrodescMaxDownloadTries)
  3264. continue;
  3265. {
  3266. char buf[BASE64_DIGEST256_LEN+1];
  3267. digest256_to_base64(buf, d);
  3268. download_status_increment_failure(dls, status_code, buf,
  3269. server, now);
  3270. }
  3271. } SMARTLIST_FOREACH_END(d);
  3272. }
  3273. /** Helper. Compare two fp_pair_t objects, and return negative, 0, or
  3274. * positive as appropriate. */
  3275. static int
  3276. compare_pairs_(const void **a, const void **b)
  3277. {
  3278. const fp_pair_t *fp1 = *a, *fp2 = *b;
  3279. int r;
  3280. if ((r = fast_memcmp(fp1->first, fp2->first, DIGEST_LEN)))
  3281. return r;
  3282. else
  3283. return fast_memcmp(fp1->second, fp2->second, DIGEST_LEN);
  3284. }
  3285. /** Divide a string <b>res</b> of the form FP1-FP2+FP3-FP4...[.z], where each
  3286. * FP is a hex-encoded fingerprint, into a sequence of distinct sorted
  3287. * fp_pair_t. Skip malformed pairs. On success, return 0 and add those
  3288. * fp_pair_t into <b>pairs_out</b>. On failure, return -1. */
  3289. int
  3290. dir_split_resource_into_fingerprint_pairs(const char *res,
  3291. smartlist_t *pairs_out)
  3292. {
  3293. smartlist_t *pairs_tmp = smartlist_new();
  3294. smartlist_t *pairs_result = smartlist_new();
  3295. smartlist_split_string(pairs_tmp, res, "+", 0, 0);
  3296. if (smartlist_len(pairs_tmp)) {
  3297. char *last = smartlist_get(pairs_tmp,smartlist_len(pairs_tmp)-1);
  3298. size_t last_len = strlen(last);
  3299. if (last_len > 2 && !strcmp(last+last_len-2, ".z")) {
  3300. last[last_len-2] = '\0';
  3301. }
  3302. }
  3303. SMARTLIST_FOREACH_BEGIN(pairs_tmp, char *, cp) {
  3304. if (strlen(cp) != HEX_DIGEST_LEN*2+1) {
  3305. log_info(LD_DIR,
  3306. "Skipping digest pair %s with non-standard length.", escaped(cp));
  3307. } else if (cp[HEX_DIGEST_LEN] != '-') {
  3308. log_info(LD_DIR,
  3309. "Skipping digest pair %s with missing dash.", escaped(cp));
  3310. } else {
  3311. fp_pair_t pair;
  3312. if (base16_decode(pair.first, DIGEST_LEN, cp, HEX_DIGEST_LEN)<0 ||
  3313. base16_decode(pair.second,
  3314. DIGEST_LEN, cp+HEX_DIGEST_LEN+1, HEX_DIGEST_LEN)<0) {
  3315. log_info(LD_DIR, "Skipping non-decodable digest pair %s", escaped(cp));
  3316. } else {
  3317. smartlist_add(pairs_result, tor_memdup(&pair, sizeof(pair)));
  3318. }
  3319. }
  3320. tor_free(cp);
  3321. } SMARTLIST_FOREACH_END(cp);
  3322. smartlist_free(pairs_tmp);
  3323. /* Uniq-and-sort */
  3324. smartlist_sort(pairs_result, compare_pairs_);
  3325. smartlist_uniq(pairs_result, compare_pairs_, tor_free_);
  3326. smartlist_add_all(pairs_out, pairs_result);
  3327. smartlist_free(pairs_result);
  3328. return 0;
  3329. }
  3330. /** Given a directory <b>resource</b> request, containing zero
  3331. * or more strings separated by plus signs, followed optionally by ".z", store
  3332. * the strings, in order, into <b>fp_out</b>. If <b>compressed_out</b> is
  3333. * non-NULL, set it to 1 if the resource ends in ".z", else set it to 0.
  3334. *
  3335. * If (flags & DSR_HEX), then delete all elements that aren't hex digests, and
  3336. * decode the rest. If (flags & DSR_BASE64), then use "-" rather than "+" as
  3337. * a separator, delete all the elements that aren't base64-encoded digests,
  3338. * and decode the rest. If (flags & DSR_DIGEST256), these digests should be
  3339. * 256 bits long; else they should be 160.
  3340. *
  3341. * If (flags & DSR_SORT_UNIQ), then sort the list and remove all duplicates.
  3342. */
  3343. int
  3344. dir_split_resource_into_fingerprints(const char *resource,
  3345. smartlist_t *fp_out, int *compressed_out,
  3346. int flags)
  3347. {
  3348. const int decode_hex = flags & DSR_HEX;
  3349. const int decode_base64 = flags & DSR_BASE64;
  3350. const int digests_are_256 = flags & DSR_DIGEST256;
  3351. const int sort_uniq = flags & DSR_SORT_UNIQ;
  3352. const int digest_len = digests_are_256 ? DIGEST256_LEN : DIGEST_LEN;
  3353. const int hex_digest_len = digests_are_256 ?
  3354. HEX_DIGEST256_LEN : HEX_DIGEST_LEN;
  3355. const int base64_digest_len = digests_are_256 ?
  3356. BASE64_DIGEST256_LEN : BASE64_DIGEST_LEN;
  3357. smartlist_t *fp_tmp = smartlist_new();
  3358. tor_assert(!(decode_hex && decode_base64));
  3359. tor_assert(fp_out);
  3360. smartlist_split_string(fp_tmp, resource, decode_base64?"-":"+", 0, 0);
  3361. if (compressed_out)
  3362. *compressed_out = 0;
  3363. if (smartlist_len(fp_tmp)) {
  3364. char *last = smartlist_get(fp_tmp,smartlist_len(fp_tmp)-1);
  3365. size_t last_len = strlen(last);
  3366. if (last_len > 2 && !strcmp(last+last_len-2, ".z")) {
  3367. last[last_len-2] = '\0';
  3368. if (compressed_out)
  3369. *compressed_out = 1;
  3370. }
  3371. }
  3372. if (decode_hex || decode_base64) {
  3373. const size_t encoded_len = decode_hex ? hex_digest_len : base64_digest_len;
  3374. int i;
  3375. char *cp, *d = NULL;
  3376. for (i = 0; i < smartlist_len(fp_tmp); ++i) {
  3377. cp = smartlist_get(fp_tmp, i);
  3378. if (strlen(cp) != encoded_len) {
  3379. log_info(LD_DIR,
  3380. "Skipping digest %s with non-standard length.", escaped(cp));
  3381. smartlist_del_keeporder(fp_tmp, i--);
  3382. goto again;
  3383. }
  3384. d = tor_malloc_zero(digest_len);
  3385. if (decode_hex ?
  3386. (base16_decode(d, digest_len, cp, hex_digest_len)<0) :
  3387. (base64_decode(d, digest_len, cp, base64_digest_len)<0)) {
  3388. log_info(LD_DIR, "Skipping non-decodable digest %s", escaped(cp));
  3389. smartlist_del_keeporder(fp_tmp, i--);
  3390. goto again;
  3391. }
  3392. smartlist_set(fp_tmp, i, d);
  3393. d = NULL;
  3394. again:
  3395. tor_free(cp);
  3396. tor_free(d);
  3397. }
  3398. }
  3399. if (sort_uniq) {
  3400. if (decode_hex || decode_base64) {
  3401. if (digests_are_256) {
  3402. smartlist_sort_digests256(fp_tmp);
  3403. smartlist_uniq_digests256(fp_tmp);
  3404. } else {
  3405. smartlist_sort_digests(fp_tmp);
  3406. smartlist_uniq_digests(fp_tmp);
  3407. }
  3408. } else {
  3409. smartlist_sort_strings(fp_tmp);
  3410. smartlist_uniq_strings(fp_tmp);
  3411. }
  3412. }
  3413. smartlist_add_all(fp_out, fp_tmp);
  3414. smartlist_free(fp_tmp);
  3415. return 0;
  3416. }