directory.c 137 KB

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