directory.c 136 KB

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