directory.c 118 KB

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