directory.c 104 KB

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