directory.c 125 KB

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