directory.c 147 KB

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