dircache.c 59 KB

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