1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201 |
- #include "or.h"
- #include "backtrace.h"
- #include "buffers.h"
- #include "circuitbuild.h"
- #include "config.h"
- #include "connection.h"
- #include "connection_edge.h"
- #include "control.h"
- #include "directory.h"
- #include "dirserv.h"
- #include "dirvote.h"
- #include "entrynodes.h"
- #include "geoip.h"
- #include "main.h"
- #include "microdesc.h"
- #include "networkstatus.h"
- #include "nodelist.h"
- #include "policies.h"
- #include "relay.h"
- #include "rendclient.h"
- #include "rendcommon.h"
- #include "rendservice.h"
- #include "rephist.h"
- #include "router.h"
- #include "routerlist.h"
- #include "routerparse.h"
- #include "routerset.h"
- #if defined(EXPORTMALLINFO) && defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
- #ifndef OPENBSD
- #include <malloc.h>
- #endif
- #endif
- static void directory_send_command(dir_connection_t *conn,
- int purpose, int direct, const char *resource,
- const char *payload, size_t payload_len,
- time_t if_modified_since);
- static int directory_handle_command(dir_connection_t *conn);
- static int body_is_plausible(const char *body, size_t body_len, int purpose);
- static char *http_get_header(const char *headers, const char *which);
- static void http_set_address_origin(const char *headers, connection_t *conn);
- static void connection_dir_download_routerdesc_failed(dir_connection_t *conn);
- static void connection_dir_bridge_routerdesc_failed(dir_connection_t *conn);
- static void connection_dir_download_cert_failed(
- dir_connection_t *conn, int status_code);
- static void connection_dir_retry_bridges(smartlist_t *descs);
- static void dir_routerdesc_download_failed(smartlist_t *failed,
- int status_code,
- int router_purpose,
- int was_extrainfo,
- int was_descriptor_digests);
- static void dir_microdesc_download_failed(smartlist_t *failed,
- int status_code);
- static int client_likes_consensus(networkstatus_t *v, const char *want_url);
- static void directory_initiate_command_rend(
- const tor_addr_port_t *or_addr_port,
- const tor_addr_port_t *dir_addr_port,
- const char *digest,
- uint8_t dir_purpose,
- uint8_t router_purpose,
- dir_indirection_t indirection,
- const char *resource,
- const char *payload,
- size_t payload_len,
- time_t if_modified_since,
- const rend_data_t *rend_query);
- static void connection_dir_close_consensus_fetches(
- dir_connection_t *except_this_one, const char *resource);
- #define ALLOW_DIRECTORY_TIME_SKEW (30*60)
- #define X_ADDRESS_HEADER "X-Your-Address-Is: "
- #define FULL_DIR_CACHE_LIFETIME (60*60)
- #define RUNNINGROUTERS_CACHE_LIFETIME (20*60)
- #define DIRPORTFRONTPAGE_CACHE_LIFETIME (20*60)
- #define NETWORKSTATUS_CACHE_LIFETIME (5*60)
- #define ROUTERDESC_CACHE_LIFETIME (30*60)
- #define ROUTERDESC_BY_DIGEST_CACHE_LIFETIME (48*60*60)
- #define ROBOTS_CACHE_LIFETIME (24*60*60)
- #define MICRODESC_CACHE_LIFETIME (48*60*60)
- STATIC int
- purpose_needs_anonymity(uint8_t dir_purpose, uint8_t router_purpose)
- {
- if (get_options()->AllDirActionsPrivate)
- return 1;
- if (router_purpose == ROUTER_PURPOSE_BRIDGE)
- return 1;
- if (dir_purpose == DIR_PURPOSE_UPLOAD_DIR ||
- dir_purpose == DIR_PURPOSE_UPLOAD_VOTE ||
- dir_purpose == DIR_PURPOSE_UPLOAD_SIGNATURES ||
- dir_purpose == DIR_PURPOSE_FETCH_STATUS_VOTE ||
- dir_purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES ||
- dir_purpose == DIR_PURPOSE_FETCH_CONSENSUS ||
- dir_purpose == DIR_PURPOSE_FETCH_CERTIFICATE ||
- dir_purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
- dir_purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
- dir_purpose == DIR_PURPOSE_FETCH_MICRODESC)
- return 0;
- return 1;
- }
- STATIC char *
- authdir_type_to_string(dirinfo_type_t auth)
- {
- char *result;
- smartlist_t *lst = smartlist_new();
- if (auth & V3_DIRINFO)
- smartlist_add(lst, (void*)"V3");
- if (auth & BRIDGE_DIRINFO)
- smartlist_add(lst, (void*)"Bridge");
- if (smartlist_len(lst)) {
- result = smartlist_join_strings(lst, ", ", 0, NULL);
- } else {
- result = tor_strdup("[Not an authority]");
- }
- smartlist_free(lst);
- return result;
- }
- STATIC const char *
- dir_conn_purpose_to_string(int purpose)
- {
- switch (purpose)
- {
- case DIR_PURPOSE_UPLOAD_DIR:
- return "server descriptor upload";
- case DIR_PURPOSE_UPLOAD_VOTE:
- return "server vote upload";
- case DIR_PURPOSE_UPLOAD_SIGNATURES:
- return "consensus signature upload";
- case DIR_PURPOSE_FETCH_SERVERDESC:
- return "server descriptor fetch";
- case DIR_PURPOSE_FETCH_EXTRAINFO:
- return "extra-info fetch";
- case DIR_PURPOSE_FETCH_CONSENSUS:
- return "consensus network-status fetch";
- case DIR_PURPOSE_FETCH_CERTIFICATE:
- return "authority cert fetch";
- case DIR_PURPOSE_FETCH_STATUS_VOTE:
- return "status vote fetch";
- case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
- return "consensus signature fetch";
- case DIR_PURPOSE_FETCH_RENDDESC_V2:
- return "hidden-service v2 descriptor fetch";
- case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
- return "hidden-service v2 descriptor upload";
- case DIR_PURPOSE_FETCH_MICRODESC:
- return "microdescriptor fetch";
- }
- log_warn(LD_BUG, "Called with unknown purpose %d", purpose);
- return "(unknown)";
- }
- STATIC dirinfo_type_t
- dir_fetch_type(int dir_purpose, int router_purpose, const char *resource)
- {
- dirinfo_type_t type;
- switch (dir_purpose) {
- case DIR_PURPOSE_FETCH_EXTRAINFO:
- type = EXTRAINFO_DIRINFO;
- if (router_purpose == ROUTER_PURPOSE_BRIDGE)
- type |= BRIDGE_DIRINFO;
- else
- type |= V3_DIRINFO;
- break;
- case DIR_PURPOSE_FETCH_SERVERDESC:
- if (router_purpose == ROUTER_PURPOSE_BRIDGE)
- type = BRIDGE_DIRINFO;
- else
- type = V3_DIRINFO;
- break;
- case DIR_PURPOSE_FETCH_STATUS_VOTE:
- case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
- case DIR_PURPOSE_FETCH_CERTIFICATE:
- type = V3_DIRINFO;
- break;
- case DIR_PURPOSE_FETCH_CONSENSUS:
- type = V3_DIRINFO;
- if (resource && !strcmp(resource, "microdesc"))
- type |= MICRODESC_DIRINFO;
- break;
- case DIR_PURPOSE_FETCH_MICRODESC:
- type = MICRODESC_DIRINFO;
- break;
- default:
- log_warn(LD_BUG, "Unexpected purpose %d", (int)dir_purpose);
- type = NO_DIRINFO;
- break;
- }
- return type;
- }
- int
- router_supports_extrainfo(const char *identity_digest, int is_authority)
- {
- const node_t *node = node_get_by_id(identity_digest);
- if (node && node->ri) {
- if (node->ri->caches_extra_info)
- return 1;
- }
- if (is_authority) {
- return 1;
- }
- return 0;
- }
- int
- directories_have_accepted_server_descriptor(void)
- {
- const smartlist_t *servers = router_get_trusted_dir_servers();
- const or_options_t *options = get_options();
- SMARTLIST_FOREACH(servers, dir_server_t *, d, {
- if ((d->type & options->PublishServerDescriptor_) &&
- d->has_accepted_serverdesc) {
- return 1;
- }
- });
- return 0;
- }
- void
- directory_post_to_dirservers(uint8_t dir_purpose, uint8_t router_purpose,
- dirinfo_type_t type,
- const char *payload,
- size_t payload_len, size_t extrainfo_len)
- {
- const or_options_t *options = get_options();
- dir_indirection_t indirection;
- const smartlist_t *dirservers = router_get_trusted_dir_servers();
- int found = 0;
- const int exclude_self = (dir_purpose == DIR_PURPOSE_UPLOAD_VOTE ||
- dir_purpose == DIR_PURPOSE_UPLOAD_SIGNATURES);
- tor_assert(dirservers);
-
- SMARTLIST_FOREACH_BEGIN(dirservers, dir_server_t *, ds) {
- routerstatus_t *rs = &(ds->fake_status);
- size_t upload_len = payload_len;
- if ((type & ds->type) == 0)
- continue;
- if (exclude_self && router_digest_is_me(ds->digest)) {
-
- found = 1;
- continue;
- }
- if (options->StrictNodes &&
- routerset_contains_routerstatus(options->ExcludeNodes, rs, -1)) {
- log_warn(LD_DIR, "Wanted to contact authority '%s' for %s, but "
- "it's in our ExcludedNodes list and StrictNodes is set. "
- "Skipping.",
- ds->nickname,
- dir_conn_purpose_to_string(dir_purpose));
- continue;
- }
- found = 1;
- if (dir_purpose == DIR_PURPOSE_UPLOAD_DIR)
- ds->has_accepted_serverdesc = 0;
- if (extrainfo_len && router_supports_extrainfo(ds->digest, 1)) {
- upload_len += extrainfo_len;
- log_info(LD_DIR, "Uploading an extrainfo too (length %d)",
- (int) extrainfo_len);
- }
- if (purpose_needs_anonymity(dir_purpose, router_purpose)) {
- indirection = DIRIND_ANONYMOUS;
- } else if (!fascist_firewall_allows_dir_server(ds,
- FIREWALL_DIR_CONNECTION,
- 0)) {
- if (fascist_firewall_allows_dir_server(ds, FIREWALL_OR_CONNECTION, 0))
- indirection = DIRIND_ONEHOP;
- else
- indirection = DIRIND_ANONYMOUS;
- } else {
- indirection = DIRIND_DIRECT_CONN;
- }
- directory_initiate_command_routerstatus(rs, dir_purpose,
- router_purpose,
- indirection,
- NULL, payload, upload_len, 0);
- } SMARTLIST_FOREACH_END(ds);
- if (!found) {
- char *s = authdir_type_to_string(type);
- log_warn(LD_DIR, "Publishing server descriptor to directory authorities "
- "of type '%s', but no authorities of that type listed!", s);
- tor_free(s);
- }
- }
- STATIC int
- should_use_directory_guards(const or_options_t *options)
- {
-
- if (public_server_mode(options))
- return 0;
-
- if (!options->UseEntryGuards || !options->UseEntryGuardsAsDirGuards)
- return 0;
-
- if (options->DownloadExtraInfo || options->FetchDirInfoEarly ||
- options->FetchDirInfoExtraEarly || options->FetchUselessDescriptors)
- return 0;
- return 1;
- }
- static const routerstatus_t *
- directory_pick_generic_dirserver(dirinfo_type_t type, int pds_flags,
- uint8_t dir_purpose)
- {
- const routerstatus_t *rs = NULL;
- const or_options_t *options = get_options();
- if (options->UseBridges)
- log_warn(LD_BUG, "Called when we have UseBridges set.");
- if (should_use_directory_guards(options)) {
- const node_t *node = choose_random_dirguard(type);
- if (node)
- rs = node->rs;
- } else {
-
- rs = router_pick_directory_server(type, pds_flags);
- }
- if (!rs) {
- log_info(LD_DIR, "No router found for %s; falling back to "
- "dirserver list.", dir_conn_purpose_to_string(dir_purpose));
- rs = router_pick_fallback_dirserver(type, pds_flags);
- }
- return rs;
- }
- MOCK_IMPL(void, directory_get_from_dirserver, (
- uint8_t dir_purpose,
- uint8_t router_purpose,
- const char *resource,
- int pds_flags,
- download_want_authority_t want_authority))
- {
- const routerstatus_t *rs = NULL;
- const or_options_t *options = get_options();
- int prefer_authority = (directory_fetches_from_authorities(options)
- || want_authority == DL_WANT_AUTHORITY);
- int require_authority = 0;
- int get_via_tor = purpose_needs_anonymity(dir_purpose, router_purpose);
- dirinfo_type_t type = dir_fetch_type(dir_purpose, router_purpose, resource);
- time_t if_modified_since = 0;
- if (type == NO_DIRINFO)
- return;
- if (dir_purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
- int flav = FLAV_NS;
- networkstatus_t *v;
- if (resource)
- flav = networkstatus_parse_flavor_name(resource);
-
- #define DEFAULT_IF_MODIFIED_SINCE_DELAY (180)
- if (flav != -1) {
-
- v = networkstatus_get_latest_consensus_by_flavor(flav);
- if (v) {
-
- time_t ims_delay = DEFAULT_IF_MODIFIED_SINCE_DELAY;
- if (v->fresh_until > v->valid_after
- && ims_delay > (v->fresh_until - v->valid_after)/2) {
- ims_delay = (v->fresh_until - v->valid_after)/2;
- }
- if_modified_since = v->valid_after + ims_delay;
- }
- } else {
-
- cached_dir_t *cd = dirserv_get_consensus(resource);
-
- if (cd)
- if_modified_since = cd->published + DEFAULT_IF_MODIFIED_SINCE_DELAY;
- }
- }
- if (!options->FetchServerDescriptors)
- return;
- if (!get_via_tor) {
- if (options->UseBridges && !(type & BRIDGE_DIRINFO)) {
-
-
- const node_t *node = choose_random_dirguard(type);
- if (node && node->ri) {
-
- routerinfo_t *ri = node->ri;
-
- tor_addr_port_t or_ap;
-
- fascist_firewall_choose_address_node(node, FIREWALL_OR_CONNECTION, 0,
- &or_ap);
- directory_initiate_command(&or_ap.addr, or_ap.port,
- NULL, 0,
- ri->cache_info.identity_digest,
- dir_purpose,
- router_purpose,
- DIRIND_ONEHOP,
- resource, NULL, 0, if_modified_since);
- } else
- log_notice(LD_DIR, "Ignoring directory request, since no bridge "
- "nodes are available yet.");
- return;
- } else {
- if (prefer_authority || (type & BRIDGE_DIRINFO)) {
-
- rs = router_pick_trusteddirserver(type, pds_flags);
- if (rs == NULL && (pds_flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
- PDS_NO_EXISTING_MICRODESC_FETCH))) {
-
- pds_flags &= ~(PDS_NO_EXISTING_SERVERDESC_FETCH|
- PDS_NO_EXISTING_MICRODESC_FETCH);
- rs = router_pick_trusteddirserver(type, pds_flags);
- if (rs) {
- log_debug(LD_DIR, "Deferring serverdesc fetch: all authorities "
- "are in use.");
- return;
- }
- }
- if (rs == NULL && require_authority) {
- log_info(LD_DIR, "No authorities were available for %s: will try "
- "later.", dir_conn_purpose_to_string(dir_purpose));
- return;
- }
- }
- if (!rs && !(type & BRIDGE_DIRINFO)) {
-
- rs = directory_pick_generic_dirserver(type, pds_flags,
- dir_purpose);
- if (!rs)
- get_via_tor = 1;
- }
- }
- }
- if (get_via_tor) {
-
- pds_flags |= PDS_IGNORE_FASCISTFIREWALL;
- rs = router_pick_directory_server(type, pds_flags);
- }
-
- if (rs) {
- const dir_indirection_t indirection =
- get_via_tor ? DIRIND_ANONYMOUS : DIRIND_ONEHOP;
- directory_initiate_command_routerstatus(rs, dir_purpose,
- router_purpose,
- indirection,
- resource, NULL, 0,
- if_modified_since);
- } else {
- log_notice(LD_DIR,
- "While fetching directory info, "
- "no running dirservers known. Will try again later. "
- "(purpose %d)", dir_purpose);
- if (!purpose_needs_anonymity(dir_purpose, router_purpose)) {
-
- directory_all_unreachable(time(NULL));
- }
- }
- }
- void
- directory_get_from_all_authorities(uint8_t dir_purpose,
- uint8_t router_purpose,
- const char *resource)
- {
- tor_assert(dir_purpose == DIR_PURPOSE_FETCH_STATUS_VOTE ||
- dir_purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES);
- SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
- dir_server_t *, ds) {
- routerstatus_t *rs;
- if (router_digest_is_me(ds->digest))
- continue;
- if (!(ds->type & V3_DIRINFO))
- continue;
- rs = &ds->fake_status;
- directory_initiate_command_routerstatus(rs, dir_purpose, router_purpose,
- DIRIND_ONEHOP, resource, NULL,
- 0, 0);
- } SMARTLIST_FOREACH_END(ds);
- }
- static int
- dirind_is_anon(dir_indirection_t ind)
- {
- return ind == DIRIND_ANON_DIRPORT || ind == DIRIND_ANONYMOUS;
- }
- static int
- directory_choose_address_routerstatus(const routerstatus_t *status,
- dir_indirection_t indirection,
- tor_addr_port_t *use_or_ap,
- tor_addr_port_t *use_dir_ap)
- {
- tor_assert(status != NULL);
- tor_assert(use_or_ap != NULL);
- tor_assert(use_dir_ap != NULL);
- const or_options_t *options = get_options();
- int have_or = 0, have_dir = 0;
-
-
- tor_addr_make_null(&use_or_ap->addr, AF_UNSPEC);
- use_or_ap->port = 0;
- tor_addr_make_null(&use_dir_ap->addr, AF_UNSPEC);
- use_dir_ap->port = 0;
-
- if (indirection == DIRIND_ANONYMOUS) {
- if (status->addr) {
-
- tor_addr_from_ipv4h(&use_or_ap->addr, status->addr);
- use_or_ap->port = status->or_port;
- have_or = 1;
- }
- } else if (indirection == DIRIND_ONEHOP) {
-
- have_or = fascist_firewall_choose_address_rs(status,
- FIREWALL_OR_CONNECTION, 0,
- use_or_ap);
- }
-
- if (indirection == DIRIND_DIRECT_CONN ||
- indirection == DIRIND_ANON_DIRPORT ||
- (indirection == DIRIND_ONEHOP
- && !directory_must_use_begindir(options))) {
- have_dir = fascist_firewall_choose_address_rs(status,
- FIREWALL_DIR_CONNECTION, 0,
- use_dir_ap);
- }
-
- if (!have_or && !have_dir) {
- static int logged_backtrace = 0;
- log_info(LD_BUG, "Rejected all OR and Dir addresses from %s when "
- "launching an outgoing directory connection to: IPv4 %s OR %d "
- "Dir %d IPv6 %s OR %d Dir %d", routerstatus_describe(status),
- fmt_addr32(status->addr), status->or_port,
- status->dir_port, fmt_addr(&status->ipv6_addr),
- status->ipv6_orport, status->dir_port);
- if (!logged_backtrace) {
- log_backtrace(LOG_INFO, LD_BUG, "Addresses came from");
- logged_backtrace = 1;
- }
- return -1;
- }
- return 0;
- }
- void
- directory_initiate_command_routerstatus_rend(const routerstatus_t *status,
- uint8_t dir_purpose,
- uint8_t router_purpose,
- dir_indirection_t indirection,
- const char *resource,
- const char *payload,
- size_t payload_len,
- time_t if_modified_since,
- const rend_data_t *rend_query)
- {
- const or_options_t *options = get_options();
- const node_t *node;
- tor_addr_port_t use_or_ap, use_dir_ap;
- const int anonymized_connection = dirind_is_anon(indirection);
- tor_assert(status != NULL);
- node = node_get_by_id(status->identity_digest);
-
- if (!node && anonymized_connection) {
- log_info(LD_DIR, "Not sending anonymized request to directory '%s'; we "
- "don't have its router descriptor.",
- routerstatus_describe(status));
- return;
- }
- if (options->ExcludeNodes && options->StrictNodes &&
- routerset_contains_routerstatus(options->ExcludeNodes, status, -1)) {
- log_warn(LD_DIR, "Wanted to contact directory mirror %s for %s, but "
- "it's in our ExcludedNodes list and StrictNodes is set. "
- "Skipping. This choice might make your Tor not work.",
- routerstatus_describe(status),
- dir_conn_purpose_to_string(dir_purpose));
- return;
- }
-
- if (directory_choose_address_routerstatus(status, indirection, &use_or_ap,
- &use_dir_ap) < 0) {
- return;
- }
-
- directory_initiate_command_rend(&use_or_ap, &use_dir_ap,
- status->identity_digest,
- dir_purpose, router_purpose,
- indirection, resource,
- payload, payload_len, if_modified_since,
- rend_query);
- }
- MOCK_IMPL(void, directory_initiate_command_routerstatus,
- (const routerstatus_t *status,
- uint8_t dir_purpose,
- uint8_t router_purpose,
- dir_indirection_t indirection,
- const char *resource,
- const char *payload,
- size_t payload_len,
- time_t if_modified_since))
- {
- directory_initiate_command_routerstatus_rend(status, dir_purpose,
- router_purpose,
- indirection, resource,
- payload, payload_len,
- if_modified_since, NULL);
- }
- static int
- directory_conn_is_self_reachability_test(dir_connection_t *conn)
- {
- if (conn->requested_resource &&
- !strcmpstart(conn->requested_resource,"authority")) {
- const routerinfo_t *me = router_get_my_routerinfo();
- if (me &&
- router_digest_is_me(conn->identity_digest) &&
- tor_addr_eq_ipv4h(&conn->base_.addr, me->addr) &&
- me->dir_port == conn->base_.port)
- return 1;
- }
- return 0;
- }
- static void
- connection_dir_request_failed(dir_connection_t *conn)
- {
- if (directory_conn_is_self_reachability_test(conn)) {
- return;
- }
- if (!entry_list_is_constrained(get_options()))
- router_set_status(conn->identity_digest, 0);
- if (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
- conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO) {
- log_info(LD_DIR, "Giving up on serverdesc/extrainfo fetch from "
- "directory server at '%s'; retrying",
- conn->base_.address);
- if (conn->router_purpose == ROUTER_PURPOSE_BRIDGE)
- connection_dir_bridge_routerdesc_failed(conn);
- connection_dir_download_routerdesc_failed(conn);
- } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
- if (conn->requested_resource)
- networkstatus_consensus_download_failed(0, conn->requested_resource);
- } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE) {
- log_info(LD_DIR, "Giving up on certificate fetch from directory server "
- "at '%s'; retrying",
- conn->base_.address);
- connection_dir_download_cert_failed(conn, 0);
- } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES) {
- log_info(LD_DIR, "Giving up downloading detached signatures from '%s'",
- conn->base_.address);
- } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) {
- log_info(LD_DIR, "Giving up downloading votes from '%s'",
- conn->base_.address);
- } else if (conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC) {
- log_info(LD_DIR, "Giving up on downloading microdescriptors from "
- "directory server at '%s'; will retry", conn->base_.address);
- connection_dir_download_routerdesc_failed(conn);
- }
- }
- static void
- connection_dir_retry_bridges(smartlist_t *descs)
- {
- char digest[DIGEST_LEN];
- SMARTLIST_FOREACH(descs, const char *, cp,
- {
- if (base16_decode(digest, DIGEST_LEN, cp, strlen(cp))<0) {
- log_warn(LD_BUG, "Malformed fingerprint in list: %s",
- escaped(cp));
- continue;
- }
- retry_bridge_descriptor_fetch_directly(digest);
- });
- }
- static void
- connection_dir_download_routerdesc_failed(dir_connection_t *conn)
- {
-
-
- tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
- conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
- conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
- (void) conn;
- }
- static void
- connection_dir_bridge_routerdesc_failed(dir_connection_t *conn)
- {
- smartlist_t *which = NULL;
-
- if (!conn->requested_resource || strcmpstart(conn->requested_resource,"fp/"))
- return;
- which = smartlist_new();
- dir_split_resource_into_fingerprints(conn->requested_resource
- + strlen("fp/"),
- which, NULL, 0);
- tor_assert(conn->base_.purpose != DIR_PURPOSE_FETCH_EXTRAINFO);
- if (smartlist_len(which)) {
- connection_dir_retry_bridges(which);
- SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
- }
- smartlist_free(which);
- }
- static void
- connection_dir_download_cert_failed(dir_connection_t *conn, int status)
- {
- const char *fp_pfx = "fp/";
- const char *fpsk_pfx = "fp-sk/";
- smartlist_t *failed;
- tor_assert(conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE);
- if (!conn->requested_resource)
- return;
- failed = smartlist_new();
-
- if (!strcmpstart(conn->requested_resource, fp_pfx)) {
-
- dir_split_resource_into_fingerprints(conn->requested_resource +
- strlen(fp_pfx),
- failed, NULL, DSR_HEX);
- SMARTLIST_FOREACH_BEGIN(failed, char *, cp) {
-
- authority_cert_dl_failed(cp, NULL, status);
- tor_free(cp);
- } SMARTLIST_FOREACH_END(cp);
- } else if (!strcmpstart(conn->requested_resource, fpsk_pfx)) {
-
- dir_split_resource_into_fingerprint_pairs(conn->requested_resource +
- strlen(fpsk_pfx), failed);
- SMARTLIST_FOREACH_BEGIN(failed, fp_pair_t *, cp) {
- authority_cert_dl_failed(cp->first, cp->second, status);
- tor_free(cp);
- } SMARTLIST_FOREACH_END(cp);
- } else {
- log_warn(LD_DIR,
- "Don't know what to do with failure for cert fetch %s",
- conn->requested_resource);
- }
- smartlist_free(failed);
- update_certificate_downloads(time(NULL));
- }
- int
- directory_must_use_begindir(const or_options_t *options)
- {
-
- return !public_server_mode(options);
- }
- static int
- directory_command_should_use_begindir(const or_options_t *options,
- const tor_addr_t *addr,
- int or_port, uint8_t router_purpose,
- dir_indirection_t indirection,
- const char **reason)
- {
- (void) router_purpose;
- tor_assert(reason);
- *reason = NULL;
-
- if (!or_port) {
- *reason = "directory with unknown ORPort";
- return 0;
- }
- if (indirection == DIRIND_DIRECT_CONN ||
- indirection == DIRIND_ANON_DIRPORT) {
- *reason = "DirPort connection";
- return 0;
- }
- if (indirection == DIRIND_ONEHOP) {
-
- if (!fascist_firewall_allows_address_addr(addr, or_port,
- FIREWALL_OR_CONNECTION, 0, 0)) {
- *reason = "ORPort not reachable";
- return 0;
- }
- }
-
- if (indirection == DIRIND_ONEHOP) {
- if (!directory_must_use_begindir(options)) {
- *reason = "in relay mode";
- return 0;
- }
- }
-
- *reason = "(using begindir)";
- return 1;
- }
- void
- directory_initiate_command(const tor_addr_t *or_addr, uint16_t or_port,
- const tor_addr_t *dir_addr, uint16_t dir_port,
- const char *digest,
- uint8_t dir_purpose, uint8_t router_purpose,
- dir_indirection_t indirection, const char *resource,
- const char *payload, size_t payload_len,
- time_t if_modified_since)
- {
- tor_addr_port_t or_ap, dir_ap;
-
- if (tor_addr_port_is_valid(or_addr, or_port, 0)) {
- tor_addr_copy(&or_ap.addr, or_addr);
- or_ap.port = or_port;
- } else {
-
- tor_addr_make_null(&or_ap.addr, AF_INET);
- or_ap.port = or_port = 0;
- }
- if (tor_addr_port_is_valid(dir_addr, dir_port, 0)) {
- tor_addr_copy(&dir_ap.addr, dir_addr);
- dir_ap.port = dir_port;
- } else {
-
- tor_addr_make_null(&dir_ap.addr, AF_INET);
- dir_ap.port = dir_port = 0;
- }
- directory_initiate_command_rend(&or_ap, &dir_ap,
- digest, dir_purpose,
- router_purpose, indirection,
- resource, payload, payload_len,
- if_modified_since, NULL);
- }
- static int
- is_sensitive_dir_purpose(uint8_t dir_purpose)
- {
- return ((dir_purpose == DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2) ||
- (dir_purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2) ||
- (dir_purpose == DIR_PURPOSE_FETCH_RENDDESC_V2));
- }
- static void
- directory_initiate_command_rend(const tor_addr_port_t *or_addr_port,
- const tor_addr_port_t *dir_addr_port,
- const char *digest,
- uint8_t dir_purpose, uint8_t router_purpose,
- dir_indirection_t indirection,
- const char *resource,
- const char *payload, size_t payload_len,
- time_t if_modified_since,
- const rend_data_t *rend_query)
- {
- tor_assert(or_addr_port);
- tor_assert(dir_addr_port);
- tor_assert(or_addr_port->port || dir_addr_port->port);
- tor_assert(digest);
- dir_connection_t *conn;
- const or_options_t *options = get_options();
- int socket_error = 0;
- const char *begindir_reason = NULL;
-
- const int use_begindir = directory_command_should_use_begindir(options,
- &or_addr_port->addr, or_addr_port->port,
- router_purpose, indirection,
- &begindir_reason);
-
- const int anonymized_connection = dirind_is_anon(indirection);
-
- tor_addr_t addr;
- tor_addr_copy(&addr, &(use_begindir ? or_addr_port : dir_addr_port)->addr);
- uint16_t port = (use_begindir ? or_addr_port : dir_addr_port)->port;
- log_debug(LD_DIR, "anonymized %d, use_begindir %d.",
- anonymized_connection, use_begindir);
- log_debug(LD_DIR, "Initiating %s", dir_conn_purpose_to_string(dir_purpose));
- #ifndef NON_ANONYMOUS_MODE_ENABLED
- tor_assert(!(is_sensitive_dir_purpose(dir_purpose) &&
- !anonymized_connection));
- #else
- (void)is_sensitive_dir_purpose;
- #endif
-
- if (!use_begindir && directory_must_use_begindir(options)) {
- log_warn(LD_BUG, "Client could not use begindir connection: %s",
- begindir_reason ? begindir_reason : "(NULL)");
- return;
- }
-
- if (!anonymized_connection && !use_begindir && !options->HTTPProxy &&
- (options->Socks4Proxy || options->Socks5Proxy)) {
- log_warn(LD_DIR, "Cannot connect to a directory server through a "
- "SOCKS proxy!");
- return;
- }
-
- if (!port || tor_addr_is_null(&addr)) {
- static int logged_backtrace = 0;
- log_warn(LD_DIR,
- "Cannot make an outgoing %sconnection without %sPort.",
- use_begindir ? "begindir " : "",
- use_begindir ? "an OR" : "a Dir");
- if (!logged_backtrace) {
- log_backtrace(LOG_INFO, LD_BUG, "Address came from");
- logged_backtrace = 1;
- }
- return;
- }
- conn = dir_connection_new(tor_addr_family(&addr));
-
- tor_addr_copy(&conn->base_.addr, &addr);
- conn->base_.port = port;
- conn->base_.address = tor_addr_to_str_dup(&addr);
- memcpy(conn->identity_digest, digest, DIGEST_LEN);
- conn->base_.purpose = dir_purpose;
- conn->router_purpose = router_purpose;
-
- conn->base_.state = DIR_CONN_STATE_CONNECTING;
-
-
- conn->dirconn_direct = !anonymized_connection;
-
- if (rend_query)
- conn->rend_data = rend_data_dup(rend_query);
- if (!anonymized_connection && !use_begindir) {
-
- if (options->HTTPProxy) {
- tor_addr_copy(&addr, &options->HTTPProxyAddr);
- port = options->HTTPProxyPort;
- }
- switch (connection_connect(TO_CONN(conn), conn->base_.address, &addr,
- port, &socket_error)) {
- case -1:
- connection_mark_for_close(TO_CONN(conn));
- return;
- case 1:
-
- conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
-
- case 0:
-
- directory_send_command(conn, dir_purpose, 1, resource,
- payload, payload_len,
- if_modified_since);
- connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
-
- }
- } else {
-
- entry_connection_t *linked_conn;
-
- int iso_flags = anonymized_connection ? ISO_STREAM : ISO_SESSIONGRP;
-
- if (anonymized_connection && use_begindir)
- rep_hist_note_used_internal(time(NULL), 0, 1);
- else if (anonymized_connection && !use_begindir)
- rep_hist_note_used_port(time(NULL), conn->base_.port);
-
- linked_conn =
- connection_ap_make_link(TO_CONN(conn),
- conn->base_.address, conn->base_.port,
- digest,
- SESSION_GROUP_DIRCONN, iso_flags,
- use_begindir, !anonymized_connection);
- if (!linked_conn) {
- log_warn(LD_NET,"Making tunnel to dirserver failed.");
- connection_mark_for_close(TO_CONN(conn));
- return;
- }
- if (connection_add(TO_CONN(conn)) < 0) {
- log_warn(LD_NET,"Unable to add connection for link to dirserver.");
- connection_mark_for_close(TO_CONN(conn));
- return;
- }
- conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
-
- directory_send_command(conn, dir_purpose, 0, resource,
- payload, payload_len,
- if_modified_since);
- connection_watch_events(TO_CONN(conn), READ_EVENT|WRITE_EVENT);
- IF_HAS_BUFFEREVENT(ENTRY_TO_CONN(linked_conn), {
- connection_watch_events(ENTRY_TO_CONN(linked_conn),
- READ_EVENT|WRITE_EVENT);
- }) ELSE_IF_NO_BUFFEREVENT
- connection_start_reading(ENTRY_TO_CONN(linked_conn));
- }
- }
- int
- connection_dir_is_encrypted(dir_connection_t *conn)
- {
-
- return TO_CONN(conn)->linked;
- }
- static int
- compare_strs_(const void **a, const void **b)
- {
- const char *s1 = *a, *s2 = *b;
- return strcmp(s1, s2);
- }
- #define CONDITIONAL_CONSENSUS_FPR_LEN 3
- #if (CONDITIONAL_CONSENSUS_FPR_LEN > DIGEST_LEN)
- #error "conditional consensus fingerprint length is larger than digest length"
- #endif
- static char *
- directory_get_consensus_url(const char *resource)
- {
- char *url = NULL;
- const char *hyphen, *flavor;
- if (resource==NULL || strcmp(resource, "ns")==0) {
- flavor = "";
- hyphen = "";
- } else {
- flavor = resource;
- hyphen = "-";
- }
- {
- char *authority_id_list;
- smartlist_t *authority_digests = smartlist_new();
- SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
- dir_server_t *, ds) {
- char *hex;
- if (!(ds->type & V3_DIRINFO))
- continue;
- hex = tor_malloc(2*CONDITIONAL_CONSENSUS_FPR_LEN+1);
- base16_encode(hex, 2*CONDITIONAL_CONSENSUS_FPR_LEN+1,
- ds->v3_identity_digest, CONDITIONAL_CONSENSUS_FPR_LEN);
- smartlist_add(authority_digests, hex);
- } SMARTLIST_FOREACH_END(ds);
- smartlist_sort(authority_digests, compare_strs_);
- authority_id_list = smartlist_join_strings(authority_digests,
- "+", 0, NULL);
- tor_asprintf(&url, "/tor/status-vote/current/consensus%s%s/%s.z",
- hyphen, flavor, authority_id_list);
- SMARTLIST_FOREACH(authority_digests, char *, cp, tor_free(cp));
- smartlist_free(authority_digests);
- tor_free(authority_id_list);
- }
- return url;
- }
- static void
- copy_ipv6_address(char* destination, const char* source, size_t len,
- int decorate) {
- tor_assert(destination);
- tor_assert(source);
- if (decorate && source[0] != '[') {
- tor_snprintf(destination, len, "[%s]", source);
- } else {
- strlcpy(destination, source, len);
- }
- }
- static void
- directory_send_command(dir_connection_t *conn,
- int purpose, int direct, const char *resource,
- const char *payload, size_t payload_len,
- time_t if_modified_since)
- {
- char proxystring[256];
- char hoststring[128];
-
- char decorated_address[128];
- smartlist_t *headers = smartlist_new();
- char *url;
- char request[8192];
- const char *httpcommand = NULL;
- tor_assert(conn);
- tor_assert(conn->base_.type == CONN_TYPE_DIR);
- tor_free(conn->requested_resource);
- if (resource)
- conn->requested_resource = tor_strdup(resource);
-
- if (strchr(conn->base_.address, ':')) {
- copy_ipv6_address(decorated_address, conn->base_.address,
- sizeof(decorated_address), 1);
- } else {
- strlcpy(decorated_address, conn->base_.address, sizeof(decorated_address));
- }
-
- if (conn->base_.port == 80) {
- strlcpy(hoststring, decorated_address, sizeof(hoststring));
- } else {
- tor_snprintf(hoststring, sizeof(hoststring), "%s:%d",
- decorated_address, conn->base_.port);
- }
-
- if (if_modified_since) {
- char b[RFC1123_TIME_LEN+1];
- format_rfc1123_time(b, if_modified_since);
- smartlist_add_asprintf(headers, "If-Modified-Since: %s\r\n", b);
- }
-
- if (direct && get_options()->HTTPProxy) {
- char *base64_authenticator=NULL;
- const char *authenticator = get_options()->HTTPProxyAuthenticator;
- tor_snprintf(proxystring, sizeof(proxystring),"http://%s", hoststring);
- if (authenticator) {
- base64_authenticator = alloc_http_authenticator(authenticator);
- if (!base64_authenticator)
- log_warn(LD_BUG, "Encoding http authenticator failed");
- }
- if (base64_authenticator) {
- smartlist_add_asprintf(headers,
- "Proxy-Authorization: Basic %s\r\n",
- base64_authenticator);
- tor_free(base64_authenticator);
- }
- } else {
- proxystring[0] = 0;
- }
- switch (purpose) {
- case DIR_PURPOSE_FETCH_CONSENSUS:
-
- tor_assert(!payload);
- httpcommand = "GET";
- url = directory_get_consensus_url(resource);
- log_info(LD_DIR, "Downloading consensus from %s using %s",
- hoststring, url);
- break;
- case DIR_PURPOSE_FETCH_CERTIFICATE:
- tor_assert(resource);
- tor_assert(!payload);
- httpcommand = "GET";
- tor_asprintf(&url, "/tor/keys/%s", resource);
- break;
- case DIR_PURPOSE_FETCH_STATUS_VOTE:
- tor_assert(resource);
- tor_assert(!payload);
- httpcommand = "GET";
- tor_asprintf(&url, "/tor/status-vote/next/%s.z", resource);
- break;
- case DIR_PURPOSE_FETCH_DETACHED_SIGNATURES:
- tor_assert(!resource);
- tor_assert(!payload);
- httpcommand = "GET";
- url = tor_strdup("/tor/status-vote/next/consensus-signatures.z");
- break;
- case DIR_PURPOSE_FETCH_SERVERDESC:
- tor_assert(resource);
- httpcommand = "GET";
- tor_asprintf(&url, "/tor/server/%s", resource);
- break;
- case DIR_PURPOSE_FETCH_EXTRAINFO:
- tor_assert(resource);
- httpcommand = "GET";
- tor_asprintf(&url, "/tor/extra/%s", resource);
- break;
- case DIR_PURPOSE_FETCH_MICRODESC:
- tor_assert(resource);
- httpcommand = "GET";
- tor_asprintf(&url, "/tor/micro/%s", resource);
- break;
- case DIR_PURPOSE_UPLOAD_DIR: {
- const char *why = router_get_descriptor_gen_reason();
- tor_assert(!resource);
- tor_assert(payload);
- httpcommand = "POST";
- url = tor_strdup("/tor/");
- if (why) {
- smartlist_add_asprintf(headers, "X-Desc-Gen-Reason: %s\r\n", why);
- }
- break;
- }
- case DIR_PURPOSE_UPLOAD_VOTE:
- tor_assert(!resource);
- tor_assert(payload);
- httpcommand = "POST";
- url = tor_strdup("/tor/post/vote");
- break;
- case DIR_PURPOSE_UPLOAD_SIGNATURES:
- tor_assert(!resource);
- tor_assert(payload);
- httpcommand = "POST";
- url = tor_strdup("/tor/post/consensus-signature");
- break;
- case DIR_PURPOSE_FETCH_RENDDESC_V2:
- tor_assert(resource);
- tor_assert(strlen(resource) <= REND_DESC_ID_V2_LEN_BASE32);
- tor_assert(!payload);
- httpcommand = "GET";
- tor_asprintf(&url, "/tor/rendezvous2/%s", resource);
- break;
- case DIR_PURPOSE_UPLOAD_RENDDESC_V2:
- tor_assert(!resource);
- tor_assert(payload);
- httpcommand = "POST";
- url = tor_strdup("/tor/rendezvous2/publish");
- break;
- default:
- tor_assert(0);
- return;
- }
-
- if (direct && (strlen(proxystring) + strlen(url) >= 4096)) {
- log_warn(LD_BUG,
- "Squid does not like URLs longer than 4095 bytes, and this "
- "one is %d bytes long: %s%s",
- (int)(strlen(proxystring) + strlen(url)), proxystring, url);
- }
- tor_snprintf(request, sizeof(request), "%s %s", httpcommand, proxystring);
- connection_write_to_buf(request, strlen(request), TO_CONN(conn));
- connection_write_to_buf(url, strlen(url), TO_CONN(conn));
- tor_free(url);
- if (!strcmp(httpcommand, "POST") || payload) {
- smartlist_add_asprintf(headers, "Content-Length: %lu\r\n",
- payload ? (unsigned long)payload_len : 0);
- }
- {
- char *header = smartlist_join_strings(headers, "", 0, NULL);
- tor_snprintf(request, sizeof(request), " HTTP/1.0\r\nHost: %s\r\n%s\r\n",
- hoststring, header);
- tor_free(header);
- }
- connection_write_to_buf(request, strlen(request), TO_CONN(conn));
- if (payload) {
-
- connection_write_to_buf(payload, payload_len, TO_CONN(conn));
- }
- SMARTLIST_FOREACH(headers, char *, h, tor_free(h));
- smartlist_free(headers);
- }
- STATIC int
- parse_http_url(const char *headers, char **url)
- {
- char *s, *start, *tmp;
- s = (char *)eat_whitespace_no_nl(headers);
- if (!*s) return -1;
- s = (char *)find_whitespace(s);
- if (!*s) return -1;
- s = (char *)eat_whitespace_no_nl(s);
- if (!*s) return -1;
- start = s;
- s = (char *)find_whitespace(start);
- if (!*s) return -1;
-
- if (s-start >= 4 && !strcmpstart(start,"http")) {
- tmp = start + 4;
- if (*tmp == 's')
- tmp++;
- if (s-tmp >= 3 && !strcmpstart(tmp,"://")) {
- tmp = strchr(tmp+3, '/');
- if (tmp && tmp < s) {
- log_debug(LD_DIR,"Skipping over 'http[s]://hostname/' string");
- start = tmp;
- }
- }
- }
-
- {
- unsigned minor_ver;
- char ch;
- char *e = (char *)eat_whitespace_no_nl(s);
- if (2 != tor_sscanf(e, "HTTP/1.%u%c", &minor_ver, &ch)) {
- return -1;
- }
- if (ch != '\r')
- return -1;
- }
- if (s-start < 5 || strcmpstart(start,"/tor/")) {
- *url = tor_malloc(s - start + 5);
- strlcpy(*url,"/tor", s-start+5);
- strlcat((*url)+4, start, s-start+1);
- } else {
- *url = tor_strndup(start, s-start);
- }
- return 0;
- }
- static char *
- http_get_header(const char *headers, const char *which)
- {
- const char *cp = headers;
- while (cp) {
- if (!strcasecmpstart(cp, which)) {
- char *eos;
- cp += strlen(which);
- if ((eos = strchr(cp,'\r')))
- return tor_strndup(cp, eos-cp);
- else
- return tor_strdup(cp);
- }
- cp = strchr(cp, '\n');
- if (cp)
- ++cp;
- }
- return NULL;
- }
- static void
- http_set_address_origin(const char *headers, connection_t *conn)
- {
- char *fwd;
- fwd = http_get_header(headers, "Forwarded-For: ");
- if (!fwd)
- fwd = http_get_header(headers, "X-Forwarded-For: ");
- if (fwd) {
- tor_addr_t toraddr;
- if (tor_addr_parse(&toraddr,fwd) == -1 ||
- tor_addr_is_internal(&toraddr,0)) {
- log_debug(LD_DIR, "Ignoring local/internal IP %s", escaped(fwd));
- tor_free(fwd);
- return;
- }
- tor_free(conn->address);
- conn->address = tor_strdup(fwd);
- tor_free(fwd);
- }
- }
- int
- parse_http_response(const char *headers, int *code, time_t *date,
- compress_method_t *compression, char **reason)
- {
- unsigned n1, n2;
- char datestr[RFC1123_TIME_LEN+1];
- smartlist_t *parsed_headers;
- tor_assert(headers);
- tor_assert(code);
- while (TOR_ISSPACE(*headers)) headers++;
- if (tor_sscanf(headers, "HTTP/1.%u %u", &n1, &n2) < 2 ||
- (n1 != 0 && n1 != 1) ||
- (n2 < 100 || n2 >= 600)) {
- log_warn(LD_HTTP,"Failed to parse header %s",escaped(headers));
- return -1;
- }
- *code = n2;
- parsed_headers = smartlist_new();
- smartlist_split_string(parsed_headers, headers, "\n",
- SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
- if (reason) {
- smartlist_t *status_line_elements = smartlist_new();
- tor_assert(smartlist_len(parsed_headers));
- smartlist_split_string(status_line_elements,
- smartlist_get(parsed_headers, 0),
- " ", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
- tor_assert(smartlist_len(status_line_elements) <= 3);
- if (smartlist_len(status_line_elements) == 3) {
- *reason = smartlist_get(status_line_elements, 2);
- smartlist_set(status_line_elements, 2, NULL);
- }
- SMARTLIST_FOREACH(status_line_elements, char *, cp, tor_free(cp));
- smartlist_free(status_line_elements);
- }
- if (date) {
- *date = 0;
- SMARTLIST_FOREACH(parsed_headers, const char *, s,
- if (!strcmpstart(s, "Date: ")) {
- strlcpy(datestr, s+6, sizeof(datestr));
-
- parse_rfc1123_time(datestr, date);
- break;
- });
- }
- if (compression) {
- const char *enc = NULL;
- SMARTLIST_FOREACH(parsed_headers, const char *, s,
- if (!strcmpstart(s, "Content-Encoding: ")) {
- enc = s+18; break;
- });
- if (!enc || !strcmp(enc, "identity")) {
- *compression = NO_METHOD;
- } else if (!strcmp(enc, "deflate") || !strcmp(enc, "x-deflate")) {
- *compression = ZLIB_METHOD;
- } else if (!strcmp(enc, "gzip") || !strcmp(enc, "x-gzip")) {
- *compression = GZIP_METHOD;
- } else {
- log_info(LD_HTTP, "Unrecognized content encoding: %s. Trying to deal.",
- escaped(enc));
- *compression = UNKNOWN_METHOD;
- }
- }
- SMARTLIST_FOREACH(parsed_headers, char *, s, tor_free(s));
- smartlist_free(parsed_headers);
- return 0;
- }
- static int
- body_is_plausible(const char *body, size_t len, int purpose)
- {
- int i;
- if (len == 0)
- return 1;
- if (len < 32)
- return 0;
- if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
- return (!strcmpstart(body,"onion-key"));
- }
- if (1) {
- if (!strcmpstart(body,"router") ||
- !strcmpstart(body,"network-status"))
- return 1;
- for (i=0;i<32;++i) {
- if (!TOR_ISPRINT(body[i]) && !TOR_ISSPACE(body[i]))
- return 0;
- }
- }
- return 1;
- }
- static int
- load_downloaded_routers(const char *body, smartlist_t *which,
- int descriptor_digests,
- int router_purpose,
- const char *source)
- {
- char buf[256];
- char time_buf[ISO_TIME_LEN+1];
- int added = 0;
- int general = router_purpose == ROUTER_PURPOSE_GENERAL;
- format_iso_time(time_buf, time(NULL));
- tor_assert(source);
- if (tor_snprintf(buf, sizeof(buf),
- "@downloaded-at %s\n"
- "@source %s\n"
- "%s%s%s", time_buf, escaped(source),
- !general ? "@purpose " : "",
- !general ? router_purpose_to_string(router_purpose) : "",
- !general ? "\n" : "")<0)
- return added;
- added = router_load_routers_from_string(body, NULL, SAVED_NOWHERE, which,
- descriptor_digests, buf);
- if (added && general)
- control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
- count_loading_descriptors_progress());
- return added;
- }
- static int
- connection_dir_client_reached_eof(dir_connection_t *conn)
- {
- char *body;
- char *headers;
- char *reason = NULL;
- size_t body_len = 0;
- int status_code;
- time_t date_header = 0;
- long apparent_skew;
- compress_method_t compression;
- int plausible;
- int skewed = 0;
- int allow_partial = (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
- conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO ||
- conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC);
- time_t now = time(NULL);
- int src_code;
- switch (connection_fetch_from_buf_http(TO_CONN(conn),
- &headers, MAX_HEADERS_SIZE,
- &body, &body_len, MAX_DIR_DL_SIZE,
- allow_partial)) {
- case -1:
- log_warn(LD_PROTOCOL,
- "'fetch' response too large (server '%s:%d'). Closing.",
- conn->base_.address, conn->base_.port);
- return -1;
- case 0:
- log_info(LD_HTTP,
- "'fetch' response not all here, but we're at eof. Closing.");
- return -1;
-
- }
- if (parse_http_response(headers, &status_code, &date_header,
- &compression, &reason) < 0) {
- log_warn(LD_HTTP,"Unparseable headers (server '%s:%d'). Closing.",
- conn->base_.address, conn->base_.port);
- tor_free(body); tor_free(headers);
- return -1;
- }
- if (!reason) reason = tor_strdup("[no reason given]");
- log_debug(LD_DIR,
- "Received response from directory server '%s:%d': %d %s "
- "(purpose: %d)",
- conn->base_.address, conn->base_.port, status_code,
- escaped(reason),
- conn->base_.purpose);
-
- if (conn->dirconn_direct) {
- char *guess = http_get_header(headers, X_ADDRESS_HEADER);
- if (guess) {
- router_new_address_suggestion(guess, conn);
- tor_free(guess);
- }
- }
- if (date_header > 0) {
-
- apparent_skew = conn->base_.timestamp_lastwritten - date_header;
- if (labs(apparent_skew)>ALLOW_DIRECTORY_TIME_SKEW) {
- int trusted = router_digest_is_trusted_dir(conn->identity_digest);
- clock_skew_warning(TO_CONN(conn), apparent_skew, trusted, LD_HTTP,
- "directory", "DIRSERV");
- skewed = 1;
- } else {
- log_debug(LD_HTTP, "Time on received directory is within tolerance; "
- "we are %ld seconds skewed. (That's okay.)", apparent_skew);
- }
- }
- (void) skewed;
- if (status_code == 503) {
- routerstatus_t *rs;
- dir_server_t *ds;
- const char *id_digest = conn->identity_digest;
- log_info(LD_DIR,"Received http status code %d (%s) from server "
- "'%s:%d'. I'll try again soon.",
- status_code, escaped(reason), conn->base_.address,
- conn->base_.port);
- if ((rs = router_get_mutable_consensus_status_by_id(id_digest)))
- rs->last_dir_503_at = now;
- if ((ds = router_get_fallback_dirserver_by_digest(id_digest)))
- ds->fake_status.last_dir_503_at = now;
- tor_free(body); tor_free(headers); tor_free(reason);
- return -1;
- }
- plausible = body_is_plausible(body, body_len, conn->base_.purpose);
- if (compression != NO_METHOD || !plausible) {
- char *new_body = NULL;
- size_t new_len = 0;
- compress_method_t guessed = detect_compression_method(body, body_len);
- if (compression == UNKNOWN_METHOD || guessed != compression) {
-
- const char *description1, *description2;
- if (compression == ZLIB_METHOD)
- description1 = "as deflated";
- else if (compression == GZIP_METHOD)
- description1 = "as gzipped";
- else if (compression == NO_METHOD)
- description1 = "as uncompressed";
- else
- description1 = "with an unknown Content-Encoding";
- if (guessed == ZLIB_METHOD)
- description2 = "deflated";
- else if (guessed == GZIP_METHOD)
- description2 = "gzipped";
- else if (!plausible)
- description2 = "confusing binary junk";
- else
- description2 = "uncompressed";
- log_info(LD_HTTP, "HTTP body from server '%s:%d' was labeled %s, "
- "but it seems to be %s.%s",
- conn->base_.address, conn->base_.port, description1,
- description2,
- (compression>0 && guessed>0)?" Trying both.":"");
- }
-
- if (compression == GZIP_METHOD || compression == ZLIB_METHOD)
- tor_gzip_uncompress(&new_body, &new_len, body, body_len, compression,
- !allow_partial, LOG_PROTOCOL_WARN);
-
- if (!new_body &&
- (guessed == GZIP_METHOD || guessed == ZLIB_METHOD) &&
- compression != guessed)
- tor_gzip_uncompress(&new_body, &new_len, body, body_len, guessed,
- !allow_partial, LOG_PROTOCOL_WARN);
-
- if (!plausible && !new_body) {
- log_fn(LOG_PROTOCOL_WARN, LD_HTTP,
- "Unable to decompress HTTP body (server '%s:%d').",
- conn->base_.address, conn->base_.port);
- tor_free(body); tor_free(headers); tor_free(reason);
- return -1;
- }
- if (new_body) {
- tor_free(body);
- body = new_body;
- body_len = new_len;
- }
- }
- if (conn->base_.purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
- int r;
- const char *flavname = conn->requested_resource;
- if (status_code != 200) {
- int severity = (status_code == 304) ? LOG_INFO : LOG_WARN;
- tor_log(severity, LD_DIR,
- "Received http status code %d (%s) from server "
- "'%s:%d' while fetching consensus directory.",
- status_code, escaped(reason), conn->base_.address,
- conn->base_.port);
- tor_free(body); tor_free(headers); tor_free(reason);
- networkstatus_consensus_download_failed(status_code, flavname);
- return -1;
- }
- log_info(LD_DIR,"Received consensus directory (size %d) from server "
- "'%s:%d'", (int)body_len, conn->base_.address, conn->base_.port);
- if ((r=networkstatus_set_current_consensus(body, flavname, 0,
- conn->identity_digest))<0) {
- log_fn(r<-1?LOG_WARN:LOG_INFO, LD_DIR,
- "Unable to load %s consensus directory downloaded from "
- "server '%s:%d'. I'll try again soon.",
- flavname, conn->base_.address, conn->base_.port);
- tor_free(body); tor_free(headers); tor_free(reason);
- networkstatus_consensus_download_failed(0, flavname);
- return -1;
- }
-
- connection_dir_close_consensus_fetches(conn, flavname);
-
- routers_update_all_from_networkstatus(now, 3);
- update_microdescs_from_networkstatus(now);
- update_microdesc_downloads(now);
- directory_info_has_arrived(now, 0, 0);
- log_info(LD_DIR, "Successfully loaded consensus.");
- }
- if (conn->base_.purpose == DIR_PURPOSE_FETCH_CERTIFICATE) {
- if (status_code != 200) {
- log_warn(LD_DIR,
- "Received http status code %d (%s) from server "
- "'%s:%d' while fetching \"/tor/keys/%s\".",
- status_code, escaped(reason), conn->base_.address,
- conn->base_.port, conn->requested_resource);
- connection_dir_download_cert_failed(conn, status_code);
- tor_free(body); tor_free(headers); tor_free(reason);
- return -1;
- }
- log_info(LD_DIR,"Received authority certificates (size %d) from server "
- "'%s:%d'", (int)body_len, conn->base_.address, conn->base_.port);
-
- src_code = -1;
- if (!strcmpstart(conn->requested_resource, "fp/")) {
- src_code = TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST;
- } else if (!strcmpstart(conn->requested_resource, "fp-sk/")) {
- src_code = TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_SK_DIGEST;
- }
- if (src_code != -1) {
- if (trusted_dirs_load_certs_from_string(body, src_code, 1,
- conn->identity_digest)<0) {
- log_warn(LD_DIR, "Unable to parse fetched certificates");
-
- connection_dir_download_cert_failed(conn, status_code);
- } else {
- directory_info_has_arrived(now, 0, 0);
- log_info(LD_DIR, "Successfully loaded certificates from fetch.");
- }
- } else {
- log_warn(LD_DIR,
- "Couldn't figure out what to do with fetched certificates for "
- "unknown resource %s",
- conn->requested_resource);
- connection_dir_download_cert_failed(conn, status_code);
- }
- }
- if (conn->base_.purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) {
- const char *msg;
- int st;
- log_info(LD_DIR,"Got votes (size %d) from server %s:%d",
- (int)body_len, conn->base_.address, conn->base_.port);
- if (status_code != 200) {
- log_warn(LD_DIR,
- "Received http status code %d (%s) from server "
- "'%s:%d' while fetching \"/tor/status-vote/next/%s.z\".",
- status_code, escaped(reason), conn->base_.address,
- conn->base_.port, conn->requested_resource);
- tor_free(body); tor_free(headers); tor_free(reason);
- return -1;
- }
- dirvote_add_vote(body, &msg, &st);
- if (st > 299) {
- log_warn(LD_DIR, "Error adding retrieved vote: %s", msg);
- } else {
- log_info(LD_DIR, "Added vote(s) successfully [msg: %s]", msg);
- }
- }
- if (conn->base_.purpose == DIR_PURPOSE_FETCH_DETACHED_SIGNATURES) {
- const char *msg = NULL;
- log_info(LD_DIR,"Got detached signatures (size %d) from server %s:%d",
- (int)body_len, conn->base_.address, conn->base_.port);
- if (status_code != 200) {
- log_warn(LD_DIR,
- "Received http status code %d (%s) from server '%s:%d' while fetching "
- "\"/tor/status-vote/next/consensus-signatures.z\".",
- status_code, escaped(reason), conn->base_.address,
- conn->base_.port);
- tor_free(body); tor_free(headers); tor_free(reason);
- return -1;
- }
- if (dirvote_add_signatures(body, conn->base_.address, &msg)<0) {
- log_warn(LD_DIR, "Problem adding detached signatures from %s:%d: %s",
- conn->base_.address, conn->base_.port, msg?msg:"???");
- }
- }
- if (conn->base_.purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
- conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO) {
- int was_ei = conn->base_.purpose == DIR_PURPOSE_FETCH_EXTRAINFO;
- smartlist_t *which = NULL;
- int n_asked_for = 0;
- int descriptor_digests = conn->requested_resource &&
- !strcmpstart(conn->requested_resource,"d/");
- log_info(LD_DIR,"Received %s (size %d) from server '%s:%d'",
- was_ei ? "extra server info" : "server info",
- (int)body_len, conn->base_.address, conn->base_.port);
- if (conn->requested_resource &&
- (!strcmpstart(conn->requested_resource,"d/") ||
- !strcmpstart(conn->requested_resource,"fp/"))) {
- which = smartlist_new();
- dir_split_resource_into_fingerprints(conn->requested_resource +
- (descriptor_digests ? 2 : 3),
- which, NULL, 0);
- n_asked_for = smartlist_len(which);
- }
- if (status_code != 200) {
- int dir_okay = status_code == 404 ||
- (status_code == 400 && !strcmp(reason, "Servers unavailable."));
-
- log_fn(dir_okay ? LOG_INFO : LOG_WARN, LD_DIR,
- "Received http status code %d (%s) from server '%s:%d' "
- "while fetching \"/tor/server/%s\". I'll try again soon.",
- status_code, escaped(reason), conn->base_.address,
- conn->base_.port, conn->requested_resource);
- if (!which) {
- connection_dir_download_routerdesc_failed(conn);
- } else {
- dir_routerdesc_download_failed(which, status_code,
- conn->router_purpose,
- was_ei, descriptor_digests);
- SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
- smartlist_free(which);
- }
- tor_free(body); tor_free(headers); tor_free(reason);
- return dir_okay ? 0 : -1;
- }
-
- if (which || (conn->requested_resource &&
- (!strcmpstart(conn->requested_resource, "all") ||
- (!strcmpstart(conn->requested_resource, "authority") &&
- get_options()->UseBridges)))) {
-
- if (was_ei) {
- router_load_extrainfo_from_string(body, NULL, SAVED_NOWHERE, which,
- descriptor_digests);
- } else {
-
-
- if (load_downloaded_routers(body, which, descriptor_digests,
- conn->router_purpose,
- conn->base_.address))
- directory_info_has_arrived(now, 0, 0);
- }
- }
- if (which) {
- log_info(LD_DIR, "Received %d/%d %s requested from %s:%d",
- n_asked_for-smartlist_len(which), n_asked_for,
- was_ei ? "extra-info documents" : "router descriptors",
- conn->base_.address, (int)conn->base_.port);
- if (smartlist_len(which)) {
- dir_routerdesc_download_failed(which, status_code,
- conn->router_purpose,
- was_ei, descriptor_digests);
- }
- SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
- smartlist_free(which);
- }
- if (directory_conn_is_self_reachability_test(conn))
- router_dirport_found_reachable();
- }
- if (conn->base_.purpose == DIR_PURPOSE_FETCH_MICRODESC) {
- smartlist_t *which = NULL;
- log_info(LD_DIR,"Received answer to microdescriptor request (status %d, "
- "size %d) from server '%s:%d'",
- status_code, (int)body_len, conn->base_.address,
- conn->base_.port);
- tor_assert(conn->requested_resource &&
- !strcmpstart(conn->requested_resource, "d/"));
- which = smartlist_new();
- dir_split_resource_into_fingerprints(conn->requested_resource+2,
- which, NULL,
- DSR_DIGEST256|DSR_BASE64);
- if (status_code != 200) {
- log_info(LD_DIR, "Received status code %d (%s) from server "
- "'%s:%d' while fetching \"/tor/micro/%s\". I'll try again "
- "soon.",
- status_code, escaped(reason), conn->base_.address,
- (int)conn->base_.port, conn->requested_resource);
- dir_microdesc_download_failed(which, status_code);
- SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
- smartlist_free(which);
- tor_free(body); tor_free(headers); tor_free(reason);
- return 0;
- } else {
- smartlist_t *mds;
- mds = microdescs_add_to_cache(get_microdesc_cache(),
- body, body+body_len, SAVED_NOWHERE, 0,
- now, which);
- if (smartlist_len(which)) {
-
- dir_microdesc_download_failed(which, status_code);
- }
- if (mds && smartlist_len(mds)) {
- control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
- count_loading_descriptors_progress());
- directory_info_has_arrived(now, 0, 1);
- }
- SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
- smartlist_free(which);
- smartlist_free(mds);
- }
- }
- if (conn->base_.purpose == DIR_PURPOSE_UPLOAD_DIR) {
- switch (status_code) {
- case 200: {
- dir_server_t *ds =
- router_get_trusteddirserver_by_digest(conn->identity_digest);
- char *rejected_hdr = http_get_header(headers,
- "X-Descriptor-Not-New: ");
- if (rejected_hdr) {
- if (!strcmp(rejected_hdr, "Yes")) {
- log_info(LD_GENERAL,
- "Authority '%s' declined our descriptor (not new)",
- ds->nickname);
-
-
- }
- tor_free(rejected_hdr);
- }
- log_info(LD_GENERAL,"eof (status 200) after uploading server "
- "descriptor: finished.");
- control_event_server_status(
- LOG_NOTICE, "ACCEPTED_SERVER_DESCRIPTOR DIRAUTH=%s:%d",
- conn->base_.address, conn->base_.port);
- ds->has_accepted_serverdesc = 1;
- if (directories_have_accepted_server_descriptor())
- control_event_server_status(LOG_NOTICE, "GOOD_SERVER_DESCRIPTOR");
- }
- break;
- case 400:
- log_warn(LD_GENERAL,"http status 400 (%s) response from "
- "dirserver '%s:%d'. Please correct.",
- escaped(reason), conn->base_.address, conn->base_.port);
- control_event_server_status(LOG_WARN,
- "BAD_SERVER_DESCRIPTOR DIRAUTH=%s:%d REASON=\"%s\"",
- conn->base_.address, conn->base_.port, escaped(reason));
- break;
- default:
- log_warn(LD_GENERAL,
- "http status %d (%s) reason unexpected while uploading "
- "descriptor to server '%s:%d').",
- status_code, escaped(reason), conn->base_.address,
- conn->base_.port);
- break;
- }
-
- }
- if (conn->base_.purpose == DIR_PURPOSE_UPLOAD_VOTE) {
- switch (status_code) {
- case 200: {
- log_notice(LD_DIR,"Uploaded a vote to dirserver %s:%d",
- conn->base_.address, conn->base_.port);
- }
- break;
- case 400:
- log_warn(LD_DIR,"http status 400 (%s) response after uploading "
- "vote to dirserver '%s:%d'. Please correct.",
- escaped(reason), conn->base_.address, conn->base_.port);
- break;
- default:
- log_warn(LD_GENERAL,
- "http status %d (%s) reason unexpected while uploading "
- "vote to server '%s:%d').",
- status_code, escaped(reason), conn->base_.address,
- conn->base_.port);
- break;
- }
-
- }
- if (conn->base_.purpose == DIR_PURPOSE_UPLOAD_SIGNATURES) {
- switch (status_code) {
- case 200: {
- log_notice(LD_DIR,"Uploaded signature(s) to dirserver %s:%d",
- conn->base_.address, conn->base_.port);
- }
- break;
- case 400:
- log_warn(LD_DIR,"http status 400 (%s) response after uploading "
- "signatures to dirserver '%s:%d'. Please correct.",
- escaped(reason), conn->base_.address, conn->base_.port);
- break;
- default:
- log_warn(LD_GENERAL,
- "http status %d (%s) reason unexpected while uploading "
- "signatures to server '%s:%d').",
- status_code, escaped(reason), conn->base_.address,
- conn->base_.port);
- break;
- }
-
- }
- if (conn->base_.purpose == DIR_PURPOSE_FETCH_RENDDESC_V2) {
- #define SEND_HS_DESC_FAILED_EVENT(reason) ( \
- control_event_hs_descriptor_failed(conn->rend_data, \
- conn->identity_digest, \
- reason) )
- #define SEND_HS_DESC_FAILED_CONTENT() ( \
- control_event_hs_descriptor_content(conn->rend_data->onion_address, \
- conn->requested_resource, \
- conn->identity_digest, \
- NULL) )
- tor_assert(conn->rend_data);
- log_info(LD_REND,"Received rendezvous descriptor (size %d, status %d "
- "(%s))",
- (int)body_len, status_code, escaped(reason));
- switch (status_code) {
- case 200:
- {
- rend_cache_entry_t *entry = NULL;
- if (rend_cache_store_v2_desc_as_client(body,
- conn->requested_resource, conn->rend_data, &entry) < 0) {
- log_warn(LD_REND,"Fetching v2 rendezvous descriptor failed. "
- "Retrying at another directory.");
-
- SEND_HS_DESC_FAILED_EVENT("BAD_DESC");
- SEND_HS_DESC_FAILED_CONTENT();
- } else {
- char service_id[REND_SERVICE_ID_LEN_BASE32 + 1];
-
- tor_assert(entry);
- rend_get_service_id(entry->parsed->pk, service_id);
-
- log_info(LD_REND, "Successfully fetched v2 rendezvous "
- "descriptor.");
- control_event_hs_descriptor_received(service_id,
- conn->rend_data,
- conn->identity_digest);
- control_event_hs_descriptor_content(service_id,
- conn->requested_resource,
- conn->identity_digest,
- body);
- conn->base_.purpose = DIR_PURPOSE_HAS_FETCHED_RENDDESC_V2;
- rend_client_desc_trynow(service_id);
- memwipe(service_id, 0, sizeof(service_id));
- }
- break;
- }
- case 404:
-
- log_info(LD_REND,"Fetching v2 rendezvous descriptor failed: "
- "Retrying at another directory.");
- SEND_HS_DESC_FAILED_EVENT("NOT_FOUND");
- SEND_HS_DESC_FAILED_CONTENT();
- break;
- case 400:
- log_warn(LD_REND, "Fetching v2 rendezvous descriptor failed: "
- "http status 400 (%s). Dirserver didn't like our "
- "v2 rendezvous query? Retrying at another directory.",
- escaped(reason));
- SEND_HS_DESC_FAILED_EVENT("QUERY_REJECTED");
- SEND_HS_DESC_FAILED_CONTENT();
- break;
- default:
- log_warn(LD_REND, "Fetching v2 rendezvous descriptor failed: "
- "http status %d (%s) response unexpected while "
- "fetching v2 hidden service descriptor (server '%s:%d'). "
- "Retrying at another directory.",
- status_code, escaped(reason), conn->base_.address,
- conn->base_.port);
- SEND_HS_DESC_FAILED_EVENT("UNEXPECTED");
- SEND_HS_DESC_FAILED_CONTENT();
- break;
- }
- }
- if (conn->base_.purpose == DIR_PURPOSE_UPLOAD_RENDDESC_V2) {
- #define SEND_HS_DESC_UPLOAD_FAILED_EVENT(reason) ( \
- control_event_hs_descriptor_upload_failed( \
- conn->identity_digest, \
- conn->rend_data->onion_address, \
- reason) )
- log_info(LD_REND,"Uploaded rendezvous descriptor (status %d "
- "(%s))",
- status_code, escaped(reason));
-
- tor_assert(conn->rend_data);
- switch (status_code) {
- case 200:
- log_info(LD_REND,
- "Uploading rendezvous descriptor: finished with status "
- "200 (%s)", escaped(reason));
- control_event_hs_descriptor_uploaded(conn->identity_digest,
- conn->rend_data->onion_address);
- rend_service_desc_has_uploaded(conn->rend_data);
- break;
- case 400:
- log_warn(LD_REND,"http status 400 (%s) response from dirserver "
- "'%s:%d'. Malformed rendezvous descriptor?",
- escaped(reason), conn->base_.address, conn->base_.port);
- SEND_HS_DESC_UPLOAD_FAILED_EVENT("UPLOAD_REJECTED");
- break;
- default:
- log_warn(LD_REND,"http status %d (%s) response unexpected (server "
- "'%s:%d').",
- status_code, escaped(reason), conn->base_.address,
- conn->base_.port);
- SEND_HS_DESC_UPLOAD_FAILED_EVENT("UNEXPECTED");
- break;
- }
- }
- tor_free(body); tor_free(headers); tor_free(reason);
- return 0;
- }
- int
- connection_dir_reached_eof(dir_connection_t *conn)
- {
- int retval;
- if (conn->base_.state != DIR_CONN_STATE_CLIENT_READING) {
- log_info(LD_HTTP,"conn reached eof, not reading. [state=%d] Closing.",
- conn->base_.state);
- connection_close_immediate(TO_CONN(conn));
- connection_mark_for_close(TO_CONN(conn));
- return -1;
- }
- retval = connection_dir_client_reached_eof(conn);
- if (retval == 0)
- conn->base_.state = DIR_CONN_STATE_CLIENT_FINISHED;
- connection_mark_for_close(TO_CONN(conn));
- return retval;
- }
- #define MAX_DIRECTORY_OBJECT_SIZE (10*(1<<20))
- #define MAX_VOTE_DL_SIZE (MAX_DIRECTORY_OBJECT_SIZE * 5)
- int
- connection_dir_process_inbuf(dir_connection_t *conn)
- {
- size_t max_size;
- tor_assert(conn);
- tor_assert(conn->base_.type == CONN_TYPE_DIR);
-
-
- if (conn->base_.state == DIR_CONN_STATE_SERVER_COMMAND_WAIT) {
- if (directory_handle_command(conn) < 0) {
- connection_mark_for_close(TO_CONN(conn));
- return -1;
- }
- return 0;
- }
- max_size =
- (TO_CONN(conn)->purpose == DIR_PURPOSE_FETCH_STATUS_VOTE) ?
- MAX_VOTE_DL_SIZE : MAX_DIRECTORY_OBJECT_SIZE;
- if (connection_get_inbuf_len(TO_CONN(conn)) > max_size) {
- log_warn(LD_HTTP,
- "Too much data received from directory connection (%s): "
- "denial of service attempt, or you need to upgrade?",
- conn->base_.address);
- connection_mark_for_close(TO_CONN(conn));
- return -1;
- }
- if (!conn->base_.inbuf_reached_eof)
- log_debug(LD_HTTP,"Got data, not eof. Leaving on inbuf.");
- return 0;
- }
- void
- connection_dir_about_to_close(dir_connection_t *dir_conn)
- {
- connection_t *conn = TO_CONN(dir_conn);
- if (conn->state < DIR_CONN_STATE_CLIENT_FINISHED) {
-
- connection_dir_request_failed(dir_conn);
- }
-
- if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2 &&
- dir_conn->rend_data &&
- strlen(dir_conn->rend_data->onion_address) == REND_SERVICE_ID_LEN_BASE32)
- rend_client_refetch_v2_renddesc(dir_conn->rend_data);
- }
- static void
- write_http_status_line(dir_connection_t *conn, int status,
- const char *reason_phrase)
- {
- char buf[256];
- if (tor_snprintf(buf, sizeof(buf), "HTTP/1.0 %d %s\r\n\r\n",
- status, reason_phrase ? reason_phrase : "OK") < 0) {
- log_warn(LD_BUG,"status line too long.");
- return;
- }
- log_debug(LD_DIRSERV,"Wrote status 'HTTP/1.0 %d %s'", status, reason_phrase);
- connection_write_to_buf(buf, strlen(buf), TO_CONN(conn));
- }
- static void
- write_http_response_header_impl(dir_connection_t *conn, ssize_t length,
- const char *type, const char *encoding,
- const char *extra_headers,
- long cache_lifetime)
- {
- char date[RFC1123_TIME_LEN+1];
- char tmp[1024];
- char *cp;
- time_t now = time(NULL);
- tor_assert(conn);
- format_rfc1123_time(date, now);
- cp = tmp;
- tor_snprintf(cp, sizeof(tmp),
- "HTTP/1.0 200 OK\r\nDate: %s\r\n",
- date);
- cp += strlen(tmp);
- if (type) {
- tor_snprintf(cp, sizeof(tmp)-(cp-tmp), "Content-Type: %s\r\n", type);
- cp += strlen(cp);
- }
- if (!is_local_addr(&conn->base_.addr)) {
-
- tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
- X_ADDRESS_HEADER "%s\r\n", conn->base_.address);
- cp += strlen(cp);
- }
- if (encoding) {
- tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
- "Content-Encoding: %s\r\n", encoding);
- cp += strlen(cp);
- }
- if (length >= 0) {
- tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
- "Content-Length: %ld\r\n", (long)length);
- cp += strlen(cp);
- }
- if (cache_lifetime > 0) {
- char expbuf[RFC1123_TIME_LEN+1];
- format_rfc1123_time(expbuf, (time_t)(now + cache_lifetime));
-
- tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
- "Expires: %s\r\n", expbuf);
- cp += strlen(cp);
- } else if (cache_lifetime == 0) {
-
- strlcpy(cp, "Pragma: no-cache\r\n", sizeof(tmp)-(cp-tmp));
- cp += strlen(cp);
- }
- if (extra_headers) {
- strlcpy(cp, extra_headers, sizeof(tmp)-(cp-tmp));
- cp += strlen(cp);
- }
- if (sizeof(tmp)-(cp-tmp) > 3)
- memcpy(cp, "\r\n", 3);
- else
- tor_assert(0);
- connection_write_to_buf(tmp, strlen(tmp), TO_CONN(conn));
- }
- static void
- write_http_response_header(dir_connection_t *conn, ssize_t length,
- int compressed, long cache_lifetime)
- {
- write_http_response_header_impl(conn, length,
- compressed?"application/octet-stream":"text/plain",
- compressed?"deflate":"identity",
- NULL,
- cache_lifetime);
- }
- int
- client_likes_consensus(networkstatus_t *v, const char *want_url)
- {
- smartlist_t *want_authorities = smartlist_new();
- int need_at_least;
- int have = 0;
- dir_split_resource_into_fingerprints(want_url, want_authorities, NULL, 0);
- need_at_least = smartlist_len(want_authorities)/2+1;
- SMARTLIST_FOREACH_BEGIN(want_authorities, const char *, d) {
- char want_digest[DIGEST_LEN];
- size_t want_len = strlen(d)/2;
- if (want_len > DIGEST_LEN)
- want_len = DIGEST_LEN;
- if (base16_decode(want_digest, DIGEST_LEN, d, want_len*2) < 0) {
- log_fn(LOG_PROTOCOL_WARN, LD_DIR,
- "Failed to decode requested authority digest %s.", escaped(d));
- continue;
- };
- SMARTLIST_FOREACH_BEGIN(v->voters, networkstatus_voter_info_t *, vi) {
- if (smartlist_len(vi->sigs) &&
- tor_memeq(vi->identity_digest, want_digest, want_len)) {
- have++;
- break;
- };
- } SMARTLIST_FOREACH_END(vi);
-
- if (have >= need_at_least)
- break;
- } SMARTLIST_FOREACH_END(d);
- SMARTLIST_FOREACH(want_authorities, char *, d, tor_free(d));
- smartlist_free(want_authorities);
- return (have >= need_at_least);
- }
- STATIC zlib_compression_level_t
- choose_compression_level(ssize_t n_bytes)
- {
- if (! have_been_under_memory_pressure()) {
- return HIGH_COMPRESSION;
- } else if (n_bytes < 0) {
- return HIGH_COMPRESSION;
- } else if (n_bytes < 1024) {
- return LOW_COMPRESSION;
- } else if (n_bytes < 2048) {
- return MEDIUM_COMPRESSION;
- } else {
- return HIGH_COMPRESSION;
- }
- }
- typedef struct get_handler_args_t {
-
- int compressed;
-
- time_t if_modified_since;
-
- const char *url;
-
- const char *headers;
- } get_handler_args_t;
- typedef struct url_table_ent_s {
- const char *string;
- int is_prefix;
- int (*handler)(dir_connection_t *conn, const get_handler_args_t *args);
- } url_table_ent_t;
- static int handle_get_frontpage(dir_connection_t *conn,
- const get_handler_args_t *args);
- static int handle_get_current_consensus(dir_connection_t *conn,
- const get_handler_args_t *args);
- static int handle_get_status_vote(dir_connection_t *conn,
- const get_handler_args_t *args);
- static int handle_get_microdesc(dir_connection_t *conn,
- const get_handler_args_t *args);
- static int handle_get_descriptor(dir_connection_t *conn,
- const get_handler_args_t *args);
- static int handle_get_keys(dir_connection_t *conn,
- const get_handler_args_t *args);
- static int handle_get_rendezvous2(dir_connection_t *conn,
- const get_handler_args_t *args);
- static int handle_get_robots(dir_connection_t *conn,
- const get_handler_args_t *args);
- static int handle_get_networkstatus_bridges(dir_connection_t *conn,
- const get_handler_args_t *args);
- static const url_table_ent_t url_table[] = {
- { "/tor/", 0, handle_get_frontpage },
- { "/tor/status-vote/current/consensus", 1, handle_get_current_consensus },
- { "/tor/status-vote/current/", 1, handle_get_status_vote },
- { "/tor/status-vote/next/", 1, handle_get_status_vote },
- { "/tor/micro/d/", 1, handle_get_microdesc },
- { "/tor/server/", 1, handle_get_descriptor },
- { "/tor/extra/", 1, handle_get_descriptor },
- { "/tor/keys/", 1, handle_get_keys },
- { "/tor/rendezvous2/", 1, handle_get_rendezvous2 },
- { "/tor/robots.txt", 0, handle_get_robots },
- { "/tor/networkstatus-bridges", 0, handle_get_networkstatus_bridges },
- { NULL, 0, NULL },
- };
- STATIC int
- directory_handle_command_get(dir_connection_t *conn, const char *headers,
- const char *req_body, size_t req_body_len)
- {
- char *url, *url_mem, *header;
- time_t if_modified_since = 0;
- int compressed;
- size_t url_len;
-
- (void)req_body;
- (void)req_body_len;
- log_debug(LD_DIRSERV,"Received GET command.");
- conn->base_.state = DIR_CONN_STATE_SERVER_WRITING;
- if (parse_http_url(headers, &url) < 0) {
- write_http_status_line(conn, 400, "Bad request");
- return 0;
- }
- if ((header = http_get_header(headers, "If-Modified-Since: "))) {
- struct tm tm;
- if (parse_http_time(header, &tm) == 0) {
- if (tor_timegm(&tm, &if_modified_since)<0) {
- if_modified_since = 0;
- } else {
- log_debug(LD_DIRSERV, "If-Modified-Since is '%s'.", escaped(header));
- }
- }
-
- tor_free(header);
- }
- log_debug(LD_DIRSERV,"rewritten url as '%s'.", escaped(url));
- url_mem = url;
- url_len = strlen(url);
- compressed = url_len > 2 && !strcmp(url+url_len-2, ".z");
- if (compressed) {
- url[url_len-2] = '\0';
- url_len -= 2;
- }
- get_handler_args_t args;
- args.url = url;
- args.headers = headers;
- args.if_modified_since = if_modified_since;
- args.compressed = compressed;
- int i, result = -1;
- for (i = 0; url_table[i].string; ++i) {
- int match;
- if (url_table[i].is_prefix) {
- match = !strcmpstart(url, url_table[i].string);
- } else {
- match = !strcmp(url, url_table[i].string);
- }
- if (match) {
- result = url_table[i].handler(conn, &args);
- goto done;
- }
- }
-
- write_http_status_line(conn, 404, "Not found");
- result = 0;
- done:
- tor_free(url_mem);
- return result;
- }
- static int
- handle_get_frontpage(dir_connection_t *conn, const get_handler_args_t *args)
- {
- (void) args;
- const char *frontpage = get_dirportfrontpage();
- if (frontpage) {
- size_t dlen;
- dlen = strlen(frontpage);
-
-
- write_http_response_header_impl(conn, dlen, "text/html", "identity",
- NULL, DIRPORTFRONTPAGE_CACHE_LIFETIME);
- connection_write_to_buf(frontpage, dlen, TO_CONN(conn));
- } else {
- write_http_status_line(conn, 404, "Not found");
- }
- return 0;
- }
- static int
- handle_get_current_consensus(dir_connection_t *conn,
- const get_handler_args_t *args)
- {
- const char *url = args->url;
- const int compressed = args->compressed;
- const time_t if_modified_since = args->if_modified_since;
- {
-
- smartlist_t *dir_fps = smartlist_new();
- long lifetime = NETWORKSTATUS_CACHE_LIFETIME;
- if (1) {
- networkstatus_t *v;
- time_t now = time(NULL);
- const char *want_fps = NULL;
- char *flavor = NULL;
- int flav = FLAV_NS;
- #define CONSENSUS_URL_PREFIX "/tor/status-vote/current/consensus/"
- #define CONSENSUS_FLAVORED_PREFIX "/tor/status-vote/current/consensus-"
-
- if (!strcmpstart(url, CONSENSUS_FLAVORED_PREFIX)) {
- const char *f, *cp;
- f = url + strlen(CONSENSUS_FLAVORED_PREFIX);
- cp = strchr(f, '/');
- if (cp) {
- want_fps = cp+1;
- flavor = tor_strndup(f, cp-f);
- } else {
- flavor = tor_strdup(f);
- }
- flav = networkstatus_parse_flavor_name(flavor);
- if (flav < 0)
- flav = FLAV_NS;
- } else {
- if (!strcmpstart(url, CONSENSUS_URL_PREFIX))
- want_fps = url+strlen(CONSENSUS_URL_PREFIX);
- }
- v = networkstatus_get_latest_consensus_by_flavor(flav);
- if (v && want_fps &&
- !client_likes_consensus(v, want_fps)) {
- write_http_status_line(conn, 404, "Consensus not signed by sufficient "
- "number of requested authorities");
- smartlist_free(dir_fps);
- geoip_note_ns_response(GEOIP_REJECT_NOT_ENOUGH_SIGS);
- tor_free(flavor);
- goto done;
- }
- {
- char *fp = tor_malloc_zero(DIGEST_LEN);
- if (flavor)
- strlcpy(fp, flavor, DIGEST_LEN);
- tor_free(flavor);
- smartlist_add(dir_fps, fp);
- }
- lifetime = (v && v->fresh_until > now) ? v->fresh_until - now : 0;
- }
- if (!smartlist_len(dir_fps)) {
- write_http_status_line(conn, 503, "Network status object unavailable");
- smartlist_free(dir_fps);
- geoip_note_ns_response(GEOIP_REJECT_UNAVAILABLE);
- goto done;
- }
- if (!dirserv_remove_old_statuses(dir_fps, if_modified_since)) {
- write_http_status_line(conn, 404, "Not found");
- SMARTLIST_FOREACH(dir_fps, char *, cp, tor_free(cp));
- smartlist_free(dir_fps);
- geoip_note_ns_response(GEOIP_REJECT_NOT_FOUND);
- goto done;
- } else if (!smartlist_len(dir_fps)) {
- write_http_status_line(conn, 304, "Not modified");
- SMARTLIST_FOREACH(dir_fps, char *, cp, tor_free(cp));
- smartlist_free(dir_fps);
- geoip_note_ns_response(GEOIP_REJECT_NOT_MODIFIED);
- goto done;
- }
- size_t dlen = dirserv_estimate_data_size(dir_fps, 0, compressed);
- if (global_write_bucket_low(TO_CONN(conn), dlen, 2)) {
- log_debug(LD_DIRSERV,
- "Client asked for network status lists, but we've been "
- "writing too many bytes lately. Sending 503 Dir busy.");
- write_http_status_line(conn, 503, "Directory busy, try again later");
- SMARTLIST_FOREACH(dir_fps, char *, fp, tor_free(fp));
- smartlist_free(dir_fps);
- geoip_note_ns_response(GEOIP_REJECT_BUSY);
- goto done;
- }
- if (1) {
- tor_addr_t addr;
- if (tor_addr_parse(&addr, (TO_CONN(conn))->address) >= 0) {
- geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS,
- &addr, NULL,
- time(NULL));
- geoip_note_ns_response(GEOIP_SUCCESS);
-
- if (conn->dirreq_id)
- geoip_start_dirreq(conn->dirreq_id, dlen, DIRREQ_TUNNELED);
- else
- geoip_start_dirreq(TO_CONN(conn)->global_identifier, dlen,
- DIRREQ_DIRECT);
- }
- }
- write_http_response_header(conn, -1, compressed,
- smartlist_len(dir_fps) == 1 ? lifetime : 0);
- conn->fingerprint_stack = dir_fps;
- if (! compressed)
- conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD, HIGH_COMPRESSION);
-
- conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
- connection_dirserv_flushed_some(conn);
- goto done;
- }
- done:
- return 0;
- }
- static int
- handle_get_status_vote(dir_connection_t *conn, const get_handler_args_t *args)
- {
- const char *url = args->url;
- const int compressed = args->compressed;
- {
- int current;
- ssize_t body_len = 0;
- ssize_t estimated_len = 0;
- smartlist_t *items = smartlist_new();
- smartlist_t *dir_items = smartlist_new();
- int lifetime = 60;
- url += strlen("/tor/status-vote/");
- current = !strcmpstart(url, "current/");
- url = strchr(url, '/');
- tor_assert(url);
- ++url;
- if (!strcmp(url, "consensus")) {
- const char *item;
- tor_assert(!current);
- if ((item = dirvote_get_pending_consensus(FLAV_NS)))
- smartlist_add(items, (char*)item);
- } else if (!current && !strcmp(url, "consensus-signatures")) {
-
- const char *item;
- if ((item=dirvote_get_pending_detached_signatures()))
- smartlist_add(items, (char*)item);
- } else if (!strcmp(url, "authority")) {
- const cached_dir_t *d;
- int flags = DGV_BY_ID |
- (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
- if ((d=dirvote_get_vote(NULL, flags)))
- smartlist_add(dir_items, (cached_dir_t*)d);
- } else {
- const cached_dir_t *d;
- smartlist_t *fps = smartlist_new();
- int flags;
- if (!strcmpstart(url, "d/")) {
- url += 2;
- flags = DGV_INCLUDE_PENDING | DGV_INCLUDE_PREVIOUS;
- } else {
- flags = DGV_BY_ID |
- (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
- }
- dir_split_resource_into_fingerprints(url, fps, NULL,
- DSR_HEX|DSR_SORT_UNIQ);
- SMARTLIST_FOREACH(fps, char *, fp, {
- if ((d = dirvote_get_vote(fp, flags)))
- smartlist_add(dir_items, (cached_dir_t*)d);
- tor_free(fp);
- });
- smartlist_free(fps);
- }
- if (!smartlist_len(dir_items) && !smartlist_len(items)) {
- write_http_status_line(conn, 404, "Not found");
- goto vote_done;
- }
- SMARTLIST_FOREACH(dir_items, cached_dir_t *, d,
- body_len += compressed ? d->dir_z_len : d->dir_len);
- estimated_len += body_len;
- SMARTLIST_FOREACH(items, const char *, item, {
- size_t ln = strlen(item);
- if (compressed) {
- estimated_len += ln/2;
- } else {
- body_len += ln; estimated_len += ln;
- }
- });
- if (global_write_bucket_low(TO_CONN(conn), estimated_len, 2)) {
- write_http_status_line(conn, 503, "Directory busy, try again later");
- goto vote_done;
- }
- write_http_response_header(conn, body_len ? body_len : -1, compressed,
- lifetime);
- if (smartlist_len(items)) {
- if (compressed) {
- conn->zlib_state = tor_zlib_new(1, ZLIB_METHOD,
- choose_compression_level(estimated_len));
- SMARTLIST_FOREACH(items, const char *, c,
- connection_write_to_buf_zlib(c, strlen(c), conn, 0));
- connection_write_to_buf_zlib("", 0, conn, 1);
- } else {
- SMARTLIST_FOREACH(items, const char *, c,
- connection_write_to_buf(c, strlen(c), TO_CONN(conn)));
- }
- } else {
- SMARTLIST_FOREACH(dir_items, cached_dir_t *, d,
- connection_write_to_buf(compressed ? d->dir_z : d->dir,
- compressed ? d->dir_z_len : d->dir_len,
- TO_CONN(conn)));
- }
- vote_done:
- smartlist_free(items);
- smartlist_free(dir_items);
- goto done;
- }
- done:
- return 0;
- }
- static int
- handle_get_microdesc(dir_connection_t *conn, const get_handler_args_t *args)
- {
- const char *url = args->url;
- const int compressed = args->compressed;
- {
- smartlist_t *fps = smartlist_new();
- dir_split_resource_into_fingerprints(url+strlen("/tor/micro/d/"),
- fps, NULL,
- DSR_DIGEST256|DSR_BASE64|DSR_SORT_UNIQ);
- if (!dirserv_have_any_microdesc(fps)) {
- write_http_status_line(conn, 404, "Not found");
- SMARTLIST_FOREACH(fps, char *, fp, tor_free(fp));
- smartlist_free(fps);
- goto done;
- }
- size_t dlen = dirserv_estimate_microdesc_size(fps, compressed);
- if (global_write_bucket_low(TO_CONN(conn), dlen, 2)) {
- log_info(LD_DIRSERV,
- "Client asked for server descriptors, but we've been "
- "writing too many bytes lately. Sending 503 Dir busy.");
- write_http_status_line(conn, 503, "Directory busy, try again later");
- SMARTLIST_FOREACH(fps, char *, fp, tor_free(fp));
- smartlist_free(fps);
- goto done;
- }
- write_http_response_header(conn, -1, compressed, MICRODESC_CACHE_LIFETIME);
- conn->dir_spool_src = DIR_SPOOL_MICRODESC;
- conn->fingerprint_stack = fps;
- if (compressed)
- conn->zlib_state = tor_zlib_new(1, ZLIB_METHOD,
- choose_compression_level(dlen));
- connection_dirserv_flushed_some(conn);
- goto done;
- }
- done:
- return 0;
- }
- static int
- handle_get_descriptor(dir_connection_t *conn, const get_handler_args_t *args)
- {
- const char *url = args->url;
- const int compressed = args->compressed;
- const or_options_t *options = get_options();
- if (!strcmpstart(url,"/tor/server/") ||
- (!options->BridgeAuthoritativeDir &&
- !options->BridgeRelay && !strcmpstart(url,"/tor/extra/"))) {
- size_t dlen;
- int res;
- const char *msg;
- int cache_lifetime = 0;
- int is_extra = !strcmpstart(url,"/tor/extra/");
- url += is_extra ? strlen("/tor/extra/") : strlen("/tor/server/");
- conn->fingerprint_stack = smartlist_new();
- res = dirserv_get_routerdesc_fingerprints(conn->fingerprint_stack, url,
- &msg,
- !connection_dir_is_encrypted(conn),
- is_extra);
- if (!strcmpstart(url, "fp/")) {
- if (smartlist_len(conn->fingerprint_stack) == 1)
- cache_lifetime = ROUTERDESC_CACHE_LIFETIME;
- } else if (!strcmpstart(url, "authority")) {
- cache_lifetime = ROUTERDESC_CACHE_LIFETIME;
- } else if (!strcmpstart(url, "all")) {
- cache_lifetime = FULL_DIR_CACHE_LIFETIME;
- } else if (!strcmpstart(url, "d/")) {
- if (smartlist_len(conn->fingerprint_stack) == 1)
- cache_lifetime = ROUTERDESC_BY_DIGEST_CACHE_LIFETIME;
- }
- if (!strcmpstart(url, "d/"))
- conn->dir_spool_src =
- is_extra ? DIR_SPOOL_EXTRA_BY_DIGEST : DIR_SPOOL_SERVER_BY_DIGEST;
- else
- conn->dir_spool_src =
- is_extra ? DIR_SPOOL_EXTRA_BY_FP : DIR_SPOOL_SERVER_BY_FP;
- if (!dirserv_have_any_serverdesc(conn->fingerprint_stack,
- conn->dir_spool_src)) {
- res = -1;
- msg = "Not found";
- }
- if (res < 0)
- write_http_status_line(conn, 404, msg);
- else {
- dlen = dirserv_estimate_data_size(conn->fingerprint_stack,
- 1, compressed);
- if (global_write_bucket_low(TO_CONN(conn), dlen, 2)) {
- log_info(LD_DIRSERV,
- "Client asked for server descriptors, but we've been "
- "writing too many bytes lately. Sending 503 Dir busy.");
- write_http_status_line(conn, 503, "Directory busy, try again later");
- conn->dir_spool_src = DIR_SPOOL_NONE;
- goto done;
- }
- write_http_response_header(conn, -1, compressed, cache_lifetime);
- if (compressed)
- conn->zlib_state = tor_zlib_new(1, ZLIB_METHOD,
- choose_compression_level(dlen));
-
- connection_dirserv_flushed_some(conn);
- }
- goto done;
- }
- done:
- return 0;
- }
- static int
- handle_get_keys(dir_connection_t *conn, const get_handler_args_t *args)
- {
- const char *url = args->url;
- const int compressed = args->compressed;
- const time_t if_modified_since = args->if_modified_since;
- {
- smartlist_t *certs = smartlist_new();
- ssize_t len = -1;
- if (!strcmp(url, "/tor/keys/all")) {
- authority_cert_get_all(certs);
- } else if (!strcmp(url, "/tor/keys/authority")) {
- authority_cert_t *cert = get_my_v3_authority_cert();
- if (cert)
- smartlist_add(certs, cert);
- } else if (!strcmpstart(url, "/tor/keys/fp/")) {
- smartlist_t *fps = smartlist_new();
- dir_split_resource_into_fingerprints(url+strlen("/tor/keys/fp/"),
- fps, NULL,
- DSR_HEX|DSR_SORT_UNIQ);
- SMARTLIST_FOREACH(fps, char *, d, {
- authority_cert_t *c = authority_cert_get_newest_by_id(d);
- if (c) smartlist_add(certs, c);
- tor_free(d);
- });
- smartlist_free(fps);
- } else if (!strcmpstart(url, "/tor/keys/sk/")) {
- smartlist_t *fps = smartlist_new();
- dir_split_resource_into_fingerprints(url+strlen("/tor/keys/sk/"),
- fps, NULL,
- DSR_HEX|DSR_SORT_UNIQ);
- SMARTLIST_FOREACH(fps, char *, d, {
- authority_cert_t *c = authority_cert_get_by_sk_digest(d);
- if (c) smartlist_add(certs, c);
- tor_free(d);
- });
- smartlist_free(fps);
- } else if (!strcmpstart(url, "/tor/keys/fp-sk/")) {
- smartlist_t *fp_sks = smartlist_new();
- dir_split_resource_into_fingerprint_pairs(url+strlen("/tor/keys/fp-sk/"),
- fp_sks);
- SMARTLIST_FOREACH(fp_sks, fp_pair_t *, pair, {
- authority_cert_t *c = authority_cert_get_by_digests(pair->first,
- pair->second);
- if (c) smartlist_add(certs, c);
- tor_free(pair);
- });
- smartlist_free(fp_sks);
- } else {
- write_http_status_line(conn, 400, "Bad request");
- goto keys_done;
- }
- if (!smartlist_len(certs)) {
- write_http_status_line(conn, 404, "Not found");
- goto keys_done;
- }
- SMARTLIST_FOREACH(certs, authority_cert_t *, c,
- if (c->cache_info.published_on < if_modified_since)
- SMARTLIST_DEL_CURRENT(certs, c));
- if (!smartlist_len(certs)) {
- write_http_status_line(conn, 304, "Not modified");
- goto keys_done;
- }
- len = 0;
- SMARTLIST_FOREACH(certs, authority_cert_t *, c,
- len += c->cache_info.signed_descriptor_len);
- if (global_write_bucket_low(TO_CONN(conn), compressed?len/2:len, 2)) {
- write_http_status_line(conn, 503, "Directory busy, try again later");
- goto keys_done;
- }
- write_http_response_header(conn, compressed?-1:len, compressed, 60*60);
- if (compressed) {
- conn->zlib_state = tor_zlib_new(1, ZLIB_METHOD,
- choose_compression_level(len));
- SMARTLIST_FOREACH(certs, authority_cert_t *, c,
- connection_write_to_buf_zlib(c->cache_info.signed_descriptor_body,
- c->cache_info.signed_descriptor_len,
- conn, 0));
- connection_write_to_buf_zlib("", 0, conn, 1);
- } else {
- SMARTLIST_FOREACH(certs, authority_cert_t *, c,
- connection_write_to_buf(c->cache_info.signed_descriptor_body,
- c->cache_info.signed_descriptor_len,
- TO_CONN(conn)));
- }
- keys_done:
- smartlist_free(certs);
- goto done;
- }
- done:
- return 0;
- }
- static int
- handle_get_rendezvous2(dir_connection_t *conn, const get_handler_args_t *args)
- {
- const char *url = args->url;
- if (connection_dir_is_encrypted(conn)) {
-
- const char *descp;
- const char *query = url + strlen("/tor/rendezvous2/");
- if (rend_valid_descriptor_id(query)) {
- log_info(LD_REND, "Got a v2 rendezvous descriptor request for ID '%s'",
- safe_str(escaped(query)));
- switch (rend_cache_lookup_v2_desc_as_dir(query, &descp)) {
- case 1:
- write_http_response_header(conn, strlen(descp), 0, 0);
- connection_write_to_buf(descp, strlen(descp), TO_CONN(conn));
- break;
- case 0:
- write_http_status_line(conn, 404, "Not found");
- break;
- case -1:
- write_http_status_line(conn, 400, "Bad request");
- break;
- }
- } else {
- write_http_status_line(conn, 400, "Bad request");
- }
- goto done;
- } else {
-
- write_http_status_line(conn, 404, "Not found");
- }
- done:
- return 0;
- }
- static int
- handle_get_networkstatus_bridges(dir_connection_t *conn,
- const get_handler_args_t *args)
- {
- const char *headers = args->headers;
- const or_options_t *options = get_options();
- if (options->BridgeAuthoritativeDir &&
- options->BridgePassword_AuthDigest_ &&
- connection_dir_is_encrypted(conn)) {
- char *status;
- char digest[DIGEST256_LEN];
- char *header = http_get_header(headers, "Authorization: Basic ");
- if (header)
- crypto_digest256(digest, header, strlen(header), DIGEST_SHA256);
-
- if (!header ||
- tor_memneq(digest,
- options->BridgePassword_AuthDigest_, DIGEST256_LEN)) {
- write_http_status_line(conn, 404, "Not found");
- tor_free(header);
- goto done;
- }
- tor_free(header);
-
- status = networkstatus_getinfo_by_purpose("bridge", time(NULL));
- size_t dlen = strlen(status);
- write_http_response_header(conn, dlen, 0, 0);
- connection_write_to_buf(status, dlen, TO_CONN(conn));
- tor_free(status);
- goto done;
- }
- done:
- return 0;
- }
- static int
- handle_get_robots(dir_connection_t *conn, const get_handler_args_t *args)
- {
- (void)args;
- {
- const char robots[] = "User-agent: *\r\nDisallow: /\r\n";
- size_t len = strlen(robots);
- write_http_response_header(conn, len, 0, ROBOTS_CACHE_LIFETIME);
- connection_write_to_buf(robots, len, TO_CONN(conn));
- }
- return 0;
- }
- static int
- directory_handle_command_post(dir_connection_t *conn, const char *headers,
- const char *body, size_t body_len)
- {
- char *url = NULL;
- const or_options_t *options = get_options();
- log_debug(LD_DIRSERV,"Received POST command.");
- conn->base_.state = DIR_CONN_STATE_SERVER_WRITING;
- if (!public_server_mode(options)) {
- log_info(LD_DIR, "Rejected dir post request from %s "
- "since we're not a public relay.", conn->base_.address);
- write_http_status_line(conn, 503, "Not acting as a public relay");
- goto done;
- }
- if (parse_http_url(headers, &url) < 0) {
- write_http_status_line(conn, 400, "Bad request");
- return 0;
- }
- log_debug(LD_DIRSERV,"rewritten url as '%s'.", escaped(url));
-
- if (connection_dir_is_encrypted(conn) &&
- !strcmpstart(url,"/tor/rendezvous2/publish")) {
- if (rend_cache_store_v2_desc_as_dir(body) < 0) {
- log_warn(LD_REND, "Rejected v2 rend descriptor (length %d) from %s.",
- (int)body_len, conn->base_.address);
- write_http_status_line(conn, 400,
- "Invalid v2 service descriptor rejected");
- } else {
- write_http_status_line(conn, 200, "Service descriptor (v2) stored");
- log_info(LD_REND, "Handled v2 rendezvous descriptor post: accepted");
- }
- goto done;
- }
- if (!authdir_mode(options)) {
-
- write_http_status_line(conn, 400, "Nonauthoritative directory does not "
- "accept posted server descriptors");
- goto done;
- }
- if (authdir_mode_handles_descs(options, -1) &&
- !strcmp(url,"/tor/")) {
- const char *msg = "[None]";
- uint8_t purpose = authdir_mode_bridge(options) ?
- ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
- was_router_added_t r = dirserv_add_multiple_descriptors(body, purpose,
- conn->base_.address, &msg);
- tor_assert(msg);
- if (r == ROUTER_ADDED_NOTIFY_GENERATOR) {
-
- log_info(LD_DIRSERV,
- "Problematic router descriptor or extra-info from %s "
- "(\"%s\").",
- conn->base_.address, msg);
- write_http_status_line(conn, 400, msg);
- } else if (r == ROUTER_ADDED_SUCCESSFULLY) {
- write_http_status_line(conn, 200, msg);
- } else if (WRA_WAS_OUTDATED(r)) {
- write_http_response_header_impl(conn, -1, NULL, NULL,
- "X-Descriptor-Not-New: Yes\r\n", -1);
- } else {
- log_info(LD_DIRSERV,
- "Rejected router descriptor or extra-info from %s "
- "(\"%s\").",
- conn->base_.address, msg);
- write_http_status_line(conn, 400, msg);
- }
- goto done;
- }
- if (authdir_mode_v3(options) &&
- !strcmp(url,"/tor/post/vote")) {
- const char *msg = "OK";
- int status;
- if (dirvote_add_vote(body, &msg, &status)) {
- write_http_status_line(conn, status, "Vote stored");
- } else {
- tor_assert(msg);
- log_warn(LD_DIRSERV, "Rejected vote from %s (\"%s\").",
- conn->base_.address, msg);
- write_http_status_line(conn, status, msg);
- }
- goto done;
- }
- if (authdir_mode_v3(options) &&
- !strcmp(url,"/tor/post/consensus-signature")) {
- const char *msg = NULL;
- if (dirvote_add_signatures(body, conn->base_.address, &msg)>=0) {
- write_http_status_line(conn, 200, msg?msg:"Signatures stored");
- } else {
- log_warn(LD_DIR, "Unable to store signatures posted by %s: %s",
- conn->base_.address, msg?msg:"???");
- write_http_status_line(conn, 400, msg?msg:"Unable to store signatures");
- }
- goto done;
- }
-
- write_http_status_line(conn, 404, "Not found");
- done:
- tor_free(url);
- return 0;
- }
- static int
- directory_handle_command(dir_connection_t *conn)
- {
- char *headers=NULL, *body=NULL;
- size_t body_len=0;
- int r;
- tor_assert(conn);
- tor_assert(conn->base_.type == CONN_TYPE_DIR);
- switch (connection_fetch_from_buf_http(TO_CONN(conn),
- &headers, MAX_HEADERS_SIZE,
- &body, &body_len, MAX_DIR_UL_SIZE, 0)) {
- case -1:
- log_warn(LD_DIRSERV,
- "Request too large from address '%s' to DirPort. Closing.",
- safe_str(conn->base_.address));
- return -1;
- case 0:
- log_debug(LD_DIRSERV,"command not all here yet.");
- return 0;
-
- }
- http_set_address_origin(headers, TO_CONN(conn));
-
-
-
- if (!strncasecmp(headers,"GET",3))
- r = directory_handle_command_get(conn, headers, body, body_len);
- else if (!strncasecmp(headers,"POST",4))
- r = directory_handle_command_post(conn, headers, body, body_len);
- else {
- log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
- "Got headers %s with unknown command. Closing.",
- escaped(headers));
- r = -1;
- }
- tor_free(headers); tor_free(body);
- return r;
- }
- int
- connection_dir_finished_flushing(dir_connection_t *conn)
- {
- tor_assert(conn);
- tor_assert(conn->base_.type == CONN_TYPE_DIR);
-
- if (conn->dirreq_id)
- geoip_change_dirreq_state(conn->dirreq_id, DIRREQ_TUNNELED,
- DIRREQ_FLUSHING_DIR_CONN_FINISHED);
- else
- geoip_change_dirreq_state(TO_CONN(conn)->global_identifier,
- DIRREQ_DIRECT,
- DIRREQ_FLUSHING_DIR_CONN_FINISHED);
- switch (conn->base_.state) {
- case DIR_CONN_STATE_CONNECTING:
- case DIR_CONN_STATE_CLIENT_SENDING:
- log_debug(LD_DIR,"client finished sending command.");
- conn->base_.state = DIR_CONN_STATE_CLIENT_READING;
- return 0;
- case DIR_CONN_STATE_SERVER_WRITING:
- if (conn->dir_spool_src != DIR_SPOOL_NONE) {
- #ifdef USE_BUFFEREVENTS
-
- log_debug(LD_DIRSERV, "Emptied a dirserv buffer, but still spooling.");
- #else
- log_warn(LD_BUG, "Emptied a dirserv buffer, but it's still spooling!");
- connection_mark_for_close(TO_CONN(conn));
- #endif
- } else {
- log_debug(LD_DIRSERV, "Finished writing server response. Closing.");
- connection_mark_for_close(TO_CONN(conn));
- }
- return 0;
- default:
- log_warn(LD_BUG,"called in unexpected state %d.",
- conn->base_.state);
- tor_fragile_assert();
- return -1;
- }
- return 0;
- }
- static void
- connection_dir_close_consensus_fetches(dir_connection_t *except_this_one,
- const char *resource)
- {
- smartlist_t *conns_to_close =
- connection_dir_list_by_purpose_and_resource(DIR_PURPOSE_FETCH_CONSENSUS,
- resource);
- SMARTLIST_FOREACH_BEGIN(conns_to_close, dir_connection_t *, d) {
- if (d == except_this_one)
- continue;
- log_info(LD_DIR, "Closing consensus fetch (to %s) since one "
- "has just arrived.", TO_CONN(d)->address);
- connection_mark_for_close(TO_CONN(d));
- } SMARTLIST_FOREACH_END(d);
- smartlist_free(conns_to_close);
- }
- int
- connection_dir_finished_connecting(dir_connection_t *conn)
- {
- tor_assert(conn);
- tor_assert(conn->base_.type == CONN_TYPE_DIR);
- tor_assert(conn->base_.state == DIR_CONN_STATE_CONNECTING);
- log_debug(LD_HTTP,"Dir connection to router %s:%u established.",
- conn->base_.address,conn->base_.port);
-
- conn->base_.state = DIR_CONN_STATE_CLIENT_SENDING;
- return 0;
- }
- STATIC const smartlist_t *
- find_dl_schedule(download_status_t *dls, const or_options_t *options)
- {
- const int dir_server = dir_server_mode(options);
- const int multi_d = networkstatus_consensus_can_use_multiple_directories(
- options);
- const int we_are_bootstrapping = networkstatus_consensus_is_bootstrapping(
- time(NULL));
- const int use_fallbacks = networkstatus_consensus_can_use_extra_fallbacks(
- options);
- switch (dls->schedule) {
- case DL_SCHED_GENERIC:
- if (dir_server) {
- return options->TestingServerDownloadSchedule;
- } else {
- return options->TestingClientDownloadSchedule;
- }
- case DL_SCHED_CONSENSUS:
- if (!multi_d) {
- return options->TestingServerConsensusDownloadSchedule;
- } else {
- if (we_are_bootstrapping) {
- if (!use_fallbacks) {
-
- return
- options->ClientBootstrapConsensusAuthorityOnlyDownloadSchedule;
- } else if (dls->want_authority) {
-
- return
- options->ClientBootstrapConsensusAuthorityDownloadSchedule;
- } else {
-
- return
- options->ClientBootstrapConsensusFallbackDownloadSchedule;
- }
- } else {
- return options->TestingClientConsensusDownloadSchedule;
- }
- }
- case DL_SCHED_BRIDGE:
- return options->TestingBridgeDownloadSchedule;
- default:
- tor_assert(0);
- }
-
- return NULL;
- }
- STATIC int
- download_status_schedule_get_delay(download_status_t *dls,
- const smartlist_t *schedule,
- time_t now)
- {
- tor_assert(dls);
- tor_assert(schedule);
- int delay = INT_MAX;
- uint8_t dls_schedule_position = (dls->increment_on
- == DL_SCHED_INCREMENT_ATTEMPT
- ? dls->n_download_attempts
- : dls->n_download_failures);
- if (dls_schedule_position < smartlist_len(schedule))
- delay = *(int *)smartlist_get(schedule, dls_schedule_position);
- else if (dls_schedule_position == IMPOSSIBLE_TO_DOWNLOAD)
- delay = INT_MAX;
- else
- delay = *(int *)smartlist_get(schedule, smartlist_len(schedule) - 1);
-
- tor_assert(delay >= 0);
-
- if (delay < INT_MAX && now <= INT_MAX - delay) {
- dls->next_attempt_at = now+delay;
- } else {
- dls->next_attempt_at = TIME_MAX;
- }
- return delay;
- }
- static void
- download_status_log_helper(const char *item, int was_schedule_incremented,
- const char *increment_action,
- const char *not_incremented_response,
- uint8_t dls_n_download_increments, int increment,
- time_t dls_next_attempt_at, time_t now)
- {
- if (item) {
- if (!was_schedule_incremented)
- log_debug(LD_DIR, "%s %s %d time(s); I'll try again %s.",
- item, increment_action, (int)dls_n_download_increments,
- not_incremented_response);
- else if (increment == 0)
- log_debug(LD_DIR, "%s %s %d time(s); I'll try again immediately.",
- item, increment_action, (int)dls_n_download_increments);
- else if (dls_next_attempt_at < TIME_MAX)
- log_debug(LD_DIR, "%s %s %d time(s); I'll try again in %d seconds.",
- item, increment_action, (int)dls_n_download_increments,
- (int)(dls_next_attempt_at-now));
- else
- log_debug(LD_DIR, "%s %s %d time(s); Giving up for a while.",
- item, increment_action, (int)dls_n_download_increments);
- }
- }
- time_t
- download_status_increment_failure(download_status_t *dls, int status_code,
- const char *item, int server, time_t now)
- {
- int increment = -1;
- tor_assert(dls);
-
- if (status_code != 503 || server) {
- if (dls->n_download_failures < IMPOSSIBLE_TO_DOWNLOAD-1)
- ++dls->n_download_failures;
- }
- if (dls->increment_on == DL_SCHED_INCREMENT_FAILURE) {
-
- if (dls->n_download_attempts < IMPOSSIBLE_TO_DOWNLOAD-1)
- ++dls->n_download_attempts;
-
- const smartlist_t *schedule = find_dl_schedule(dls, get_options());
- increment = download_status_schedule_get_delay(dls, schedule, now);
- }
- download_status_log_helper(item, !dls->increment_on, "failed",
- "concurrently", dls->n_download_failures,
- increment, dls->next_attempt_at, now);
- if (dls->increment_on == DL_SCHED_INCREMENT_ATTEMPT) {
-
- return TIME_MAX;
- } else {
- return dls->next_attempt_at;
- }
- }
- time_t
- download_status_increment_attempt(download_status_t *dls, const char *item,
- time_t now)
- {
- int delay = -1;
- tor_assert(dls);
- if (dls->increment_on == DL_SCHED_INCREMENT_FAILURE) {
-
- log_info(LD_BUG, "Tried to launch an attempt-based connection on a "
- "failure-based schedule.");
- return TIME_MAX;
- }
- if (dls->n_download_attempts < IMPOSSIBLE_TO_DOWNLOAD-1)
- ++dls->n_download_attempts;
- const smartlist_t *schedule = find_dl_schedule(dls, get_options());
- delay = download_status_schedule_get_delay(dls, schedule, now);
- download_status_log_helper(item, dls->increment_on, "attempted",
- "on failure", dls->n_download_attempts,
- delay, dls->next_attempt_at, now);
- return dls->next_attempt_at;
- }
- void
- download_status_reset(download_status_t *dls)
- {
- if (dls->n_download_failures == IMPOSSIBLE_TO_DOWNLOAD
- || dls->n_download_attempts == IMPOSSIBLE_TO_DOWNLOAD)
- return;
- const smartlist_t *schedule = find_dl_schedule(dls, get_options());
- dls->n_download_failures = 0;
- dls->n_download_attempts = 0;
- dls->next_attempt_at = time(NULL) + *(int *)smartlist_get(schedule, 0);
-
- }
- int
- download_status_get_n_failures(const download_status_t *dls)
- {
- return dls->n_download_failures;
- }
- int
- download_status_get_n_attempts(const download_status_t *dls)
- {
- return dls->n_download_attempts;
- }
- time_t
- download_status_get_next_attempt_at(const download_status_t *dls)
- {
- return dls->next_attempt_at;
- }
- static void
- dir_routerdesc_download_failed(smartlist_t *failed, int status_code,
- int router_purpose,
- int was_extrainfo, int was_descriptor_digests)
- {
- char digest[DIGEST_LEN];
- time_t now = time(NULL);
- int server = directory_fetches_from_authorities(get_options());
- if (!was_descriptor_digests) {
- if (router_purpose == ROUTER_PURPOSE_BRIDGE) {
- tor_assert(!was_extrainfo);
- connection_dir_retry_bridges(failed);
- }
- return;
- }
- SMARTLIST_FOREACH_BEGIN(failed, const char *, cp) {
- download_status_t *dls = NULL;
- if (base16_decode(digest, DIGEST_LEN, cp, strlen(cp)) < 0) {
- log_warn(LD_BUG, "Malformed fingerprint in list: %s", escaped(cp));
- continue;
- }
- if (was_extrainfo) {
- signed_descriptor_t *sd =
- router_get_by_extrainfo_digest(digest);
- if (sd)
- dls = &sd->ei_dl_status;
- } else {
- dls = router_get_dl_status_by_descriptor_digest(digest);
- }
- if (!dls || dls->n_download_failures >=
- get_options()->TestingDescriptorMaxDownloadTries)
- continue;
- download_status_increment_failure(dls, status_code, cp, server, now);
- } SMARTLIST_FOREACH_END(cp);
-
- }
- static void
- dir_microdesc_download_failed(smartlist_t *failed,
- int status_code)
- {
- networkstatus_t *consensus
- = networkstatus_get_latest_consensus_by_flavor(FLAV_MICRODESC);
- routerstatus_t *rs;
- download_status_t *dls;
- time_t now = time(NULL);
- int server = directory_fetches_from_authorities(get_options());
- if (! consensus)
- return;
- SMARTLIST_FOREACH_BEGIN(failed, const char *, d) {
- rs = router_get_mutable_consensus_status_by_descriptor_digest(consensus,d);
- if (!rs)
- continue;
- dls = &rs->dl_status;
- if (dls->n_download_failures >=
- get_options()->TestingMicrodescMaxDownloadTries)
- continue;
- {
- char buf[BASE64_DIGEST256_LEN+1];
- digest256_to_base64(buf, d);
- download_status_increment_failure(dls, status_code, buf,
- server, now);
- }
- } SMARTLIST_FOREACH_END(d);
- }
- static int
- compare_pairs_(const void **a, const void **b)
- {
- const fp_pair_t *fp1 = *a, *fp2 = *b;
- int r;
- if ((r = fast_memcmp(fp1->first, fp2->first, DIGEST_LEN)))
- return r;
- else
- return fast_memcmp(fp1->second, fp2->second, DIGEST_LEN);
- }
- int
- dir_split_resource_into_fingerprint_pairs(const char *res,
- smartlist_t *pairs_out)
- {
- smartlist_t *pairs_tmp = smartlist_new();
- smartlist_t *pairs_result = smartlist_new();
- smartlist_split_string(pairs_tmp, res, "+", 0, 0);
- if (smartlist_len(pairs_tmp)) {
- char *last = smartlist_get(pairs_tmp,smartlist_len(pairs_tmp)-1);
- size_t last_len = strlen(last);
- if (last_len > 2 && !strcmp(last+last_len-2, ".z")) {
- last[last_len-2] = '\0';
- }
- }
- SMARTLIST_FOREACH_BEGIN(pairs_tmp, char *, cp) {
- if (strlen(cp) != HEX_DIGEST_LEN*2+1) {
- log_info(LD_DIR,
- "Skipping digest pair %s with non-standard length.", escaped(cp));
- } else if (cp[HEX_DIGEST_LEN] != '-') {
- log_info(LD_DIR,
- "Skipping digest pair %s with missing dash.", escaped(cp));
- } else {
- fp_pair_t pair;
- if (base16_decode(pair.first, DIGEST_LEN, cp, HEX_DIGEST_LEN)<0 ||
- base16_decode(pair.second,
- DIGEST_LEN, cp+HEX_DIGEST_LEN+1, HEX_DIGEST_LEN)<0) {
- log_info(LD_DIR, "Skipping non-decodable digest pair %s", escaped(cp));
- } else {
- smartlist_add(pairs_result, tor_memdup(&pair, sizeof(pair)));
- }
- }
- tor_free(cp);
- } SMARTLIST_FOREACH_END(cp);
- smartlist_free(pairs_tmp);
-
- smartlist_sort(pairs_result, compare_pairs_);
- smartlist_uniq(pairs_result, compare_pairs_, tor_free_);
- smartlist_add_all(pairs_out, pairs_result);
- smartlist_free(pairs_result);
- return 0;
- }
- int
- dir_split_resource_into_fingerprints(const char *resource,
- smartlist_t *fp_out, int *compressed_out,
- int flags)
- {
- const int decode_hex = flags & DSR_HEX;
- const int decode_base64 = flags & DSR_BASE64;
- const int digests_are_256 = flags & DSR_DIGEST256;
- const int sort_uniq = flags & DSR_SORT_UNIQ;
- const int digest_len = digests_are_256 ? DIGEST256_LEN : DIGEST_LEN;
- const int hex_digest_len = digests_are_256 ?
- HEX_DIGEST256_LEN : HEX_DIGEST_LEN;
- const int base64_digest_len = digests_are_256 ?
- BASE64_DIGEST256_LEN : BASE64_DIGEST_LEN;
- smartlist_t *fp_tmp = smartlist_new();
- tor_assert(!(decode_hex && decode_base64));
- tor_assert(fp_out);
- smartlist_split_string(fp_tmp, resource, decode_base64?"-":"+", 0, 0);
- if (compressed_out)
- *compressed_out = 0;
- if (smartlist_len(fp_tmp)) {
- char *last = smartlist_get(fp_tmp,smartlist_len(fp_tmp)-1);
- size_t last_len = strlen(last);
- if (last_len > 2 && !strcmp(last+last_len-2, ".z")) {
- last[last_len-2] = '\0';
- if (compressed_out)
- *compressed_out = 1;
- }
- }
- if (decode_hex || decode_base64) {
- const size_t encoded_len = decode_hex ? hex_digest_len : base64_digest_len;
- int i;
- char *cp, *d = NULL;
- for (i = 0; i < smartlist_len(fp_tmp); ++i) {
- cp = smartlist_get(fp_tmp, i);
- if (strlen(cp) != encoded_len) {
- log_info(LD_DIR,
- "Skipping digest %s with non-standard length.", escaped(cp));
- smartlist_del_keeporder(fp_tmp, i--);
- goto again;
- }
- d = tor_malloc_zero(digest_len);
- if (decode_hex ?
- (base16_decode(d, digest_len, cp, hex_digest_len)<0) :
- (base64_decode(d, digest_len, cp, base64_digest_len)<0)) {
- log_info(LD_DIR, "Skipping non-decodable digest %s", escaped(cp));
- smartlist_del_keeporder(fp_tmp, i--);
- goto again;
- }
- smartlist_set(fp_tmp, i, d);
- d = NULL;
- again:
- tor_free(cp);
- tor_free(d);
- }
- }
- if (sort_uniq) {
- if (decode_hex || decode_base64) {
- if (digests_are_256) {
- smartlist_sort_digests256(fp_tmp);
- smartlist_uniq_digests256(fp_tmp);
- } else {
- smartlist_sort_digests(fp_tmp);
- smartlist_uniq_digests(fp_tmp);
- }
- } else {
- smartlist_sort_strings(fp_tmp);
- smartlist_uniq_strings(fp_tmp);
- }
- }
- smartlist_add_all(fp_out, fp_tmp);
- smartlist_free(fp_tmp);
- return 0;
- }
|