dircache.c 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #define DIRCACHE_PRIVATE
  6. #include "core/or/or.h"
  7. #include "app/config/config.h"
  8. #include "core/mainloop/connection.h"
  9. #include "core/or/relay.h"
  10. #include "feature/dirauth/dirvote.h"
  11. #include "feature/dirauth/authmode.h"
  12. #include "feature/dirauth/process_descs.h"
  13. #include "feature/dircache/conscache.h"
  14. #include "feature/dircache/consdiffmgr.h"
  15. #include "feature/dircache/dircache.h"
  16. #include "feature/dircache/dirserv.h"
  17. #include "feature/dircommon/directory.h"
  18. #include "feature/dircommon/fp_pair.h"
  19. #include "feature/hs/hs_cache.h"
  20. #include "feature/nodelist/authcert.h"
  21. #include "feature/nodelist/networkstatus.h"
  22. #include "feature/nodelist/routerlist.h"
  23. #include "feature/relay/routermode.h"
  24. #include "feature/rend/rendcache.h"
  25. #include "feature/stats/geoip_stats.h"
  26. #include "feature/stats/rephist.h"
  27. #include "lib/compress/compress.h"
  28. #include "feature/dircache/cached_dir_st.h"
  29. #include "feature/dircommon/dir_connection_st.h"
  30. #include "feature/nodelist/authority_cert_st.h"
  31. #include "feature/nodelist/networkstatus_st.h"
  32. #include "feature/nodelist/routerinfo_st.h"
  33. /** Maximum size, in bytes, for any directory object that we're accepting
  34. * as an upload. */
  35. #define MAX_DIR_UL_SIZE ((1<<24)-1) /* 16MB-1 */
  36. /** HTTP cache control: how long do we tell proxies they can cache each
  37. * kind of document we serve? */
  38. #define FULL_DIR_CACHE_LIFETIME (60*60)
  39. #define RUNNINGROUTERS_CACHE_LIFETIME (20*60)
  40. #define DIRPORTFRONTPAGE_CACHE_LIFETIME (20*60)
  41. #define NETWORKSTATUS_CACHE_LIFETIME (5*60)
  42. #define ROUTERDESC_CACHE_LIFETIME (30*60)
  43. #define ROUTERDESC_BY_DIGEST_CACHE_LIFETIME (48*60*60)
  44. #define ROBOTS_CACHE_LIFETIME (24*60*60)
  45. #define MICRODESC_CACHE_LIFETIME (48*60*60)
  46. /* Bandwidth files change every hour. */
  47. #define BANDWIDTH_CACHE_LIFETIME (30*60)
  48. /** Parse an HTTP request string <b>headers</b> of the form
  49. * \verbatim
  50. * "\%s [http[s]://]\%s HTTP/1..."
  51. * \endverbatim
  52. * If it's well-formed, strdup the second \%s into *<b>url</b>, and
  53. * nul-terminate it. If the url doesn't start with "/tor/", rewrite it
  54. * so it does. Return 0.
  55. * Otherwise, return -1.
  56. */
  57. STATIC int
  58. parse_http_url(const char *headers, char **url)
  59. {
  60. char *command = NULL;
  61. if (parse_http_command(headers, &command, url) < 0) {
  62. return -1;
  63. }
  64. if (strcmpstart(*url, "/tor/")) {
  65. char *new_url = NULL;
  66. tor_asprintf(&new_url, "/tor%s%s",
  67. *url[0] == '/' ? "" : "/",
  68. *url);
  69. tor_free(*url);
  70. *url = new_url;
  71. }
  72. tor_free(command);
  73. return 0;
  74. }
  75. /** Create an http response for the client <b>conn</b> out of
  76. * <b>status</b> and <b>reason_phrase</b>. Write it to <b>conn</b>.
  77. */
  78. static void
  79. write_short_http_response(dir_connection_t *conn, int status,
  80. const char *reason_phrase)
  81. {
  82. char *buf = NULL;
  83. char *datestring = NULL;
  84. IF_BUG_ONCE(!reason_phrase) { /* bullet-proofing */
  85. reason_phrase = "unspecified";
  86. }
  87. if (server_mode(get_options())) {
  88. /* include the Date: header, but only if we're a relay or bridge */
  89. char datebuf[RFC1123_TIME_LEN+1];
  90. format_rfc1123_time(datebuf, time(NULL));
  91. tor_asprintf(&datestring, "Date: %s\r\n", datebuf);
  92. }
  93. tor_asprintf(&buf, "HTTP/1.0 %d %s\r\n%s\r\n",
  94. status, reason_phrase, datestring?datestring:"");
  95. log_debug(LD_DIRSERV,"Wrote status 'HTTP/1.0 %d %s'", status, reason_phrase);
  96. connection_buf_add(buf, strlen(buf), TO_CONN(conn));
  97. tor_free(datestring);
  98. tor_free(buf);
  99. }
  100. /** Write the header for an HTTP/1.0 response onto <b>conn</b>-\>outbuf,
  101. * with <b>type</b> as the Content-Type.
  102. *
  103. * If <b>length</b> is nonnegative, it is the Content-Length.
  104. * If <b>encoding</b> is provided, it is the Content-Encoding.
  105. * If <b>cache_lifetime</b> is greater than 0, the content may be cached for
  106. * up to cache_lifetime seconds. Otherwise, the content may not be cached. */
  107. static void
  108. write_http_response_header_impl(dir_connection_t *conn, ssize_t length,
  109. const char *type, const char *encoding,
  110. const char *extra_headers,
  111. long cache_lifetime)
  112. {
  113. char date[RFC1123_TIME_LEN+1];
  114. time_t now = approx_time();
  115. buf_t *buf = buf_new_with_capacity(1024);
  116. tor_assert(conn);
  117. format_rfc1123_time(date, now);
  118. buf_add_printf(buf, "HTTP/1.0 200 OK\r\nDate: %s\r\n", date);
  119. if (type) {
  120. buf_add_printf(buf, "Content-Type: %s\r\n", type);
  121. }
  122. if (!is_local_addr(&conn->base_.addr)) {
  123. /* Don't report the source address for a nearby/private connection.
  124. * Otherwise we tend to mis-report in cases where incoming ports are
  125. * being forwarded to a Tor server running behind the firewall. */
  126. buf_add_printf(buf, X_ADDRESS_HEADER "%s\r\n", conn->base_.address);
  127. }
  128. if (encoding) {
  129. buf_add_printf(buf, "Content-Encoding: %s\r\n", encoding);
  130. }
  131. if (length >= 0) {
  132. buf_add_printf(buf, "Content-Length: %ld\r\n", (long)length);
  133. }
  134. if (cache_lifetime > 0) {
  135. char expbuf[RFC1123_TIME_LEN+1];
  136. format_rfc1123_time(expbuf, (time_t)(now + cache_lifetime));
  137. /* We could say 'Cache-control: max-age=%d' here if we start doing
  138. * http/1.1 */
  139. buf_add_printf(buf, "Expires: %s\r\n", expbuf);
  140. } else if (cache_lifetime == 0) {
  141. /* We could say 'Cache-control: no-cache' here if we start doing
  142. * http/1.1 */
  143. buf_add_string(buf, "Pragma: no-cache\r\n");
  144. }
  145. if (extra_headers) {
  146. buf_add_string(buf, extra_headers);
  147. }
  148. buf_add_string(buf, "\r\n");
  149. connection_buf_add_buf(TO_CONN(conn), buf);
  150. buf_free(buf);
  151. }
  152. /** As write_http_response_header_impl, but translates method into
  153. * encoding */
  154. static void
  155. write_http_response_headers(dir_connection_t *conn, ssize_t length,
  156. compress_method_t method,
  157. const char *extra_headers, long cache_lifetime)
  158. {
  159. write_http_response_header_impl(conn, length,
  160. "text/plain",
  161. compression_method_get_name(method),
  162. extra_headers,
  163. cache_lifetime);
  164. }
  165. /** As write_http_response_headers, but assumes extra_headers is NULL */
  166. static void
  167. write_http_response_header(dir_connection_t *conn, ssize_t length,
  168. compress_method_t method,
  169. long cache_lifetime)
  170. {
  171. write_http_response_headers(conn, length, method, NULL, cache_lifetime);
  172. }
  173. /** Array of compression methods to use (if supported) for serving
  174. * precompressed data, ordered from best to worst. */
  175. static compress_method_t srv_meth_pref_precompressed[] = {
  176. LZMA_METHOD,
  177. ZSTD_METHOD,
  178. ZLIB_METHOD,
  179. GZIP_METHOD,
  180. NO_METHOD
  181. };
  182. /** Array of compression methods to use (if supported) for serving
  183. * streamed data, ordered from best to worst. */
  184. static compress_method_t srv_meth_pref_streaming_compression[] = {
  185. ZSTD_METHOD,
  186. ZLIB_METHOD,
  187. GZIP_METHOD,
  188. NO_METHOD
  189. };
  190. /** Parse the compression methods listed in an Accept-Encoding header <b>h</b>,
  191. * and convert them to a bitfield where compression method x is supported if
  192. * and only if 1 &lt;&lt; x is set in the bitfield. */
  193. STATIC unsigned
  194. parse_accept_encoding_header(const char *h)
  195. {
  196. unsigned result = (1u << NO_METHOD);
  197. smartlist_t *methods = smartlist_new();
  198. smartlist_split_string(methods, h, ",",
  199. SPLIT_SKIP_SPACE|SPLIT_STRIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  200. SMARTLIST_FOREACH_BEGIN(methods, const char *, m) {
  201. compress_method_t method = compression_method_get_by_name(m);
  202. if (method != UNKNOWN_METHOD) {
  203. tor_assert(((unsigned)method) < 8*sizeof(unsigned));
  204. result |= (1u << method);
  205. }
  206. } SMARTLIST_FOREACH_END(m);
  207. SMARTLIST_FOREACH_BEGIN(methods, char *, m) {
  208. tor_free(m);
  209. } SMARTLIST_FOREACH_END(m);
  210. smartlist_free(methods);
  211. return result;
  212. }
  213. /** Decide whether a client would accept the consensus we have.
  214. *
  215. * Clients can say they only want a consensus if it's signed by more
  216. * than half the authorities in a list. They pass this list in
  217. * the url as "...consensus/<b>fpr</b>+<b>fpr</b>+<b>fpr</b>".
  218. *
  219. * <b>fpr</b> may be an abbreviated fingerprint, i.e. only a left substring
  220. * of the full authority identity digest. (Only strings of even length,
  221. * i.e. encodings of full bytes, are handled correctly. In the case
  222. * of an odd number of hex digits the last one is silently ignored.)
  223. *
  224. * Returns 1 if more than half of the requested authorities signed the
  225. * consensus, 0 otherwise.
  226. */
  227. static int
  228. client_likes_consensus(const struct consensus_cache_entry_t *ent,
  229. const char *want_url)
  230. {
  231. smartlist_t *voters = smartlist_new();
  232. int need_at_least;
  233. int have = 0;
  234. if (consensus_cache_entry_get_voter_id_digests(ent, voters) != 0) {
  235. smartlist_free(voters);
  236. return 1; // We don't know the voters; assume the client won't mind. */
  237. }
  238. smartlist_t *want_authorities = smartlist_new();
  239. dir_split_resource_into_fingerprints(want_url, want_authorities, NULL, 0);
  240. need_at_least = smartlist_len(want_authorities)/2+1;
  241. SMARTLIST_FOREACH_BEGIN(want_authorities, const char *, want_digest) {
  242. SMARTLIST_FOREACH_BEGIN(voters, const char *, digest) {
  243. if (!strcasecmpstart(digest, want_digest)) {
  244. have++;
  245. break;
  246. };
  247. } SMARTLIST_FOREACH_END(digest);
  248. /* early exit, if we already have enough */
  249. if (have >= need_at_least)
  250. break;
  251. } SMARTLIST_FOREACH_END(want_digest);
  252. SMARTLIST_FOREACH(want_authorities, char *, d, tor_free(d));
  253. smartlist_free(want_authorities);
  254. SMARTLIST_FOREACH(voters, char *, cp, tor_free(cp));
  255. smartlist_free(voters);
  256. return (have >= need_at_least);
  257. }
  258. /** Return the compression level we should use for sending a compressed
  259. * response of size <b>n_bytes</b>. */
  260. STATIC compression_level_t
  261. choose_compression_level(ssize_t n_bytes)
  262. {
  263. if (! have_been_under_memory_pressure()) {
  264. return HIGH_COMPRESSION; /* we have plenty of RAM. */
  265. } else if (n_bytes < 0) {
  266. return HIGH_COMPRESSION; /* unknown; might be big. */
  267. } else if (n_bytes < 1024) {
  268. return LOW_COMPRESSION;
  269. } else if (n_bytes < 2048) {
  270. return MEDIUM_COMPRESSION;
  271. } else {
  272. return HIGH_COMPRESSION;
  273. }
  274. }
  275. /** Information passed to handle a GET request. */
  276. typedef struct get_handler_args_t {
  277. /** Bitmask of compression methods that the client said (or implied) it
  278. * supported. */
  279. unsigned compression_supported;
  280. /** If nonzero, the time included an if-modified-since header with this
  281. * value. */
  282. time_t if_modified_since;
  283. /** String containing the requested URL or resource. */
  284. const char *url;
  285. /** String containing the HTTP headers */
  286. const char *headers;
  287. } get_handler_args_t;
  288. /** Entry for handling an HTTP GET request.
  289. *
  290. * This entry matches a request if "string" is equal to the requested
  291. * resource, or if "is_prefix" is true and "string" is a prefix of the
  292. * requested resource.
  293. *
  294. * The 'handler' function is called to handle the request. It receives
  295. * an arguments structure, and must return 0 on success or -1 if we should
  296. * close the connection.
  297. **/
  298. typedef struct url_table_ent_s {
  299. const char *string;
  300. int is_prefix;
  301. int (*handler)(dir_connection_t *conn, const get_handler_args_t *args);
  302. } url_table_ent_t;
  303. static int handle_get_frontpage(dir_connection_t *conn,
  304. const get_handler_args_t *args);
  305. static int handle_get_current_consensus(dir_connection_t *conn,
  306. const get_handler_args_t *args);
  307. static int handle_get_status_vote(dir_connection_t *conn,
  308. const get_handler_args_t *args);
  309. static int handle_get_microdesc(dir_connection_t *conn,
  310. const get_handler_args_t *args);
  311. static int handle_get_descriptor(dir_connection_t *conn,
  312. const get_handler_args_t *args);
  313. static int handle_get_keys(dir_connection_t *conn,
  314. const get_handler_args_t *args);
  315. static int handle_get_hs_descriptor_v2(dir_connection_t *conn,
  316. const get_handler_args_t *args);
  317. static int handle_get_robots(dir_connection_t *conn,
  318. const get_handler_args_t *args);
  319. static int handle_get_networkstatus_bridges(dir_connection_t *conn,
  320. const get_handler_args_t *args);
  321. static int handle_get_next_bandwidth(dir_connection_t *conn,
  322. const get_handler_args_t *args);
  323. /** Table for handling GET requests. */
  324. static const url_table_ent_t url_table[] = {
  325. { "/tor/", 0, handle_get_frontpage },
  326. { "/tor/status-vote/current/consensus", 1, handle_get_current_consensus },
  327. { "/tor/status-vote/current/", 1, handle_get_status_vote },
  328. { "/tor/status-vote/next/bandwidth", 0, handle_get_next_bandwidth },
  329. { "/tor/status-vote/next/", 1, handle_get_status_vote },
  330. { "/tor/micro/d/", 1, handle_get_microdesc },
  331. { "/tor/server/", 1, handle_get_descriptor },
  332. { "/tor/extra/", 1, handle_get_descriptor },
  333. { "/tor/keys/", 1, handle_get_keys },
  334. { "/tor/rendezvous2/", 1, handle_get_hs_descriptor_v2 },
  335. { "/tor/hs/3/", 1, handle_get_hs_descriptor_v3 },
  336. { "/tor/robots.txt", 0, handle_get_robots },
  337. { "/tor/networkstatus-bridges", 0, handle_get_networkstatus_bridges },
  338. { NULL, 0, NULL },
  339. };
  340. /** Helper function: called when a dirserver gets a complete HTTP GET
  341. * request. Look for a request for a directory or for a rendezvous
  342. * service descriptor. On finding one, write a response into
  343. * conn-\>outbuf. If the request is unrecognized, send a 404.
  344. * Return 0 if we handled this successfully, or -1 if we need to close
  345. * the connection. */
  346. MOCK_IMPL(STATIC int,
  347. directory_handle_command_get,(dir_connection_t *conn, const char *headers,
  348. const char *req_body, size_t req_body_len))
  349. {
  350. char *url, *url_mem, *header;
  351. time_t if_modified_since = 0;
  352. int zlib_compressed_in_url;
  353. unsigned compression_methods_supported;
  354. /* We ignore the body of a GET request. */
  355. (void)req_body;
  356. (void)req_body_len;
  357. log_debug(LD_DIRSERV,"Received GET command.");
  358. conn->base_.state = DIR_CONN_STATE_SERVER_WRITING;
  359. if (parse_http_url(headers, &url) < 0) {
  360. write_short_http_response(conn, 400, "Bad request");
  361. return 0;
  362. }
  363. if ((header = http_get_header(headers, "If-Modified-Since: "))) {
  364. struct tm tm;
  365. if (parse_http_time(header, &tm) == 0) {
  366. if (tor_timegm(&tm, &if_modified_since)<0) {
  367. if_modified_since = 0;
  368. } else {
  369. log_debug(LD_DIRSERV, "If-Modified-Since is '%s'.", escaped(header));
  370. }
  371. }
  372. /* The correct behavior on a malformed If-Modified-Since header is to
  373. * act as if no If-Modified-Since header had been given. */
  374. tor_free(header);
  375. }
  376. log_debug(LD_DIRSERV,"rewritten url as '%s'.", escaped(url));
  377. url_mem = url;
  378. {
  379. size_t url_len = strlen(url);
  380. zlib_compressed_in_url = url_len > 2 && !strcmp(url+url_len-2, ".z");
  381. if (zlib_compressed_in_url) {
  382. url[url_len-2] = '\0';
  383. }
  384. }
  385. if ((header = http_get_header(headers, "Accept-Encoding: "))) {
  386. compression_methods_supported = parse_accept_encoding_header(header);
  387. tor_free(header);
  388. } else {
  389. compression_methods_supported = (1u << NO_METHOD);
  390. }
  391. if (zlib_compressed_in_url) {
  392. compression_methods_supported |= (1u << ZLIB_METHOD);
  393. }
  394. /* Remove all methods that we don't both support. */
  395. compression_methods_supported &= tor_compress_get_supported_method_bitmask();
  396. get_handler_args_t args;
  397. args.url = url;
  398. args.headers = headers;
  399. args.if_modified_since = if_modified_since;
  400. args.compression_supported = compression_methods_supported;
  401. int i, result = -1;
  402. for (i = 0; url_table[i].string; ++i) {
  403. int match;
  404. if (url_table[i].is_prefix) {
  405. match = !strcmpstart(url, url_table[i].string);
  406. } else {
  407. match = !strcmp(url, url_table[i].string);
  408. }
  409. if (match) {
  410. result = url_table[i].handler(conn, &args);
  411. goto done;
  412. }
  413. }
  414. /* we didn't recognize the url */
  415. write_short_http_response(conn, 404, "Not found");
  416. result = 0;
  417. done:
  418. tor_free(url_mem);
  419. return result;
  420. }
  421. /** Helper function for GET / or GET /tor/
  422. */
  423. static int
  424. handle_get_frontpage(dir_connection_t *conn, const get_handler_args_t *args)
  425. {
  426. (void) args; /* unused */
  427. const char *frontpage = get_dirportfrontpage();
  428. if (frontpage) {
  429. size_t dlen;
  430. dlen = strlen(frontpage);
  431. /* Let's return a disclaimer page (users shouldn't use V1 anymore,
  432. and caches don't fetch '/', so this is safe). */
  433. /* [We don't check for write_bucket_low here, since we want to serve
  434. * this page no matter what.] */
  435. write_http_response_header_impl(conn, dlen, "text/html", "identity",
  436. NULL, DIRPORTFRONTPAGE_CACHE_LIFETIME);
  437. connection_buf_add(frontpage, dlen, TO_CONN(conn));
  438. } else {
  439. write_short_http_response(conn, 404, "Not found");
  440. }
  441. return 0;
  442. }
  443. /** Warn that the cached consensus <b>consensus</b> of type
  444. * <b>flavor</b> too new or too old, based on <b>is_too_new</b>,
  445. * and will not be served to clients. Rate-limit the warning to avoid logging
  446. * an entry on every request.
  447. */
  448. static void
  449. warn_consensus_is_not_reasonably_live(
  450. const struct consensus_cache_entry_t *consensus,
  451. const char *flavor, time_t now, bool is_too_new)
  452. {
  453. #define NOT_REASONABLY_LIVE_WARNING_INTERVAL (60*60)
  454. static ratelim_t warned[2] = { RATELIM_INIT(
  455. NOT_REASONABLY_LIVE_WARNING_INTERVAL),
  456. RATELIM_INIT(
  457. NOT_REASONABLY_LIVE_WARNING_INTERVAL) };
  458. char timestamp[ISO_TIME_LEN+1];
  459. /* valid_after if is_too_new, valid_until if !is_too_new */
  460. time_t valid_time = 0;
  461. char *dupes = NULL;
  462. if (is_too_new) {
  463. if (consensus_cache_entry_get_valid_after(consensus, &valid_time))
  464. return;
  465. dupes = rate_limit_log(&warned[1], now);
  466. } else {
  467. if (consensus_cache_entry_get_valid_until(consensus, &valid_time))
  468. return;
  469. dupes = rate_limit_log(&warned[0], now);
  470. }
  471. if (dupes) {
  472. format_local_iso_time(timestamp, valid_time);
  473. log_warn(LD_DIRSERV, "Our %s%sconsensus is too %s, so we will not "
  474. "serve it to clients. It was valid %s %s local time and we "
  475. "continued to serve it for up to 24 hours %s.%s",
  476. flavor ? flavor : "",
  477. flavor ? " " : "",
  478. is_too_new ? "new" : "old",
  479. is_too_new ? "after" : "until",
  480. timestamp,
  481. is_too_new ? "before it was valid" : "after it expired",
  482. dupes);
  483. tor_free(dupes);
  484. }
  485. }
  486. /**
  487. * Parse a single hex-encoded sha3-256 digest from <b>hex</b> into
  488. * <b>digest</b>. Return 0 on success. On failure, report that the hash came
  489. * from <b>location</b>, report that we are taking <b>action</b> with it, and
  490. * return -1.
  491. */
  492. static int
  493. parse_one_diff_hash(uint8_t *digest, const char *hex, const char *location,
  494. const char *action)
  495. {
  496. if (base16_decode((char*)digest, DIGEST256_LEN, hex, strlen(hex)) ==
  497. DIGEST256_LEN) {
  498. return 0;
  499. } else {
  500. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  501. "%s contained bogus digest %s; %s.",
  502. location, escaped(hex), action);
  503. return -1;
  504. }
  505. }
  506. /** If there is an X-Or-Diff-From-Consensus header included in <b>headers</b>,
  507. * set <b>digest_out<b> to a new smartlist containing every 256-bit
  508. * hex-encoded digest listed in that header and return 0. Otherwise return
  509. * -1. */
  510. static int
  511. parse_or_diff_from_header(smartlist_t **digests_out, const char *headers)
  512. {
  513. char *hdr = http_get_header(headers, X_OR_DIFF_FROM_CONSENSUS_HEADER);
  514. if (hdr == NULL) {
  515. return -1;
  516. }
  517. smartlist_t *hex_digests = smartlist_new();
  518. *digests_out = smartlist_new();
  519. smartlist_split_string(hex_digests, hdr, " ",
  520. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  521. SMARTLIST_FOREACH_BEGIN(hex_digests, const char *, hex) {
  522. uint8_t digest[DIGEST256_LEN];
  523. if (!parse_one_diff_hash(digest, hex, "X-Or-Diff-From-Consensus header",
  524. "ignoring")) {
  525. smartlist_add(*digests_out, tor_memdup(digest, sizeof(digest)));
  526. }
  527. } SMARTLIST_FOREACH_END(hex);
  528. SMARTLIST_FOREACH(hex_digests, char *, cp, tor_free(cp));
  529. smartlist_free(hex_digests);
  530. tor_free(hdr);
  531. return 0;
  532. }
  533. /** Fallback compression method. The fallback compression method is used in
  534. * case a client requests a non-compressed document. We only store compressed
  535. * documents, so we use this compression method to fetch the document and let
  536. * the spooling system do the streaming decompression.
  537. */
  538. #define FALLBACK_COMPRESS_METHOD ZLIB_METHOD
  539. /**
  540. * Try to find the best consensus diff possible in order to serve a client
  541. * request for a diff from one of the consensuses in <b>digests</b> to the
  542. * current consensus of flavor <b>flav</b>. The client supports the
  543. * compression methods listed in the <b>compression_methods</b> bitfield:
  544. * place the method chosen (if any) into <b>compression_used_out</b>.
  545. */
  546. static struct consensus_cache_entry_t *
  547. find_best_diff(const smartlist_t *digests, int flav,
  548. unsigned compression_methods,
  549. compress_method_t *compression_used_out)
  550. {
  551. struct consensus_cache_entry_t *result = NULL;
  552. SMARTLIST_FOREACH_BEGIN(digests, const uint8_t *, diff_from) {
  553. unsigned u;
  554. for (u = 0; u < ARRAY_LENGTH(srv_meth_pref_precompressed); ++u) {
  555. compress_method_t method = srv_meth_pref_precompressed[u];
  556. if (0 == (compression_methods & (1u<<method)))
  557. continue; // client doesn't like this one, or we don't have it.
  558. if (consdiffmgr_find_diff_from(&result, flav, DIGEST_SHA3_256,
  559. diff_from, DIGEST256_LEN,
  560. method) == CONSDIFF_AVAILABLE) {
  561. tor_assert_nonfatal(result);
  562. *compression_used_out = method;
  563. return result;
  564. }
  565. }
  566. } SMARTLIST_FOREACH_END(diff_from);
  567. SMARTLIST_FOREACH_BEGIN(digests, const uint8_t *, diff_from) {
  568. if (consdiffmgr_find_diff_from(&result, flav, DIGEST_SHA3_256, diff_from,
  569. DIGEST256_LEN, FALLBACK_COMPRESS_METHOD) == CONSDIFF_AVAILABLE) {
  570. tor_assert_nonfatal(result);
  571. *compression_used_out = FALLBACK_COMPRESS_METHOD;
  572. return result;
  573. }
  574. } SMARTLIST_FOREACH_END(diff_from);
  575. return NULL;
  576. }
  577. /** Lookup the cached consensus document by the flavor found in <b>flav</b>.
  578. * The preferred set of compression methods should be listed in the
  579. * <b>compression_methods</b> bitfield. The compression method chosen (if any)
  580. * is stored in <b>compression_used_out</b>. */
  581. static struct consensus_cache_entry_t *
  582. find_best_consensus(int flav,
  583. unsigned compression_methods,
  584. compress_method_t *compression_used_out)
  585. {
  586. struct consensus_cache_entry_t *result = NULL;
  587. unsigned u;
  588. for (u = 0; u < ARRAY_LENGTH(srv_meth_pref_precompressed); ++u) {
  589. compress_method_t method = srv_meth_pref_precompressed[u];
  590. if (0 == (compression_methods & (1u<<method)))
  591. continue;
  592. if (consdiffmgr_find_consensus(&result, flav,
  593. method) == CONSDIFF_AVAILABLE) {
  594. tor_assert_nonfatal(result);
  595. *compression_used_out = method;
  596. return result;
  597. }
  598. }
  599. if (consdiffmgr_find_consensus(&result, flav,
  600. FALLBACK_COMPRESS_METHOD) == CONSDIFF_AVAILABLE) {
  601. tor_assert_nonfatal(result);
  602. *compression_used_out = FALLBACK_COMPRESS_METHOD;
  603. return result;
  604. }
  605. return NULL;
  606. }
  607. /** Try to find the best supported compression method possible from a given
  608. * <b>compression_methods</b>. Return NO_METHOD if no mutually supported
  609. * compression method could be found. */
  610. static compress_method_t
  611. find_best_compression_method(unsigned compression_methods, int stream)
  612. {
  613. unsigned u;
  614. compress_method_t *methods;
  615. size_t length;
  616. if (stream) {
  617. methods = srv_meth_pref_streaming_compression;
  618. length = ARRAY_LENGTH(srv_meth_pref_streaming_compression);
  619. } else {
  620. methods = srv_meth_pref_precompressed;
  621. length = ARRAY_LENGTH(srv_meth_pref_precompressed);
  622. }
  623. for (u = 0; u < length; ++u) {
  624. compress_method_t method = methods[u];
  625. if (compression_methods & (1u<<method))
  626. return method;
  627. }
  628. return NO_METHOD;
  629. }
  630. /** Check if any of the digests in <b>digests</b> matches the latest consensus
  631. * flavor (given in <b>flavor</b>) that we have available. */
  632. static int
  633. digest_list_contains_best_consensus(consensus_flavor_t flavor,
  634. const smartlist_t *digests)
  635. {
  636. const networkstatus_t *ns = NULL;
  637. if (digests == NULL)
  638. return 0;
  639. ns = networkstatus_get_latest_consensus_by_flavor(flavor);
  640. if (ns == NULL)
  641. return 0;
  642. SMARTLIST_FOREACH_BEGIN(digests, const uint8_t *, digest) {
  643. if (tor_memeq(ns->digest_sha3_as_signed, digest, DIGEST256_LEN))
  644. return 1;
  645. } SMARTLIST_FOREACH_END(digest);
  646. return 0;
  647. }
  648. /** Encodes the results of parsing a consensus request to figure out what
  649. * consensus, and possibly what diffs, the user asked for. */
  650. typedef struct {
  651. /** name of the flavor to retrieve. */
  652. char *flavor;
  653. /** flavor to retrive, as enum. */
  654. consensus_flavor_t flav;
  655. /** plus-separated list of authority fingerprints; see
  656. * client_likes_consensus(). Aliases the URL in the request passed to
  657. * parse_consensus_request(). */
  658. const char *want_fps;
  659. /** Optionally, a smartlist of sha3 digests-as-signed of the consensuses
  660. * to return a diff from. */
  661. smartlist_t *diff_from_digests;
  662. /** If true, never send a full consensus. If there is no diff, send
  663. * a 404 instead. */
  664. int diff_only;
  665. } parsed_consensus_request_t;
  666. /** Remove all data held in <b>req</b>. Do not free <b>req</b> itself, since
  667. * it is stack-allocated. */
  668. static void
  669. parsed_consensus_request_clear(parsed_consensus_request_t *req)
  670. {
  671. if (!req)
  672. return;
  673. tor_free(req->flavor);
  674. if (req->diff_from_digests) {
  675. SMARTLIST_FOREACH(req->diff_from_digests, uint8_t *, d, tor_free(d));
  676. smartlist_free(req->diff_from_digests);
  677. }
  678. memset(req, 0, sizeof(parsed_consensus_request_t));
  679. }
  680. /**
  681. * Parse the URL and relevant headers of <b>args</b> for a current-consensus
  682. * request to learn what flavor of consensus we want, what keys it must be
  683. * signed with, and what diffs we would accept (or demand) instead. Return 0
  684. * on success and -1 on failure.
  685. */
  686. static int
  687. parse_consensus_request(parsed_consensus_request_t *out,
  688. const get_handler_args_t *args)
  689. {
  690. const char *url = args->url;
  691. memset(out, 0, sizeof(parsed_consensus_request_t));
  692. out->flav = FLAV_NS;
  693. const char CONSENSUS_URL_PREFIX[] = "/tor/status-vote/current/consensus/";
  694. const char CONSENSUS_FLAVORED_PREFIX[] =
  695. "/tor/status-vote/current/consensus-";
  696. /* figure out the flavor if any, and who we wanted to sign the thing */
  697. const char *after_flavor = NULL;
  698. if (!strcmpstart(url, CONSENSUS_FLAVORED_PREFIX)) {
  699. const char *f, *cp;
  700. f = url + strlen(CONSENSUS_FLAVORED_PREFIX);
  701. cp = strchr(f, '/');
  702. if (cp) {
  703. after_flavor = cp+1;
  704. out->flavor = tor_strndup(f, cp-f);
  705. } else {
  706. out->flavor = tor_strdup(f);
  707. }
  708. int flav = networkstatus_parse_flavor_name(out->flavor);
  709. if (flav < 0)
  710. flav = FLAV_NS;
  711. out->flav = flav;
  712. } else {
  713. if (!strcmpstart(url, CONSENSUS_URL_PREFIX))
  714. after_flavor = url+strlen(CONSENSUS_URL_PREFIX);
  715. }
  716. /* see whether we've been asked explicitly for a diff from an older
  717. * consensus. (The user might also have said that a diff would be okay,
  718. * via X-Or-Diff-From-Consensus */
  719. const char DIFF_COMPONENT[] = "diff/";
  720. char *diff_hash_in_url = NULL;
  721. if (after_flavor && !strcmpstart(after_flavor, DIFF_COMPONENT)) {
  722. after_flavor += strlen(DIFF_COMPONENT);
  723. const char *cp = strchr(after_flavor, '/');
  724. if (cp) {
  725. diff_hash_in_url = tor_strndup(after_flavor, cp-after_flavor);
  726. out->want_fps = cp+1;
  727. } else {
  728. diff_hash_in_url = tor_strdup(after_flavor);
  729. out->want_fps = NULL;
  730. }
  731. } else {
  732. out->want_fps = after_flavor;
  733. }
  734. if (diff_hash_in_url) {
  735. uint8_t diff_from[DIGEST256_LEN];
  736. out->diff_from_digests = smartlist_new();
  737. out->diff_only = 1;
  738. int ok = !parse_one_diff_hash(diff_from, diff_hash_in_url, "URL",
  739. "rejecting");
  740. tor_free(diff_hash_in_url);
  741. if (ok) {
  742. smartlist_add(out->diff_from_digests,
  743. tor_memdup(diff_from, DIGEST256_LEN));
  744. } else {
  745. return -1;
  746. }
  747. } else {
  748. parse_or_diff_from_header(&out->diff_from_digests, args->headers);
  749. }
  750. return 0;
  751. }
  752. /** Helper function for GET /tor/status-vote/current/consensus
  753. */
  754. static int
  755. handle_get_current_consensus(dir_connection_t *conn,
  756. const get_handler_args_t *args)
  757. {
  758. const compress_method_t compress_method =
  759. find_best_compression_method(args->compression_supported, 0);
  760. const time_t if_modified_since = args->if_modified_since;
  761. int clear_spool = 0;
  762. /* v3 network status fetch. */
  763. long lifetime = NETWORKSTATUS_CACHE_LIFETIME;
  764. time_t now = time(NULL);
  765. parsed_consensus_request_t req;
  766. if (parse_consensus_request(&req, args) < 0) {
  767. write_short_http_response(conn, 404, "Couldn't parse request");
  768. goto done;
  769. }
  770. if (digest_list_contains_best_consensus(req.flav,
  771. req.diff_from_digests)) {
  772. write_short_http_response(conn, 304, "Not modified");
  773. geoip_note_ns_response(GEOIP_REJECT_NOT_MODIFIED);
  774. goto done;
  775. }
  776. struct consensus_cache_entry_t *cached_consensus = NULL;
  777. compress_method_t compression_used = NO_METHOD;
  778. if (req.diff_from_digests) {
  779. cached_consensus = find_best_diff(req.diff_from_digests, req.flav,
  780. args->compression_supported,
  781. &compression_used);
  782. }
  783. if (req.diff_only && !cached_consensus) {
  784. write_short_http_response(conn, 404, "No such diff available");
  785. geoip_note_ns_response(GEOIP_REJECT_NOT_FOUND);
  786. goto done;
  787. }
  788. if (! cached_consensus) {
  789. cached_consensus = find_best_consensus(req.flav,
  790. args->compression_supported,
  791. &compression_used);
  792. }
  793. time_t valid_after, fresh_until, valid_until;
  794. int have_valid_after = 0, have_fresh_until = 0, have_valid_until = 0;
  795. if (cached_consensus) {
  796. have_valid_after =
  797. !consensus_cache_entry_get_valid_after(cached_consensus, &valid_after);
  798. have_fresh_until =
  799. !consensus_cache_entry_get_fresh_until(cached_consensus, &fresh_until);
  800. have_valid_until =
  801. !consensus_cache_entry_get_valid_until(cached_consensus, &valid_until);
  802. }
  803. if (cached_consensus && have_valid_after &&
  804. !networkstatus_valid_after_is_reasonably_live(valid_after, now)) {
  805. write_short_http_response(conn, 404, "Consensus is too new");
  806. warn_consensus_is_not_reasonably_live(cached_consensus, req.flavor, now,
  807. 1);
  808. geoip_note_ns_response(GEOIP_REJECT_NOT_FOUND);
  809. goto done;
  810. } else if (
  811. cached_consensus && have_valid_until &&
  812. !networkstatus_valid_until_is_reasonably_live(valid_until, now)) {
  813. write_short_http_response(conn, 404, "Consensus is too old");
  814. warn_consensus_is_not_reasonably_live(cached_consensus, req.flavor, now,
  815. 0);
  816. geoip_note_ns_response(GEOIP_REJECT_NOT_FOUND);
  817. goto done;
  818. }
  819. if (cached_consensus && req.want_fps &&
  820. !client_likes_consensus(cached_consensus, req.want_fps)) {
  821. write_short_http_response(conn, 404, "Consensus not signed by sufficient "
  822. "number of requested authorities");
  823. geoip_note_ns_response(GEOIP_REJECT_NOT_ENOUGH_SIGS);
  824. goto done;
  825. }
  826. conn->spool = smartlist_new();
  827. clear_spool = 1;
  828. {
  829. spooled_resource_t *spooled;
  830. if (cached_consensus) {
  831. spooled = spooled_resource_new_from_cache_entry(cached_consensus);
  832. smartlist_add(conn->spool, spooled);
  833. }
  834. }
  835. lifetime = (have_fresh_until && fresh_until > now) ? fresh_until - now : 0;
  836. size_t size_guess = 0;
  837. int n_expired = 0;
  838. dirserv_spool_remove_missing_and_guess_size(conn, if_modified_since,
  839. compress_method != NO_METHOD,
  840. &size_guess,
  841. &n_expired);
  842. if (!smartlist_len(conn->spool) && !n_expired) {
  843. write_short_http_response(conn, 404, "Not found");
  844. geoip_note_ns_response(GEOIP_REJECT_NOT_FOUND);
  845. goto done;
  846. } else if (!smartlist_len(conn->spool)) {
  847. write_short_http_response(conn, 304, "Not modified");
  848. geoip_note_ns_response(GEOIP_REJECT_NOT_MODIFIED);
  849. goto done;
  850. }
  851. if (global_write_bucket_low(TO_CONN(conn), size_guess, 2)) {
  852. log_debug(LD_DIRSERV,
  853. "Client asked for network status lists, but we've been "
  854. "writing too many bytes lately. Sending 503 Dir busy.");
  855. write_short_http_response(conn, 503, "Directory busy, try again later");
  856. geoip_note_ns_response(GEOIP_REJECT_BUSY);
  857. goto done;
  858. }
  859. tor_addr_t addr;
  860. if (tor_addr_parse(&addr, (TO_CONN(conn))->address) >= 0) {
  861. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS,
  862. &addr, NULL,
  863. time(NULL));
  864. geoip_note_ns_response(GEOIP_SUCCESS);
  865. /* Note that a request for a network status has started, so that we
  866. * can measure the download time later on. */
  867. if (conn->dirreq_id)
  868. geoip_start_dirreq(conn->dirreq_id, size_guess, DIRREQ_TUNNELED);
  869. else
  870. geoip_start_dirreq(TO_CONN(conn)->global_identifier, size_guess,
  871. DIRREQ_DIRECT);
  872. }
  873. /* Use this header to tell caches that the response depends on the
  874. * X-Or-Diff-From-Consensus header (or lack thereof). */
  875. const char vary_header[] = "Vary: X-Or-Diff-From-Consensus\r\n";
  876. clear_spool = 0;
  877. // The compress_method might have been NO_METHOD, but we store the data
  878. // compressed. Decompress them using `compression_used`. See fallback code in
  879. // find_best_consensus() and find_best_diff().
  880. write_http_response_headers(conn, -1,
  881. compress_method == NO_METHOD ?
  882. NO_METHOD : compression_used,
  883. vary_header,
  884. smartlist_len(conn->spool) == 1 ? lifetime : 0);
  885. if (compress_method == NO_METHOD && smartlist_len(conn->spool))
  886. conn->compress_state = tor_compress_new(0, compression_used,
  887. HIGH_COMPRESSION);
  888. /* Prime the connection with some data. */
  889. const int initial_flush_result = connection_dirserv_flushed_some(conn);
  890. tor_assert_nonfatal(initial_flush_result == 0);
  891. goto done;
  892. done:
  893. parsed_consensus_request_clear(&req);
  894. if (clear_spool) {
  895. dir_conn_clear_spool(conn);
  896. }
  897. return 0;
  898. }
  899. /** Helper function for GET /tor/status-vote/{current,next}/...
  900. */
  901. static int
  902. handle_get_status_vote(dir_connection_t *conn, const get_handler_args_t *args)
  903. {
  904. const char *url = args->url;
  905. {
  906. ssize_t body_len = 0;
  907. ssize_t estimated_len = 0;
  908. int lifetime = 60; /* XXXX?? should actually use vote intervals. */
  909. /* This smartlist holds strings that we can compress on the fly. */
  910. smartlist_t *items = smartlist_new();
  911. /* This smartlist holds cached_dir_t objects that have a precompressed
  912. * deflated version. */
  913. smartlist_t *dir_items = smartlist_new();
  914. dirvote_dirreq_get_status_vote(url, items, dir_items);
  915. if (!smartlist_len(dir_items) && !smartlist_len(items)) {
  916. write_short_http_response(conn, 404, "Not found");
  917. goto vote_done;
  918. }
  919. /* We're sending items from at most one kind of source */
  920. tor_assert_nonfatal(smartlist_len(items) == 0 ||
  921. smartlist_len(dir_items) == 0);
  922. int streaming;
  923. unsigned mask;
  924. if (smartlist_len(items)) {
  925. /* We're taking strings and compressing them on the fly. */
  926. streaming = 1;
  927. mask = ~0u;
  928. } else {
  929. /* We're taking cached_dir_t objects. We only have them uncompressed
  930. * or deflated. */
  931. streaming = 0;
  932. mask = (1u<<NO_METHOD) | (1u<<ZLIB_METHOD);
  933. }
  934. const compress_method_t compress_method = find_best_compression_method(
  935. args->compression_supported&mask, streaming);
  936. SMARTLIST_FOREACH(dir_items, cached_dir_t *, d,
  937. body_len += compress_method != NO_METHOD ?
  938. d->dir_compressed_len : d->dir_len);
  939. estimated_len += body_len;
  940. SMARTLIST_FOREACH(items, const char *, item, {
  941. size_t ln = strlen(item);
  942. if (compress_method != NO_METHOD) {
  943. estimated_len += ln/2;
  944. } else {
  945. body_len += ln; estimated_len += ln;
  946. }
  947. });
  948. if (global_write_bucket_low(TO_CONN(conn), estimated_len, 2)) {
  949. write_short_http_response(conn, 503, "Directory busy, try again later");
  950. goto vote_done;
  951. }
  952. write_http_response_header(conn, body_len ? body_len : -1,
  953. compress_method,
  954. lifetime);
  955. if (smartlist_len(items)) {
  956. if (compress_method != NO_METHOD) {
  957. conn->compress_state = tor_compress_new(1, compress_method,
  958. choose_compression_level(estimated_len));
  959. }
  960. SMARTLIST_FOREACH(items, const char *, c,
  961. connection_dir_buf_add(c, strlen(c), conn,
  962. c_sl_idx == c_sl_len - 1));
  963. } else {
  964. SMARTLIST_FOREACH(dir_items, cached_dir_t *, d,
  965. connection_buf_add(compress_method != NO_METHOD ?
  966. d->dir_compressed : d->dir,
  967. compress_method != NO_METHOD ?
  968. d->dir_compressed_len : d->dir_len,
  969. TO_CONN(conn)));
  970. }
  971. vote_done:
  972. smartlist_free(items);
  973. smartlist_free(dir_items);
  974. goto done;
  975. }
  976. done:
  977. return 0;
  978. }
  979. /** Helper function for GET /tor/micro/d/...
  980. */
  981. static int
  982. handle_get_microdesc(dir_connection_t *conn, const get_handler_args_t *args)
  983. {
  984. const char *url = args->url;
  985. const compress_method_t compress_method =
  986. find_best_compression_method(args->compression_supported, 1);
  987. int clear_spool = 1;
  988. {
  989. conn->spool = smartlist_new();
  990. dir_split_resource_into_spoolable(url+strlen("/tor/micro/d/"),
  991. DIR_SPOOL_MICRODESC,
  992. conn->spool, NULL,
  993. DSR_DIGEST256|DSR_BASE64|DSR_SORT_UNIQ);
  994. size_t size_guess = 0;
  995. dirserv_spool_remove_missing_and_guess_size(conn, 0,
  996. compress_method != NO_METHOD,
  997. &size_guess, NULL);
  998. if (smartlist_len(conn->spool) == 0) {
  999. write_short_http_response(conn, 404, "Not found");
  1000. goto done;
  1001. }
  1002. if (global_write_bucket_low(TO_CONN(conn), size_guess, 2)) {
  1003. log_info(LD_DIRSERV,
  1004. "Client asked for server descriptors, but we've been "
  1005. "writing too many bytes lately. Sending 503 Dir busy.");
  1006. write_short_http_response(conn, 503, "Directory busy, try again later");
  1007. goto done;
  1008. }
  1009. clear_spool = 0;
  1010. write_http_response_header(conn, -1,
  1011. compress_method,
  1012. MICRODESC_CACHE_LIFETIME);
  1013. if (compress_method != NO_METHOD)
  1014. conn->compress_state = tor_compress_new(1, compress_method,
  1015. choose_compression_level(size_guess));
  1016. const int initial_flush_result = connection_dirserv_flushed_some(conn);
  1017. tor_assert_nonfatal(initial_flush_result == 0);
  1018. goto done;
  1019. }
  1020. done:
  1021. if (clear_spool) {
  1022. dir_conn_clear_spool(conn);
  1023. }
  1024. return 0;
  1025. }
  1026. /** Helper function for GET /tor/{server,extra}/...
  1027. */
  1028. static int
  1029. handle_get_descriptor(dir_connection_t *conn, const get_handler_args_t *args)
  1030. {
  1031. const char *url = args->url;
  1032. const compress_method_t compress_method =
  1033. find_best_compression_method(args->compression_supported, 1);
  1034. const or_options_t *options = get_options();
  1035. int clear_spool = 1;
  1036. if (!strcmpstart(url,"/tor/server/") ||
  1037. (!options->BridgeAuthoritativeDir &&
  1038. !options->BridgeRelay && !strcmpstart(url,"/tor/extra/"))) {
  1039. int res;
  1040. const char *msg = NULL;
  1041. int cache_lifetime = 0;
  1042. int is_extra = !strcmpstart(url,"/tor/extra/");
  1043. url += is_extra ? strlen("/tor/extra/") : strlen("/tor/server/");
  1044. dir_spool_source_t source;
  1045. time_t publish_cutoff = 0;
  1046. if (!strcmpstart(url, "d/")) {
  1047. source =
  1048. is_extra ? DIR_SPOOL_EXTRA_BY_DIGEST : DIR_SPOOL_SERVER_BY_DIGEST;
  1049. } else {
  1050. source =
  1051. is_extra ? DIR_SPOOL_EXTRA_BY_FP : DIR_SPOOL_SERVER_BY_FP;
  1052. /* We only want to apply a publish cutoff when we're requesting
  1053. * resources by fingerprint. */
  1054. publish_cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
  1055. }
  1056. conn->spool = smartlist_new();
  1057. res = dirserv_get_routerdesc_spool(conn->spool, url,
  1058. source,
  1059. connection_dir_is_encrypted(conn),
  1060. &msg);
  1061. if (!strcmpstart(url, "all")) {
  1062. cache_lifetime = FULL_DIR_CACHE_LIFETIME;
  1063. } else if (smartlist_len(conn->spool) == 1) {
  1064. cache_lifetime = ROUTERDESC_BY_DIGEST_CACHE_LIFETIME;
  1065. }
  1066. size_t size_guess = 0;
  1067. int n_expired = 0;
  1068. dirserv_spool_remove_missing_and_guess_size(conn, publish_cutoff,
  1069. compress_method != NO_METHOD,
  1070. &size_guess, &n_expired);
  1071. /* If we are the bridge authority and the descriptor is a bridge
  1072. * descriptor, remember that we served this descriptor for desc stats. */
  1073. /* XXXX it's a bit of a kludge to have this here. */
  1074. if (get_options()->BridgeAuthoritativeDir &&
  1075. source == DIR_SPOOL_SERVER_BY_FP) {
  1076. SMARTLIST_FOREACH_BEGIN(conn->spool, spooled_resource_t *, spooled) {
  1077. const routerinfo_t *router =
  1078. router_get_by_id_digest((const char *)spooled->digest);
  1079. /* router can be NULL here when the bridge auth is asked for its own
  1080. * descriptor. */
  1081. if (router && router->purpose == ROUTER_PURPOSE_BRIDGE)
  1082. rep_hist_note_desc_served(router->cache_info.identity_digest);
  1083. } SMARTLIST_FOREACH_END(spooled);
  1084. }
  1085. if (res < 0 || size_guess == 0 || smartlist_len(conn->spool) == 0) {
  1086. if (msg == NULL)
  1087. msg = "Not found";
  1088. write_short_http_response(conn, 404, msg);
  1089. } else {
  1090. if (global_write_bucket_low(TO_CONN(conn), size_guess, 2)) {
  1091. log_info(LD_DIRSERV,
  1092. "Client asked for server descriptors, but we've been "
  1093. "writing too many bytes lately. Sending 503 Dir busy.");
  1094. write_short_http_response(conn, 503,
  1095. "Directory busy, try again later");
  1096. dir_conn_clear_spool(conn);
  1097. goto done;
  1098. }
  1099. write_http_response_header(conn, -1, compress_method, cache_lifetime);
  1100. if (compress_method != NO_METHOD)
  1101. conn->compress_state = tor_compress_new(1, compress_method,
  1102. choose_compression_level(size_guess));
  1103. clear_spool = 0;
  1104. /* Prime the connection with some data. */
  1105. int initial_flush_result = connection_dirserv_flushed_some(conn);
  1106. tor_assert_nonfatal(initial_flush_result == 0);
  1107. }
  1108. goto done;
  1109. }
  1110. done:
  1111. if (clear_spool)
  1112. dir_conn_clear_spool(conn);
  1113. return 0;
  1114. }
  1115. /** Helper function for GET /tor/keys/...
  1116. */
  1117. static int
  1118. handle_get_keys(dir_connection_t *conn, const get_handler_args_t *args)
  1119. {
  1120. const char *url = args->url;
  1121. const compress_method_t compress_method =
  1122. find_best_compression_method(args->compression_supported, 1);
  1123. const time_t if_modified_since = args->if_modified_since;
  1124. {
  1125. smartlist_t *certs = smartlist_new();
  1126. ssize_t len = -1;
  1127. if (!strcmp(url, "/tor/keys/all")) {
  1128. authority_cert_get_all(certs);
  1129. } else if (!strcmp(url, "/tor/keys/authority")) {
  1130. authority_cert_t *cert = get_my_v3_authority_cert();
  1131. if (cert)
  1132. smartlist_add(certs, cert);
  1133. } else if (!strcmpstart(url, "/tor/keys/fp/")) {
  1134. smartlist_t *fps = smartlist_new();
  1135. dir_split_resource_into_fingerprints(url+strlen("/tor/keys/fp/"),
  1136. fps, NULL,
  1137. DSR_HEX|DSR_SORT_UNIQ);
  1138. SMARTLIST_FOREACH(fps, char *, d, {
  1139. authority_cert_t *c = authority_cert_get_newest_by_id(d);
  1140. if (c) smartlist_add(certs, c);
  1141. tor_free(d);
  1142. });
  1143. smartlist_free(fps);
  1144. } else if (!strcmpstart(url, "/tor/keys/sk/")) {
  1145. smartlist_t *fps = smartlist_new();
  1146. dir_split_resource_into_fingerprints(url+strlen("/tor/keys/sk/"),
  1147. fps, NULL,
  1148. DSR_HEX|DSR_SORT_UNIQ);
  1149. SMARTLIST_FOREACH(fps, char *, d, {
  1150. authority_cert_t *c = authority_cert_get_by_sk_digest(d);
  1151. if (c) smartlist_add(certs, c);
  1152. tor_free(d);
  1153. });
  1154. smartlist_free(fps);
  1155. } else if (!strcmpstart(url, "/tor/keys/fp-sk/")) {
  1156. smartlist_t *fp_sks = smartlist_new();
  1157. dir_split_resource_into_fingerprint_pairs(url+strlen("/tor/keys/fp-sk/"),
  1158. fp_sks);
  1159. SMARTLIST_FOREACH(fp_sks, fp_pair_t *, pair, {
  1160. authority_cert_t *c = authority_cert_get_by_digests(pair->first,
  1161. pair->second);
  1162. if (c) smartlist_add(certs, c);
  1163. tor_free(pair);
  1164. });
  1165. smartlist_free(fp_sks);
  1166. } else {
  1167. write_short_http_response(conn, 400, "Bad request");
  1168. goto keys_done;
  1169. }
  1170. if (!smartlist_len(certs)) {
  1171. write_short_http_response(conn, 404, "Not found");
  1172. goto keys_done;
  1173. }
  1174. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  1175. if (c->cache_info.published_on < if_modified_since)
  1176. SMARTLIST_DEL_CURRENT(certs, c));
  1177. if (!smartlist_len(certs)) {
  1178. write_short_http_response(conn, 304, "Not modified");
  1179. goto keys_done;
  1180. }
  1181. len = 0;
  1182. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  1183. len += c->cache_info.signed_descriptor_len);
  1184. if (global_write_bucket_low(TO_CONN(conn),
  1185. compress_method != NO_METHOD ? len/2 : len,
  1186. 2)) {
  1187. write_short_http_response(conn, 503, "Directory busy, try again later");
  1188. goto keys_done;
  1189. }
  1190. write_http_response_header(conn,
  1191. compress_method != NO_METHOD ? -1 : len,
  1192. compress_method,
  1193. 60*60);
  1194. if (compress_method != NO_METHOD) {
  1195. conn->compress_state = tor_compress_new(1, compress_method,
  1196. choose_compression_level(len));
  1197. }
  1198. SMARTLIST_FOREACH(certs, authority_cert_t *, c,
  1199. connection_dir_buf_add(c->cache_info.signed_descriptor_body,
  1200. c->cache_info.signed_descriptor_len,
  1201. conn, c_sl_idx == c_sl_len - 1));
  1202. keys_done:
  1203. smartlist_free(certs);
  1204. goto done;
  1205. }
  1206. done:
  1207. return 0;
  1208. }
  1209. /** Helper function for GET /tor/rendezvous2/
  1210. */
  1211. static int
  1212. handle_get_hs_descriptor_v2(dir_connection_t *conn,
  1213. const get_handler_args_t *args)
  1214. {
  1215. const char *url = args->url;
  1216. if (connection_dir_is_encrypted(conn)) {
  1217. /* Handle v2 rendezvous descriptor fetch request. */
  1218. const char *descp;
  1219. const char *query = url + strlen("/tor/rendezvous2/");
  1220. if (rend_valid_descriptor_id(query)) {
  1221. log_info(LD_REND, "Got a v2 rendezvous descriptor request for ID '%s'",
  1222. safe_str(escaped(query)));
  1223. switch (rend_cache_lookup_v2_desc_as_dir(query, &descp)) {
  1224. case 1: /* valid */
  1225. write_http_response_header(conn, strlen(descp), NO_METHOD, 0);
  1226. connection_buf_add(descp, strlen(descp), TO_CONN(conn));
  1227. break;
  1228. case 0: /* well-formed but not present */
  1229. write_short_http_response(conn, 404, "Not found");
  1230. break;
  1231. case -1: /* not well-formed */
  1232. write_short_http_response(conn, 400, "Bad request");
  1233. break;
  1234. }
  1235. } else { /* not well-formed */
  1236. write_short_http_response(conn, 400, "Bad request");
  1237. }
  1238. goto done;
  1239. } else {
  1240. /* Not encrypted! */
  1241. write_short_http_response(conn, 404, "Not found");
  1242. }
  1243. done:
  1244. return 0;
  1245. }
  1246. /** Helper function for GET /tor/hs/3/<z>. Only for version 3.
  1247. */
  1248. STATIC int
  1249. handle_get_hs_descriptor_v3(dir_connection_t *conn,
  1250. const get_handler_args_t *args)
  1251. {
  1252. int retval;
  1253. const char *desc_str = NULL;
  1254. const char *pubkey_str = NULL;
  1255. const char *url = args->url;
  1256. /* Reject non anonymous dir connections (which also tests if encrypted). We
  1257. * do not allow single hop clients to query an HSDir. */
  1258. if (!connection_dir_is_anonymous(conn)) {
  1259. write_short_http_response(conn, 503,
  1260. "Rejecting single hop HS v3 descriptor request");
  1261. goto done;
  1262. }
  1263. /* After the path prefix follows the base64 encoded blinded pubkey which we
  1264. * use to get the descriptor from the cache. Skip the prefix and get the
  1265. * pubkey. */
  1266. tor_assert(!strcmpstart(url, "/tor/hs/3/"));
  1267. pubkey_str = url + strlen("/tor/hs/3/");
  1268. retval = hs_cache_lookup_as_dir(HS_VERSION_THREE,
  1269. pubkey_str, &desc_str);
  1270. if (retval <= 0 || desc_str == NULL) {
  1271. write_short_http_response(conn, 404, "Not found");
  1272. goto done;
  1273. }
  1274. /* Found requested descriptor! Pass it to this nice client. */
  1275. write_http_response_header(conn, strlen(desc_str), NO_METHOD, 0);
  1276. connection_buf_add(desc_str, strlen(desc_str), TO_CONN(conn));
  1277. done:
  1278. return 0;
  1279. }
  1280. /** Helper function for GET /tor/networkstatus-bridges
  1281. */
  1282. static int
  1283. handle_get_networkstatus_bridges(dir_connection_t *conn,
  1284. const get_handler_args_t *args)
  1285. {
  1286. const char *headers = args->headers;
  1287. const or_options_t *options = get_options();
  1288. if (options->BridgeAuthoritativeDir &&
  1289. options->BridgePassword_AuthDigest_ &&
  1290. connection_dir_is_encrypted(conn)) {
  1291. char *status;
  1292. char digest[DIGEST256_LEN];
  1293. char *header = http_get_header(headers, "Authorization: Basic ");
  1294. if (header)
  1295. crypto_digest256(digest, header, strlen(header), DIGEST_SHA256);
  1296. /* now make sure the password is there and right */
  1297. if (!header ||
  1298. tor_memneq(digest,
  1299. options->BridgePassword_AuthDigest_, DIGEST256_LEN)) {
  1300. write_short_http_response(conn, 404, "Not found");
  1301. tor_free(header);
  1302. goto done;
  1303. }
  1304. tor_free(header);
  1305. /* all happy now. send an answer. */
  1306. status = networkstatus_getinfo_by_purpose("bridge", time(NULL));
  1307. size_t dlen = strlen(status);
  1308. write_http_response_header(conn, dlen, NO_METHOD, 0);
  1309. connection_buf_add(status, dlen, TO_CONN(conn));
  1310. tor_free(status);
  1311. goto done;
  1312. }
  1313. done:
  1314. return 0;
  1315. }
  1316. /** Helper function for GET the bandwidth file used for the next vote */
  1317. static int
  1318. handle_get_next_bandwidth(dir_connection_t *conn,
  1319. const get_handler_args_t *args)
  1320. {
  1321. log_debug(LD_DIR, "Getting next bandwidth.");
  1322. const or_options_t *options = get_options();
  1323. const compress_method_t compress_method =
  1324. find_best_compression_method(args->compression_supported, 1);
  1325. if (options->V3BandwidthsFile) {
  1326. char *bandwidth = read_file_to_str(options->V3BandwidthsFile,
  1327. RFTS_IGNORE_MISSING, NULL);
  1328. if (bandwidth != NULL) {
  1329. ssize_t len = strlen(bandwidth);
  1330. write_http_response_header(conn, compress_method != NO_METHOD ? -1 : len,
  1331. compress_method, BANDWIDTH_CACHE_LIFETIME);
  1332. if (compress_method != NO_METHOD) {
  1333. conn->compress_state = tor_compress_new(1, compress_method,
  1334. choose_compression_level(len/2));
  1335. log_debug(LD_DIR, "Compressing bandwidth file.");
  1336. } else {
  1337. log_debug(LD_DIR, "Not compressing bandwidth file.");
  1338. }
  1339. connection_dir_buf_add((const char*)bandwidth, len, conn, 1);
  1340. tor_free(bandwidth);
  1341. return 0;
  1342. }
  1343. }
  1344. write_short_http_response(conn, 404, "Not found");
  1345. return 0;
  1346. }
  1347. /** Helper function for GET robots.txt or /tor/robots.txt */
  1348. static int
  1349. handle_get_robots(dir_connection_t *conn, const get_handler_args_t *args)
  1350. {
  1351. (void)args;
  1352. {
  1353. const char robots[] = "User-agent: *\r\nDisallow: /\r\n";
  1354. size_t len = strlen(robots);
  1355. write_http_response_header(conn, len, NO_METHOD, ROBOTS_CACHE_LIFETIME);
  1356. connection_buf_add(robots, len, TO_CONN(conn));
  1357. }
  1358. return 0;
  1359. }
  1360. /* Given the <b>url</b> from a POST request, try to extract the version number
  1361. * using the provided <b>prefix</b>. The version should be after the prefix and
  1362. * ending with the separator "/". For instance:
  1363. * /tor/hs/3/publish
  1364. *
  1365. * On success, <b>end_pos</b> points to the position right after the version
  1366. * was found. On error, it is set to NULL.
  1367. *
  1368. * Return version on success else negative value. */
  1369. STATIC int
  1370. parse_hs_version_from_post(const char *url, const char *prefix,
  1371. const char **end_pos)
  1372. {
  1373. int ok;
  1374. unsigned long version;
  1375. const char *start;
  1376. char *end = NULL;
  1377. tor_assert(url);
  1378. tor_assert(prefix);
  1379. tor_assert(end_pos);
  1380. /* Check if the prefix does start the url. */
  1381. if (strcmpstart(url, prefix)) {
  1382. goto err;
  1383. }
  1384. /* Move pointer to the end of the prefix string. */
  1385. start = url + strlen(prefix);
  1386. /* Try this to be the HS version and if we are still at the separator, next
  1387. * will be move to the right value. */
  1388. version = tor_parse_long(start, 10, 0, INT_MAX, &ok, &end);
  1389. if (!ok) {
  1390. goto err;
  1391. }
  1392. *end_pos = end;
  1393. return (int) version;
  1394. err:
  1395. *end_pos = NULL;
  1396. return -1;
  1397. }
  1398. /* Handle the POST request for a hidden service descripror. The request is in
  1399. * <b>url</b>, the body of the request is in <b>body</b>. Return 200 on success
  1400. * else return 400 indicating a bad request. */
  1401. STATIC int
  1402. handle_post_hs_descriptor(const char *url, const char *body)
  1403. {
  1404. int version;
  1405. const char *end_pos;
  1406. tor_assert(url);
  1407. tor_assert(body);
  1408. version = parse_hs_version_from_post(url, "/tor/hs/", &end_pos);
  1409. if (version < 0) {
  1410. goto err;
  1411. }
  1412. /* We have a valid version number, now make sure it's a publish request. Use
  1413. * the end position just after the version and check for the command. */
  1414. if (strcmpstart(end_pos, "/publish")) {
  1415. goto err;
  1416. }
  1417. switch (version) {
  1418. case HS_VERSION_THREE:
  1419. if (hs_cache_store_as_dir(body) < 0) {
  1420. goto err;
  1421. }
  1422. log_info(LD_REND, "Publish request for HS descriptor handled "
  1423. "successfully.");
  1424. break;
  1425. default:
  1426. /* Unsupported version, return a bad request. */
  1427. goto err;
  1428. }
  1429. return 200;
  1430. err:
  1431. /* Bad request. */
  1432. return 400;
  1433. }
  1434. /** Helper function: called when a dirserver gets a complete HTTP POST
  1435. * request. Look for an uploaded server descriptor or rendezvous
  1436. * service descriptor. On finding one, process it and write a
  1437. * response into conn-\>outbuf. If the request is unrecognized, send a
  1438. * 400. Always return 0. */
  1439. MOCK_IMPL(STATIC int,
  1440. directory_handle_command_post,(dir_connection_t *conn, const char *headers,
  1441. const char *body, size_t body_len))
  1442. {
  1443. char *url = NULL;
  1444. const or_options_t *options = get_options();
  1445. log_debug(LD_DIRSERV,"Received POST command.");
  1446. conn->base_.state = DIR_CONN_STATE_SERVER_WRITING;
  1447. if (!public_server_mode(options)) {
  1448. log_info(LD_DIR, "Rejected dir post request from %s "
  1449. "since we're not a public relay.", conn->base_.address);
  1450. write_short_http_response(conn, 503, "Not acting as a public relay");
  1451. goto done;
  1452. }
  1453. if (parse_http_url(headers, &url) < 0) {
  1454. write_short_http_response(conn, 400, "Bad request");
  1455. return 0;
  1456. }
  1457. log_debug(LD_DIRSERV,"rewritten url as '%s'.", escaped(url));
  1458. /* Handle v2 rendezvous service publish request. */
  1459. if (connection_dir_is_encrypted(conn) &&
  1460. !strcmpstart(url,"/tor/rendezvous2/publish")) {
  1461. if (rend_cache_store_v2_desc_as_dir(body) < 0) {
  1462. log_warn(LD_REND, "Rejected v2 rend descriptor (body size %d) from %s.",
  1463. (int)body_len, conn->base_.address);
  1464. write_short_http_response(conn, 400,
  1465. "Invalid v2 service descriptor rejected");
  1466. } else {
  1467. write_short_http_response(conn, 200, "Service descriptor (v2) stored");
  1468. log_info(LD_REND, "Handled v2 rendezvous descriptor post: accepted");
  1469. }
  1470. goto done;
  1471. }
  1472. /* Handle HS descriptor publish request. We force an anonymous connection
  1473. * (which also tests for encrypted). We do not allow single-hop client to
  1474. * post a descriptor onto an HSDir. */
  1475. if (!strcmpstart(url, "/tor/hs/")) {
  1476. if (!connection_dir_is_anonymous(conn)) {
  1477. write_short_http_response(conn, 503,
  1478. "Rejecting single hop HS descriptor post");
  1479. goto done;
  1480. }
  1481. const char *msg = "HS descriptor stored successfully.";
  1482. /* We most probably have a publish request for an HS descriptor. */
  1483. int code = handle_post_hs_descriptor(url, body);
  1484. if (code != 200) {
  1485. msg = "Invalid HS descriptor. Rejected.";
  1486. }
  1487. write_short_http_response(conn, code, msg);
  1488. goto done;
  1489. }
  1490. if (!authdir_mode(options)) {
  1491. /* we just provide cached directories; we don't want to
  1492. * receive anything. */
  1493. write_short_http_response(conn, 400, "Nonauthoritative directory does not "
  1494. "accept posted server descriptors");
  1495. goto done;
  1496. }
  1497. if (authdir_mode(options) &&
  1498. !strcmp(url,"/tor/")) { /* server descriptor post */
  1499. const char *msg = "[None]";
  1500. uint8_t purpose = authdir_mode_bridge(options) ?
  1501. ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
  1502. was_router_added_t r = dirserv_add_multiple_descriptors(body, body_len,
  1503. purpose, conn->base_.address, &msg);
  1504. tor_assert(msg);
  1505. if (r == ROUTER_ADDED_SUCCESSFULLY) {
  1506. write_short_http_response(conn, 200, msg);
  1507. } else if (WRA_WAS_OUTDATED(r)) {
  1508. write_http_response_header_impl(conn, -1, NULL, NULL,
  1509. "X-Descriptor-Not-New: Yes\r\n", -1);
  1510. } else {
  1511. log_info(LD_DIRSERV,
  1512. "Rejected router descriptor or extra-info from %s "
  1513. "(\"%s\").",
  1514. conn->base_.address, msg);
  1515. write_short_http_response(conn, 400, msg);
  1516. }
  1517. goto done;
  1518. }
  1519. if (authdir_mode_v3(options) &&
  1520. !strcmp(url,"/tor/post/vote")) { /* v3 networkstatus vote */
  1521. const char *msg = "OK";
  1522. int status;
  1523. if (dirvote_add_vote(body, &msg, &status)) {
  1524. write_short_http_response(conn, status, "Vote stored");
  1525. } else {
  1526. tor_assert(msg);
  1527. log_warn(LD_DIRSERV, "Rejected vote from %s (\"%s\").",
  1528. conn->base_.address, msg);
  1529. write_short_http_response(conn, status, msg);
  1530. }
  1531. goto done;
  1532. }
  1533. if (authdir_mode_v3(options) &&
  1534. !strcmp(url,"/tor/post/consensus-signature")) { /* sigs on consensus. */
  1535. const char *msg = NULL;
  1536. if (dirvote_add_signatures(body, conn->base_.address, &msg)>=0) {
  1537. write_short_http_response(conn, 200, msg?msg:"Signatures stored");
  1538. } else {
  1539. log_warn(LD_DIR, "Unable to store signatures posted by %s: %s",
  1540. conn->base_.address, msg?msg:"???");
  1541. write_short_http_response(conn, 400,
  1542. msg?msg:"Unable to store signatures");
  1543. }
  1544. goto done;
  1545. }
  1546. /* we didn't recognize the url */
  1547. write_short_http_response(conn, 404, "Not found");
  1548. done:
  1549. tor_free(url);
  1550. return 0;
  1551. }
  1552. /** If <b>headers</b> indicates that a proxy was involved, then rewrite
  1553. * <b>conn</b>-\>address to describe our best guess of the address that
  1554. * originated this HTTP request. */
  1555. static void
  1556. http_set_address_origin(const char *headers, connection_t *conn)
  1557. {
  1558. char *fwd;
  1559. fwd = http_get_header(headers, "Forwarded-For: ");
  1560. if (!fwd)
  1561. fwd = http_get_header(headers, "X-Forwarded-For: ");
  1562. if (fwd) {
  1563. tor_addr_t toraddr;
  1564. if (tor_addr_parse(&toraddr,fwd) == -1 ||
  1565. tor_addr_is_internal(&toraddr,0)) {
  1566. log_debug(LD_DIR, "Ignoring local/internal IP %s", escaped(fwd));
  1567. tor_free(fwd);
  1568. return;
  1569. }
  1570. tor_free(conn->address);
  1571. conn->address = tor_strdup(fwd);
  1572. tor_free(fwd);
  1573. }
  1574. }
  1575. /** Called when a dirserver receives data on a directory connection;
  1576. * looks for an HTTP request. If the request is complete, remove it
  1577. * from the inbuf, try to process it; otherwise, leave it on the
  1578. * buffer. Return a 0 on success, or -1 on error.
  1579. */
  1580. int
  1581. directory_handle_command(dir_connection_t *conn)
  1582. {
  1583. char *headers=NULL, *body=NULL;
  1584. size_t body_len=0;
  1585. int r;
  1586. tor_assert(conn);
  1587. tor_assert(conn->base_.type == CONN_TYPE_DIR);
  1588. switch (connection_fetch_from_buf_http(TO_CONN(conn),
  1589. &headers, MAX_HEADERS_SIZE,
  1590. &body, &body_len, MAX_DIR_UL_SIZE, 0)) {
  1591. case -1: /* overflow */
  1592. log_warn(LD_DIRSERV,
  1593. "Request too large from address '%s' to DirPort. Closing.",
  1594. safe_str(conn->base_.address));
  1595. return -1;
  1596. case 0:
  1597. log_debug(LD_DIRSERV,"command not all here yet.");
  1598. return 0;
  1599. /* case 1, fall through */
  1600. }
  1601. http_set_address_origin(headers, TO_CONN(conn));
  1602. // we should escape headers here as well,
  1603. // but we can't call escaped() twice, as it uses the same buffer
  1604. //log_debug(LD_DIRSERV,"headers %s, body %s.", headers, escaped(body));
  1605. if (!strncasecmp(headers,"GET",3))
  1606. r = directory_handle_command_get(conn, headers, body, body_len);
  1607. else if (!strncasecmp(headers,"POST",4))
  1608. r = directory_handle_command_post(conn, headers, body, body_len);
  1609. else {
  1610. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1611. "Got headers %s with unknown command. Closing.",
  1612. escaped(headers));
  1613. r = -1;
  1614. }
  1615. tor_free(headers); tor_free(body);
  1616. return r;
  1617. }