dircache.c 59 KB

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