directory.c 153 KB

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