directory.c 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987
  1. /* Copyright 2001-2004 Roger Dingledine.
  2. * Copyright 2004-2006 Roger Dingledine, Nick Mathewson. */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char directory_c_id[] =
  6. "$Id$";
  7. #include "or.h"
  8. /**
  9. * \file directory.c
  10. * \brief Code to send and fetch directories and router
  11. * descriptors via HTTP. Directories use dirserv.c to generate the
  12. * results; clients use routers.c to parse them.
  13. **/
  14. /* In-points to directory.c:
  15. *
  16. * - directory_post_to_dirservers(), called from
  17. * router_upload_dir_desc_to_dirservers() in router.c
  18. * upload_service_descriptor() in rendservice.c
  19. * - directory_get_from_dirserver(), called from
  20. * rend_client_refetch_renddesc() in rendclient.c
  21. * run_scheduled_events() in main.c
  22. * do_hup() in main.c
  23. * - connection_dir_process_inbuf(), called from
  24. * connection_process_inbuf() in connection.c
  25. * - connection_dir_finished_flushing(), called from
  26. * connection_finished_flushing() in connection.c
  27. * - connection_dir_finished_connecting(), called from
  28. * connection_finished_connecting() in connection.c
  29. */
  30. static void
  31. directory_initiate_command(const char *address, uint32_t addr, uint16_t port,
  32. const char *platform,
  33. const char *digest, uint8_t purpose,
  34. int private_connection, const char *resource,
  35. const char *payload, size_t payload_len);
  36. static void
  37. directory_send_command(dir_connection_t *conn, const char *platform,
  38. int purpose, const char *resource,
  39. const char *payload, size_t payload_len);
  40. static int directory_handle_command(dir_connection_t *conn);
  41. static int body_is_plausible(const char *body, size_t body_len, int purpose);
  42. static int purpose_is_private(uint8_t purpose);
  43. static char *http_get_header(const char *headers, const char *which);
  44. static void http_set_address_origin(const char *headers, connection_t *conn);
  45. static void connection_dir_download_networkstatus_failed(
  46. dir_connection_t *conn);
  47. static void connection_dir_download_routerdesc_failed(dir_connection_t *conn);
  48. static void dir_networkstatus_download_failed(smartlist_t *failed);
  49. static void dir_routerdesc_download_failed(smartlist_t *failed);
  50. static void note_request(const char *key, size_t bytes);
  51. /********* START VARIABLES **********/
  52. /** How far in the future do we allow a directory server to tell us it is
  53. * before deciding that one of us has the wrong time? */
  54. #define ALLOW_DIRECTORY_TIME_SKEW (30*60)
  55. #define X_ADDRESS_HEADER "X-Your-Address-Is: "
  56. /********* END VARIABLES ************/
  57. /** Return true iff the directory purpose 'purpose' must use an
  58. * anonymous connection to a directory. */
  59. static int
  60. purpose_is_private(uint8_t purpose)
  61. {
  62. if (get_options()->AllDirActionsPrivate)
  63. return 1;
  64. if (purpose == DIR_PURPOSE_FETCH_DIR ||
  65. purpose == DIR_PURPOSE_UPLOAD_DIR ||
  66. purpose == DIR_PURPOSE_FETCH_RUNNING_LIST ||
  67. purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS ||
  68. purpose == DIR_PURPOSE_FETCH_SERVERDESC)
  69. return 0;
  70. return 1;
  71. }
  72. /** Start a connection to every known directory server, using
  73. * connection purpose 'purpose' and uploading the payload 'payload'
  74. * (length 'payload_len'). The purpose should be one of
  75. * 'DIR_PURPOSE_UPLOAD_DIR' or 'DIR_PURPOSE_UPLOAD_RENDDESC'.
  76. */
  77. void
  78. directory_post_to_dirservers(uint8_t purpose, const char *payload,
  79. size_t payload_len)
  80. {
  81. smartlist_t *dirservers;
  82. int post_via_tor;
  83. int post_to_v1_only;
  84. dirservers = router_get_trusted_dir_servers();
  85. tor_assert(dirservers);
  86. /* Only old dirservers handle rendezvous descriptor publishing. */
  87. post_to_v1_only = (purpose == DIR_PURPOSE_UPLOAD_RENDDESC);
  88. /* This tries dirservers which we believe to be down, but ultimately, that's
  89. * harmless, and we may as well err on the side of getting things uploaded.
  90. */
  91. SMARTLIST_FOREACH(dirservers, trusted_dir_server_t *, ds,
  92. {
  93. routerstatus_t *rs = &(ds->fake_status);
  94. if (post_to_v1_only && !ds->is_v1_authority)
  95. continue;
  96. post_via_tor = purpose_is_private(purpose) ||
  97. !fascist_firewall_allows_address_dir(ds->addr, ds->dir_port);
  98. directory_initiate_command_routerstatus(rs, purpose, post_via_tor,
  99. NULL, payload, payload_len);
  100. });
  101. }
  102. /** Start a connection to a random running directory server, using
  103. * connection purpose 'purpose' and requesting 'resource'.
  104. * If <b>retry_if_no_servers</b>, then if all the possible servers seem
  105. * down, mark them up and try again.
  106. */
  107. void
  108. directory_get_from_dirserver(uint8_t purpose, const char *resource,
  109. int retry_if_no_servers)
  110. {
  111. routerstatus_t *rs = NULL;
  112. or_options_t *options = get_options();
  113. int prefer_authority = server_mode(options) && options->DirPort != 0;
  114. int directconn = !purpose_is_private(purpose);
  115. int need_v1_support = purpose == DIR_PURPOSE_FETCH_DIR ||
  116. purpose == DIR_PURPOSE_FETCH_RUNNING_LIST ||
  117. purpose == DIR_PURPOSE_FETCH_RENDDESC;
  118. int need_v2_support = purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS ||
  119. purpose == DIR_PURPOSE_FETCH_SERVERDESC;
  120. if (!options->FetchServerDescriptors &&
  121. (need_v1_support || need_v2_support))
  122. return;
  123. if (directconn) {
  124. if (prefer_authority) {
  125. /* only ask authdirservers, and don't ask myself */
  126. rs = router_pick_trusteddirserver(need_v1_support, 1, 1,
  127. retry_if_no_servers);
  128. }
  129. if (!rs) {
  130. /* anybody with a non-zero dirport will do */
  131. rs = router_pick_directory_server(1, 1, need_v2_support,
  132. retry_if_no_servers);
  133. if (!rs) {
  134. const char *which;
  135. if (purpose == DIR_PURPOSE_FETCH_DIR)
  136. which = "directory";
  137. else if (purpose == DIR_PURPOSE_FETCH_RUNNING_LIST)
  138. which = "status list";
  139. else if (purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS)
  140. which = "network status";
  141. else // if (purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS)
  142. which = "server descriptors";
  143. log_info(LD_DIR,
  144. "No router found for %s; falling back to dirserver list",
  145. which);
  146. rs = router_pick_trusteddirserver(need_v1_support, 1, 1,
  147. retry_if_no_servers);
  148. if (!rs)
  149. directconn = 0; /* last resort: try routing it via Tor */
  150. }
  151. }
  152. }
  153. if (!directconn) {
  154. /* Never use fascistfirewall; we're going via Tor. */
  155. if (purpose == DIR_PURPOSE_FETCH_RENDDESC) {
  156. /* only ask authdirservers, any of them will do */
  157. rs = router_pick_trusteddirserver(1, 0, 0, retry_if_no_servers);
  158. } else {
  159. /* anybody with a non-zero dirport will do. Disregard firewalls. */
  160. rs = router_pick_directory_server(1, 0, need_v2_support,
  161. retry_if_no_servers);
  162. /* If we have any hope of building an indirect conn, we know some router
  163. * descriptors. If (rs==NULL), we can't build circuits anyway, so
  164. * there's no point in falling back to the authorities in this case. */
  165. }
  166. }
  167. if (rs)
  168. directory_initiate_command_routerstatus(rs, purpose, !directconn,
  169. resource, NULL, 0);
  170. else {
  171. log_notice(LD_DIR,
  172. "No running dirservers known. Will try again later. "
  173. "(purpose %d)", purpose);
  174. if (!purpose_is_private(purpose)) {
  175. /* remember we tried them all and failed. */
  176. directory_all_unreachable(time(NULL));
  177. }
  178. }
  179. }
  180. /** Launch a new connection to the directory server <b>router</b> to upload or
  181. * download a service or rendezvous descriptor. <b>purpose</b> determines what
  182. * kind of directory connection we're launching, and must be one of
  183. * DIR_PURPOSE_{FETCH|UPLOAD}_{DIR|RENDDESC}.
  184. *
  185. * When uploading, <b>payload</b> and <b>payload_len</b> determine the content
  186. * of the HTTP post. Otherwise, <b>payload</b> should be NULL.
  187. *
  188. * When fetching a rendezvous descriptor, <b>resource</b> is the service ID we
  189. * want to fetch.
  190. */
  191. void
  192. directory_initiate_command_router(routerinfo_t *router,
  193. uint8_t purpose,
  194. int private_connection,
  195. const char *resource,
  196. const char *payload,
  197. size_t payload_len)
  198. {
  199. directory_initiate_command(router->address, router->addr, router->dir_port,
  200. router->platform,
  201. router->cache_info.identity_digest,
  202. purpose, private_connection, resource,
  203. payload, payload_len);
  204. }
  205. /** Launch a new connection to the directory server <b>status</b> to upload or
  206. * download a service or rendezvous descriptor. <b>purpose</b> determines what
  207. * kind of directory connection we're launching, and must be one of
  208. * DIR_PURPOSE_{FETCH|UPLOAD}_{DIR|RENDDESC}.
  209. *
  210. * When uploading, <b>payload</b> and <b>payload_len</b> determine the content
  211. * of the HTTP post. Otherwise, <b>payload</b> should be NULL.
  212. *
  213. * When fetching a rendezvous descriptor, <b>resource</b> is the service ID we
  214. * want to fetch.
  215. */
  216. void
  217. directory_initiate_command_routerstatus(routerstatus_t *status,
  218. uint8_t purpose,
  219. int private_connection,
  220. const char *resource,
  221. const char *payload,
  222. size_t payload_len)
  223. {
  224. const char *platform = NULL;
  225. routerinfo_t *router;
  226. char address_buf[INET_NTOA_BUF_LEN+1];
  227. struct in_addr in;
  228. const char *address;
  229. if ((router = router_get_by_digest(status->identity_digest))) {
  230. platform = router->platform;
  231. address = router->address;
  232. } else {
  233. in.s_addr = htonl(status->addr);
  234. tor_inet_ntoa(&in, address_buf, sizeof(address_buf));
  235. address = address_buf;
  236. }
  237. directory_initiate_command(address, status->addr, status->dir_port,
  238. platform, status->identity_digest,
  239. purpose, private_connection, resource,
  240. payload, payload_len);
  241. }
  242. /** Called when we are unable to complete the client's request to a
  243. * directory server: Mark the router as down and try again if possible.
  244. */
  245. void
  246. connection_dir_request_failed(dir_connection_t *conn)
  247. {
  248. if (router_digest_is_me(conn->identity_digest))
  249. return; /* this was a test fetch. don't retry. */
  250. router_set_status(conn->identity_digest, 0); /* don't try him again */
  251. if (conn->_base.purpose == DIR_PURPOSE_FETCH_DIR ||
  252. conn->_base.purpose == DIR_PURPOSE_FETCH_RUNNING_LIST) {
  253. log_info(LD_DIR, "Giving up on directory server at '%s:%d'; retrying",
  254. conn->_base.address, conn->_base.port);
  255. directory_get_from_dirserver(conn->_base.purpose, NULL,
  256. 0 /* don't retry_if_no_servers */);
  257. } else if (conn->_base.purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS) {
  258. log_info(LD_DIR, "Giving up on directory server at '%s'; retrying",
  259. conn->_base.address);
  260. connection_dir_download_networkstatus_failed(conn);
  261. } else if (conn->_base.purpose == DIR_PURPOSE_FETCH_SERVERDESC) {
  262. log_info(LD_DIR, "Giving up on directory server at '%s'; retrying",
  263. conn->_base.address);
  264. connection_dir_download_routerdesc_failed(conn);
  265. }
  266. }
  267. /** Called when an attempt to download one or more network status
  268. * documents on connection <b>conn</b> failed. Decide whether to
  269. * retry the fetch now, later, or never.
  270. */
  271. static void
  272. connection_dir_download_networkstatus_failed(dir_connection_t *conn)
  273. {
  274. if (!conn->requested_resource) {
  275. /* We never reached directory_send_command, which means that we never
  276. * opened a network connection. Either we're out of sockets, or the
  277. * network is down. Either way, retrying would be pointless. */
  278. return;
  279. }
  280. if (!strcmpstart(conn->requested_resource, "all")) {
  281. /* We're a non-authoritative directory cache; try again. */
  282. smartlist_t *trusted_dirs = router_get_trusted_dir_servers();
  283. SMARTLIST_FOREACH(trusted_dirs, trusted_dir_server_t *, ds,
  284. ++ds->n_networkstatus_failures);
  285. directory_get_from_dirserver(conn->_base.purpose, "all.z",
  286. 0 /* don't retry_if_no_servers */);
  287. } else if (!strcmpstart(conn->requested_resource, "fp/")) {
  288. /* We were trying to download by fingerprint; mark them all as having
  289. * failed, and possibly retry them later.*/
  290. smartlist_t *failed = smartlist_create();
  291. dir_split_resource_into_fingerprints(conn->requested_resource+3,
  292. failed, NULL, 0, 0);
  293. if (smartlist_len(failed)) {
  294. dir_networkstatus_download_failed(failed);
  295. SMARTLIST_FOREACH(failed, char *, cp, tor_free(cp));
  296. }
  297. smartlist_free(failed);
  298. }
  299. }
  300. /** Called when an attempt to download one or more router descriptors
  301. * on connection <b>conn</b> failed.
  302. */
  303. static void
  304. connection_dir_download_routerdesc_failed(dir_connection_t *conn)
  305. {
  306. /* Try again. No need to increment the failure count for routerdescs, since
  307. * it's not their fault.*/
  308. /* update_router_descriptor_downloads(time(NULL)); */
  309. (void) conn;
  310. /* XXXX Why did the above get commented out? -NM */
  311. }
  312. /** Helper for directory_initiate_command_(router|trusted_dir): send the
  313. * command to a server whose address is <b>address</b>, whose IP is
  314. * <b>addr</b>, whose directory port is <b>dir_port</b>, whose tor version is
  315. * <b>platform</b>, and whose identity key digest is <b>digest</b>. The
  316. * <b>platform</b> argument is optional; the others are required. */
  317. static void
  318. directory_initiate_command(const char *address, uint32_t addr,
  319. uint16_t dir_port, const char *platform,
  320. const char *digest, uint8_t purpose,
  321. int private_connection, const char *resource,
  322. const char *payload, size_t payload_len)
  323. {
  324. dir_connection_t *conn;
  325. tor_assert(address);
  326. tor_assert(addr);
  327. tor_assert(dir_port);
  328. tor_assert(digest);
  329. switch (purpose) {
  330. case DIR_PURPOSE_FETCH_DIR:
  331. log_debug(LD_DIR,"initiating directory fetch");
  332. break;
  333. case DIR_PURPOSE_FETCH_RENDDESC:
  334. log_debug(LD_DIR,"initiating hidden-service descriptor fetch");
  335. break;
  336. case DIR_PURPOSE_UPLOAD_DIR:
  337. log_debug(LD_OR,"initiating server descriptor upload");
  338. break;
  339. case DIR_PURPOSE_UPLOAD_RENDDESC:
  340. log_debug(LD_REND,"initiating hidden-service descriptor upload");
  341. break;
  342. case DIR_PURPOSE_FETCH_RUNNING_LIST:
  343. log_debug(LD_DIR,"initiating running-routers fetch");
  344. break;
  345. case DIR_PURPOSE_FETCH_NETWORKSTATUS:
  346. log_debug(LD_DIR,"initiating network-status fetch");
  347. break;
  348. case DIR_PURPOSE_FETCH_SERVERDESC:
  349. log_debug(LD_DIR,"initiating server descriptor fetch");
  350. break;
  351. default:
  352. log_err(LD_BUG, "Unrecognized directory connection purpose.");
  353. tor_assert(0);
  354. }
  355. conn = TO_DIR_CONN(connection_new(CONN_TYPE_DIR));
  356. /* set up conn so it's got all the data we need to remember */
  357. conn->_base.addr = addr;
  358. conn->_base.port = dir_port;
  359. conn->_base.address = tor_strdup(address);
  360. memcpy(conn->identity_digest, digest, DIGEST_LEN);
  361. conn->_base.purpose = purpose;
  362. /* give it an initial state */
  363. conn->_base.state = DIR_CONN_STATE_CONNECTING;
  364. conn->dirconn_direct = (private_connection == 0);
  365. if (!private_connection) {
  366. /* then we want to connect directly */
  367. if (get_options()->HttpProxy) {
  368. addr = get_options()->HttpProxyAddr;
  369. dir_port = get_options()->HttpProxyPort;
  370. }
  371. switch (connection_connect(TO_CONN(conn), conn->_base.address, addr,
  372. dir_port)) {
  373. case -1:
  374. connection_dir_request_failed(conn); /* retry if we want */
  375. connection_free(TO_CONN(conn));
  376. return;
  377. case 1:
  378. /* start flushing conn */
  379. conn->_base.state = DIR_CONN_STATE_CLIENT_SENDING;
  380. /* fall through */
  381. case 0:
  382. /* queue the command on the outbuf */
  383. directory_send_command(conn, platform, purpose, resource,
  384. payload, payload_len);
  385. connection_watch_events(TO_CONN(conn), EV_READ | EV_WRITE);
  386. /* writable indicates finish, readable indicates broken link,
  387. error indicates broken link in windowsland. */
  388. }
  389. } else { /* we want to connect via tor */
  390. /* make an AP connection
  391. * populate it and add it at the right state
  392. * socketpair and hook up both sides
  393. */
  394. conn->_base.s = connection_ap_make_bridge(conn->_base.address,
  395. conn->_base.port);
  396. if (conn->_base.s < 0) {
  397. log_warn(LD_NET,"Making AP bridge to dirserver failed.");
  398. connection_mark_for_close(TO_CONN(conn));
  399. return;
  400. }
  401. if (connection_add(TO_CONN(conn)) < 0) {
  402. log_warn(LD_NET,"Unable to add AP bridge to dirserver.");
  403. connection_mark_for_close(TO_CONN(conn));
  404. return;
  405. }
  406. conn->_base.state = DIR_CONN_STATE_CLIENT_SENDING;
  407. /* queue the command on the outbuf */
  408. directory_send_command(conn, platform, purpose, resource,
  409. payload, payload_len);
  410. connection_watch_events(TO_CONN(conn), EV_READ | EV_WRITE);
  411. }
  412. }
  413. /** Queue an appropriate HTTP command on conn-\>outbuf. The other args
  414. * are as in directory_initiate_command.
  415. */
  416. static void
  417. directory_send_command(dir_connection_t *conn, const char *platform,
  418. int purpose, const char *resource,
  419. const char *payload, size_t payload_len)
  420. {
  421. char proxystring[256];
  422. char proxyauthstring[256];
  423. char hoststring[128];
  424. char *url;
  425. char request[8192];
  426. const char *httpcommand = NULL;
  427. size_t len;
  428. tor_assert(conn);
  429. tor_assert(conn->_base.type == CONN_TYPE_DIR);
  430. tor_free(conn->requested_resource);
  431. if (resource)
  432. conn->requested_resource = tor_strdup(resource);
  433. /* come up with a string for which Host: we want */
  434. if (conn->_base.port == 80) {
  435. strlcpy(hoststring, conn->_base.address, sizeof(hoststring));
  436. } else {
  437. tor_snprintf(hoststring, sizeof(hoststring),"%s:%d",
  438. conn->_base.address, conn->_base.port);
  439. }
  440. /* come up with some proxy lines, if we're using one. */
  441. if (get_options()->HttpProxy) {
  442. char *base64_authenticator=NULL;
  443. const char *authenticator = get_options()->HttpProxyAuthenticator;
  444. tor_snprintf(proxystring, sizeof(proxystring),"http://%s", hoststring);
  445. if (authenticator) {
  446. base64_authenticator = alloc_http_authenticator(authenticator);
  447. if (!base64_authenticator)
  448. log_warn(LD_BUG, "Encoding http authenticator failed");
  449. }
  450. if (base64_authenticator) {
  451. tor_snprintf(proxyauthstring, sizeof(proxyauthstring),
  452. "\r\nProxy-Authorization: Basic %s",
  453. base64_authenticator);
  454. tor_free(base64_authenticator);
  455. } else {
  456. proxyauthstring[0] = 0;
  457. }
  458. } else {
  459. proxystring[0] = 0;
  460. proxyauthstring[0] = 0;
  461. }
  462. switch (purpose) {
  463. case DIR_PURPOSE_FETCH_DIR:
  464. tor_assert(!resource);
  465. tor_assert(!payload);
  466. log_debug(LD_DIR,
  467. "Asking for compressed directory from server running %s",
  468. platform?escaped(platform):"<unknown version>");
  469. httpcommand = "GET";
  470. url = tor_strdup("/tor/dir.z");
  471. break;
  472. case DIR_PURPOSE_FETCH_RUNNING_LIST:
  473. tor_assert(!resource);
  474. tor_assert(!payload);
  475. httpcommand = "GET";
  476. url = tor_strdup("/tor/running-routers");
  477. break;
  478. case DIR_PURPOSE_FETCH_NETWORKSTATUS:
  479. httpcommand = "GET";
  480. len = strlen(resource)+32;
  481. url = tor_malloc(len);
  482. tor_snprintf(url, len, "/tor/status/%s", resource);
  483. break;
  484. case DIR_PURPOSE_FETCH_SERVERDESC:
  485. httpcommand = "GET";
  486. len = strlen(resource)+32;
  487. url = tor_malloc(len);
  488. tor_snprintf(url, len, "/tor/server/%s", resource);
  489. break;
  490. case DIR_PURPOSE_UPLOAD_DIR:
  491. tor_assert(!resource);
  492. tor_assert(payload);
  493. httpcommand = "POST";
  494. url = tor_strdup("/tor/");
  495. break;
  496. case DIR_PURPOSE_FETCH_RENDDESC:
  497. tor_assert(resource);
  498. tor_assert(!payload);
  499. /* this must be true or we wouldn't be doing the lookup */
  500. tor_assert(strlen(resource) <= REND_SERVICE_ID_LEN);
  501. /* This breaks the function abstraction. */
  502. strlcpy(conn->rend_query, resource, sizeof(conn->rend_query));
  503. httpcommand = "GET";
  504. /* Request the most recent versioned descriptor. */
  505. // (XXXX We were going to switch this to fetch rendezvous1 descriptors,
  506. // but that never got testing, and it wasn't a good design.)
  507. len = strlen(resource)+32;
  508. url = tor_malloc(len);
  509. tor_snprintf(url, len, "/tor/rendezvous/%s", resource);
  510. break;
  511. case DIR_PURPOSE_UPLOAD_RENDDESC:
  512. tor_assert(!resource);
  513. tor_assert(payload);
  514. httpcommand = "POST";
  515. url = tor_strdup("/tor/rendezvous/publish");
  516. break;
  517. default:
  518. tor_assert(0);
  519. return;
  520. }
  521. if (strlen(proxystring) + strlen(url) >= 4096) {
  522. log_warn(LD_BUG,
  523. "Bug: squid does not like URLs longer than 4095 bytes, this "
  524. "one is %d bytes long: %s%s",
  525. (int)(strlen(proxystring) + strlen(url)), proxystring, url);
  526. }
  527. tor_snprintf(request, sizeof(request), "%s %s", httpcommand, proxystring);
  528. connection_write_to_buf(request, strlen(request), TO_CONN(conn));
  529. connection_write_to_buf(url, strlen(url), TO_CONN(conn));
  530. tor_free(url);
  531. if (!strcmp(httpcommand, "GET") && !payload) {
  532. tor_snprintf(request, sizeof(request),
  533. " HTTP/1.0\r\nHost: %s%s\r\n\r\n",
  534. hoststring,
  535. proxyauthstring);
  536. } else {
  537. tor_snprintf(request, sizeof(request),
  538. " HTTP/1.0\r\nContent-Length: %lu\r\nHost: %s%s\r\n\r\n",
  539. payload ? (unsigned long)payload_len : 0,
  540. hoststring,
  541. proxyauthstring);
  542. }
  543. connection_write_to_buf(request, strlen(request), TO_CONN(conn));
  544. if (payload) {
  545. /* then send the payload afterwards too */
  546. connection_write_to_buf(payload, payload_len, TO_CONN(conn));
  547. }
  548. }
  549. /** Parse an HTTP request string <b>headers</b> of the form
  550. * \verbatim
  551. * "\%s [http[s]://]\%s HTTP/1..."
  552. * \endverbatim
  553. * If it's well-formed, strdup the second \%s into *<b>url</b>, and
  554. * nul-terminate it. If the url doesn't start with "/tor/", rewrite it
  555. * so it does. Return 0.
  556. * Otherwise, return -1.
  557. */
  558. static int
  559. parse_http_url(char *headers, char **url)
  560. {
  561. char *s, *start, *tmp;
  562. s = (char *)eat_whitespace_no_nl(headers);
  563. if (!*s) return -1;
  564. s = (char *)find_whitespace(s); /* get past GET/POST */
  565. if (!*s) return -1;
  566. s = (char *)eat_whitespace_no_nl(s);
  567. if (!*s) return -1;
  568. start = s; /* this is it, assuming it's valid */
  569. s = (char *)find_whitespace(start);
  570. if (!*s) return -1;
  571. /* tolerate the http[s] proxy style of putting the hostname in the url */
  572. if (s-start >= 4 && !strcmpstart(start,"http")) {
  573. tmp = start + 4;
  574. if (*tmp == 's')
  575. tmp++;
  576. if (s-tmp >= 3 && !strcmpstart(tmp,"://")) {
  577. tmp = strchr(tmp+3, '/');
  578. if (tmp && tmp < s) {
  579. log_debug(LD_DIR,"Skipping over 'http[s]://hostname' string");
  580. start = tmp;
  581. }
  582. }
  583. }
  584. if (s-start < 5 || strcmpstart(start,"/tor/")) { /* need to rewrite it */
  585. *url = tor_malloc(s - start + 5);
  586. strlcpy(*url,"/tor", s-start+5);
  587. strlcat((*url)+4, start, s-start+1);
  588. } else {
  589. *url = tor_strndup(start, s-start);
  590. }
  591. return 0;
  592. }
  593. /** Return a copy of the first HTTP header in <b>headers</b> whose key is
  594. * <b>which</b>. The key should be given with a terminating colon and space;
  595. * this function copies everything after, up to but not including the
  596. * following \\r\\n. */
  597. static char *
  598. http_get_header(const char *headers, const char *which)
  599. {
  600. const char *cp = headers;
  601. while (cp) {
  602. if (!strcmpstart(cp, which)) {
  603. char *eos;
  604. cp += strlen(which);
  605. if ((eos = strchr(cp,'\r')))
  606. return tor_strndup(cp, eos-cp);
  607. else
  608. return tor_strdup(cp);
  609. }
  610. cp = strchr(cp, '\n');
  611. if (cp)
  612. ++cp;
  613. }
  614. return NULL;
  615. }
  616. /** If <b>headers</b> indicates that a proxy was involved, then rewrite
  617. * <b>conn</b>-\>address to describe our best guess of the address that
  618. * originated this HTTP request. */
  619. static void
  620. http_set_address_origin(const char *headers, connection_t *conn)
  621. {
  622. char *fwd;
  623. fwd = http_get_header(headers, "Forwarded-For: ");
  624. if (!fwd)
  625. fwd = http_get_header(headers, "X-Forwarded-For: ");
  626. if (fwd) {
  627. tor_free(conn->address);
  628. conn->address = tor_strdup(escaped(fwd));
  629. tor_free(fwd);
  630. }
  631. }
  632. /** Parse an HTTP response string <b>headers</b> of the form
  633. * \verbatim
  634. * "HTTP/1.\%d \%d\%s\r\n...".
  635. * \endverbatim
  636. *
  637. * If it's well-formed, assign the status code to *<b>code</b> and
  638. * return 0. Otherwise, return -1.
  639. *
  640. * On success: If <b>date</b> is provided, set *date to the Date
  641. * header in the http headers, or 0 if no such header is found. If
  642. * <b>compression</b> is provided, set *<b>compression</b> to the
  643. * compression method given in the Content-Encoding header, or 0 if no
  644. * such header is found, or -1 if the value of the header is not
  645. * recognized. If <b>reason</b> is provided, strdup the reason string
  646. * into it.
  647. */
  648. int
  649. parse_http_response(const char *headers, int *code, time_t *date,
  650. int *compression, char **reason)
  651. {
  652. int n1, n2;
  653. char datestr[RFC1123_TIME_LEN+1];
  654. smartlist_t *parsed_headers;
  655. tor_assert(headers);
  656. tor_assert(code);
  657. while (TOR_ISSPACE(*headers)) headers++; /* tolerate leading whitespace */
  658. if (sscanf(headers, "HTTP/1.%d %d", &n1, &n2) < 2 ||
  659. (n1 != 0 && n1 != 1) ||
  660. (n2 < 100 || n2 >= 600)) {
  661. log_warn(LD_HTTP,"Failed to parse header %s",escaped(headers));
  662. return -1;
  663. }
  664. *code = n2;
  665. parsed_headers = smartlist_create();
  666. smartlist_split_string(parsed_headers, headers, "\n",
  667. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  668. if (reason) {
  669. smartlist_t *status_line_elements = smartlist_create();
  670. tor_assert(smartlist_len(parsed_headers));
  671. smartlist_split_string(status_line_elements,
  672. smartlist_get(parsed_headers, 0),
  673. " ", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  674. tor_assert(smartlist_len(status_line_elements) <= 3);
  675. if (smartlist_len(status_line_elements) == 3) {
  676. *reason = smartlist_get(status_line_elements, 2);
  677. smartlist_set(status_line_elements, 2, NULL); /* Prevent free */
  678. }
  679. SMARTLIST_FOREACH(status_line_elements, char *, cp, tor_free(cp));
  680. smartlist_free(status_line_elements);
  681. }
  682. if (date) {
  683. *date = 0;
  684. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  685. if (!strcmpstart(s, "Date: ")) {
  686. strlcpy(datestr, s+6, sizeof(datestr));
  687. /* This will do nothing on failure, so we don't need to check
  688. the result. We shouldn't warn, since there are many other valid
  689. date formats besides the one we use. */
  690. parse_rfc1123_time(datestr, date);
  691. break;
  692. });
  693. }
  694. if (compression) {
  695. const char *enc = NULL;
  696. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  697. if (!strcmpstart(s, "Content-Encoding: ")) {
  698. enc = s+18; break;
  699. });
  700. if (!enc || !strcmp(enc, "identity")) {
  701. *compression = 0;
  702. } else if (!strcmp(enc, "deflate") || !strcmp(enc, "x-deflate")) {
  703. *compression = ZLIB_METHOD;
  704. } else if (!strcmp(enc, "gzip") || !strcmp(enc, "x-gzip")) {
  705. *compression = GZIP_METHOD;
  706. } else {
  707. log_info(LD_HTTP, "Unrecognized content encoding: %s. Trying to deal.",
  708. escaped(enc));
  709. *compression = -1;
  710. }
  711. }
  712. SMARTLIST_FOREACH(parsed_headers, char *, s, tor_free(s));
  713. smartlist_free(parsed_headers);
  714. return 0;
  715. }
  716. /** Return true iff <b>body</b> doesn't start with a plausible router or
  717. * running-list or directory opening. This is a sign of possible compression.
  718. **/
  719. static int
  720. body_is_plausible(const char *body, size_t len, int purpose)
  721. {
  722. int i;
  723. if (len == 0)
  724. return 1; /* empty bodies don't need decompression */
  725. if (len < 32)
  726. return 0;
  727. if (purpose != DIR_PURPOSE_FETCH_RENDDESC) {
  728. if (!strcmpstart(body,"router") ||
  729. !strcmpstart(body,"signed-directory") ||
  730. !strcmpstart(body,"network-status") ||
  731. !strcmpstart(body,"running-routers"))
  732. return 1;
  733. for (i=0;i<32;++i) {
  734. if (!TOR_ISPRINT(body[i]) && !TOR_ISSPACE(body[i]))
  735. return 0;
  736. }
  737. return 1;
  738. } else {
  739. return 1;
  740. }
  741. }
  742. /** We are a client, and we've finished reading the server's
  743. * response. Parse and it and act appropriately.
  744. *
  745. * If we're still happy with using this directory server in the future, return
  746. * 0. Otherwise return -1; and the caller should consider trying the request
  747. * again.
  748. *
  749. * The caller will take care of marking the connection for close.
  750. */
  751. static int
  752. connection_dir_client_reached_eof(dir_connection_t *conn)
  753. {
  754. char *body;
  755. char *headers;
  756. char *reason = NULL;
  757. size_t body_len=0, orig_len=0;
  758. int status_code;
  759. time_t now, date_header=0;
  760. int delta;
  761. int compression;
  762. int plausible;
  763. int skewed=0;
  764. int allow_partial = conn->_base.purpose == DIR_PURPOSE_FETCH_SERVERDESC;
  765. int was_compressed=0;
  766. char *guess;
  767. switch (fetch_from_buf_http(conn->_base.inbuf,
  768. &headers, MAX_HEADERS_SIZE,
  769. &body, &body_len, MAX_DIR_SIZE,
  770. allow_partial)) {
  771. case -1: /* overflow */
  772. log_warn(LD_PROTOCOL,
  773. "'fetch' response too large (server '%s:%d'). Closing.",
  774. conn->_base.address, conn->_base.port);
  775. return -1;
  776. case 0:
  777. log_info(LD_HTTP,
  778. "'fetch' response not all here, but we're at eof. Closing.");
  779. return -1;
  780. /* case 1, fall through */
  781. }
  782. orig_len = body_len;
  783. if (parse_http_response(headers, &status_code, &date_header,
  784. &compression, &reason) < 0) {
  785. log_warn(LD_HTTP,"Unparseable headers (server '%s:%d'). Closing.",
  786. conn->_base.address, conn->_base.port);
  787. tor_free(body); tor_free(headers);
  788. return -1;
  789. }
  790. if (!reason) reason = tor_strdup("[no reason given]");
  791. log_debug(LD_DIR,
  792. "Received response from directory server '%s:%d': %d %s",
  793. conn->_base.address, conn->_base.port, status_code,
  794. escaped(reason));
  795. /* now check if it's got any hints for us about our IP address. */
  796. guess = http_get_header(headers, X_ADDRESS_HEADER);
  797. if (guess) {
  798. router_new_address_suggestion(guess);
  799. tor_free(guess);
  800. }
  801. if (date_header > 0) {
  802. now = time(NULL);
  803. delta = now-date_header;
  804. if (abs(delta)>ALLOW_DIRECTORY_TIME_SKEW) {
  805. log_fn(router_digest_is_trusted_dir(conn->identity_digest) ?
  806. LOG_WARN : LOG_INFO,
  807. LD_HTTP,
  808. "Received directory with skewed time (server '%s:%d'): "
  809. "we are %d minutes %s, or the directory is %d minutes %s.",
  810. conn->_base.address, conn->_base.port,
  811. abs(delta)/60, delta>0 ? "ahead" : "behind",
  812. abs(delta)/60, delta>0 ? "behind" : "ahead");
  813. skewed = 1; /* don't check the recommended-versions line */
  814. } else {
  815. log_debug(LD_HTTP, "Time on received directory is within tolerance; "
  816. "we are %d seconds skewed. (That's okay.)", delta);
  817. }
  818. }
  819. if (status_code == 503) {
  820. log_info(LD_DIR,"Received http status code %d (%s) from server "
  821. "'%s:%d'. I'll try again soon.",
  822. status_code, escaped(reason), conn->_base.address,
  823. conn->_base.port);
  824. tor_free(body); tor_free(headers); tor_free(reason);
  825. return -1;
  826. }
  827. plausible = body_is_plausible(body, body_len, conn->_base.purpose);
  828. if (compression || !plausible) {
  829. char *new_body = NULL;
  830. size_t new_len = 0;
  831. int guessed = detect_compression_method(body, body_len);
  832. if (compression <= 0 || guessed != compression) {
  833. /* Tell the user if we don't believe what we're told about compression.*/
  834. const char *description1, *description2;
  835. if (compression == ZLIB_METHOD)
  836. description1 = "as deflated";
  837. else if (compression == GZIP_METHOD)
  838. description1 = "as gzipped";
  839. else if (compression == 0)
  840. description1 = "as uncompressed";
  841. else
  842. description1 = "with an unknown Content-Encoding";
  843. if (guessed == ZLIB_METHOD)
  844. description2 = "deflated";
  845. else if (guessed == GZIP_METHOD)
  846. description2 = "gzipped";
  847. else if (!plausible)
  848. description2 = "confusing binary junk";
  849. else
  850. description2 = "uncompressed";
  851. log_info(LD_HTTP, "HTTP body from server '%s:%d' was labeled %s, "
  852. "but it seems to be %s.%s",
  853. conn->_base.address, conn->_base.port, description1,
  854. description2,
  855. (compression>0 && guessed>0)?" Trying both.":"");
  856. }
  857. /* Try declared compression first if we can. */
  858. if (compression > 0)
  859. tor_gzip_uncompress(&new_body, &new_len, body, body_len, compression,
  860. !allow_partial, LOG_PROTOCOL_WARN);
  861. /* Okay, if that didn't work, and we think that it was compressed
  862. * differently, try that. */
  863. if (!new_body && guessed > 0 && compression != guessed)
  864. tor_gzip_uncompress(&new_body, &new_len, body, body_len, guessed,
  865. !allow_partial, LOG_PROTOCOL_WARN);
  866. /* If we're pretty sure that we have a compressed directory, and
  867. * we didn't manage to uncompress it, then warn and bail. */
  868. if (!plausible && !new_body) {
  869. log_fn(LOG_PROTOCOL_WARN, LD_HTTP,
  870. "Unable to decompress HTTP body (server '%s:%d').",
  871. conn->_base.address, conn->_base.port);
  872. tor_free(body); tor_free(headers); tor_free(reason);
  873. return -1;
  874. }
  875. if (new_body) {
  876. tor_free(body);
  877. body = new_body;
  878. body_len = new_len;
  879. was_compressed = 1;
  880. }
  881. }
  882. if (conn->_base.purpose == DIR_PURPOSE_FETCH_DIR) {
  883. /* fetch/process the directory to cache it. */
  884. log_info(LD_DIR,"Received directory (size %d) from server '%s:%d'",
  885. (int)body_len, conn->_base.address, conn->_base.port);
  886. if (status_code != 200) {
  887. log_warn(LD_DIR,"Received http status code %d (%s) from server "
  888. "'%s:%d'. I'll try again soon.",
  889. status_code, escaped(reason), conn->_base.address,
  890. conn->_base.port);
  891. tor_free(body); tor_free(headers); tor_free(reason);
  892. return -1;
  893. }
  894. if (router_parse_directory(body) < 0) {
  895. log_notice(LD_DIR,"I failed to parse the directory I fetched from "
  896. "'%s:%d'. Ignoring.", conn->_base.address, conn->_base.port);
  897. }
  898. note_request(was_compressed?"dl/dir.z":"dl/dir", orig_len);
  899. }
  900. if (conn->_base.purpose == DIR_PURPOSE_FETCH_RUNNING_LIST) {
  901. /* just update our list of running routers, if this list is new info */
  902. log_info(LD_DIR,"Received running-routers list (size %d)", (int)body_len);
  903. if (status_code != 200) {
  904. log_warn(LD_DIR,"Received http status code %d (%s) from server "
  905. "'%s:%d'. I'll try again soon.",
  906. status_code, escaped(reason), conn->_base.address,
  907. conn->_base.port);
  908. tor_free(body); tor_free(headers); tor_free(reason);
  909. return -1;
  910. }
  911. if (router_parse_runningrouters(body)<0) {
  912. log_warn(LD_DIR,
  913. "Bad running-routers from server '%s:%d'. I'll try again soon.",
  914. conn->_base.address, conn->_base.port);
  915. tor_free(body); tor_free(headers); tor_free(reason);
  916. return -1;
  917. }
  918. note_request(was_compressed?"dl/running-routers.z":
  919. "dl/running-routers", orig_len);
  920. }
  921. if (conn->_base.purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS) {
  922. smartlist_t *which = NULL;
  923. int source;
  924. char *cp;
  925. log_info(LD_DIR,"Received networkstatus objects (size %d) from server "
  926. "'%s:%d'",(int) body_len, conn->_base.address, conn->_base.port);
  927. if (status_code != 200) {
  928. log_warn(LD_DIR,
  929. "Received http status code %d (%s) from server "
  930. "'%s:%d' while fetching \"/tor/status/%s\". I'll try again soon.",
  931. status_code, escaped(reason), conn->_base.address,
  932. conn->_base.port, conn->requested_resource);
  933. tor_free(body); tor_free(headers); tor_free(reason);
  934. connection_dir_download_networkstatus_failed(conn);
  935. return -1;
  936. }
  937. note_request(was_compressed?"dl/status.z":"dl/status", orig_len);
  938. if (conn->requested_resource &&
  939. !strcmpstart(conn->requested_resource,"fp/")) {
  940. source = NS_FROM_DIR_BY_FP;
  941. which = smartlist_create();
  942. dir_split_resource_into_fingerprints(conn->requested_resource+3,
  943. which, NULL, 0, 0);
  944. } else if (conn->requested_resource &&
  945. !strcmpstart(conn->requested_resource, "all")) {
  946. source = NS_FROM_DIR_ALL;
  947. which = smartlist_create();
  948. SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  949. trusted_dir_server_t *, ds,
  950. {
  951. char *cp = tor_malloc(HEX_DIGEST_LEN+1);
  952. base16_encode(cp, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
  953. smartlist_add(which, cp);
  954. });
  955. } else {
  956. /* Can we even end up here? -- weasel*/
  957. source = NS_FROM_DIR_BY_FP;
  958. log_warn(LD_BUG, "we received a networkstatus but we did neither ask"
  959. "for it by fp/ nor did we ask for all.");
  960. }
  961. cp = body;
  962. while (*cp) {
  963. char *next = strstr(cp, "\nnetwork-status-version");
  964. if (next)
  965. next[1] = '\0';
  966. /* learn from it, and then remove it from 'which' */
  967. if (router_set_networkstatus(cp, time(NULL), source, which)<0)
  968. break;
  969. if (next) {
  970. next[1] = 'n';
  971. cp = next+1;
  972. }
  973. else
  974. break;
  975. }
  976. routers_update_all_from_networkstatus(); /*launches router downloads*/
  977. directory_info_has_arrived(time(NULL), 0);
  978. if (which) {
  979. if (smartlist_len(which)) {
  980. dir_networkstatus_download_failed(which);
  981. }
  982. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  983. smartlist_free(which);
  984. }
  985. }
  986. if (conn->_base.purpose == DIR_PURPOSE_FETCH_SERVERDESC) {
  987. smartlist_t *which = NULL;
  988. int n_asked_for = 0;
  989. log_info(LD_DIR,"Received server info (size %d) from server '%s:%d'",
  990. (int)body_len, conn->_base.address, conn->_base.port);
  991. note_request(was_compressed?"dl/server.z":"dl/server", orig_len);
  992. if (conn->requested_resource &&
  993. !strcmpstart(conn->requested_resource,"d/")) {
  994. which = smartlist_create();
  995. dir_split_resource_into_fingerprints(conn->requested_resource+2,
  996. which, NULL, 0, 0);
  997. n_asked_for = smartlist_len(which);
  998. }
  999. if (status_code != 200) {
  1000. int dir_okay = status_code == 404 ||
  1001. (status_code == 400 && !strcmp(reason, "Servers unavailable."));
  1002. /* 404 means that it didn't have them; no big deal.
  1003. * Older (pre-0.1.1.8) servers said 400 Servers unavailable instead. */
  1004. log_fn(dir_okay ? LOG_INFO : LOG_WARN, LD_DIR,
  1005. "Received http status code %d (%s) from server '%s:%d' "
  1006. "while fetching \"/tor/server/%s\". I'll try again soon.",
  1007. status_code, escaped(reason), conn->_base.address,
  1008. conn->_base.port, conn->requested_resource);
  1009. if (!which) {
  1010. connection_dir_download_routerdesc_failed(conn);
  1011. } else {
  1012. dir_routerdesc_download_failed(which);
  1013. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  1014. smartlist_free(which);
  1015. }
  1016. tor_free(body); tor_free(headers); tor_free(reason);
  1017. return dir_okay ? 0 : -1;
  1018. }
  1019. /* Learn the routers, assuming we requested by fingerprint or "all".
  1020. * Right now, we only use "authority" to fetch ourself, so we don't want
  1021. * to risk replacing ourself with a router running at the addr:port we
  1022. * think we have.
  1023. */
  1024. if (which || (conn->requested_resource &&
  1025. !strcmpstart(conn->requested_resource, "all"))) {
  1026. /* as we learn from them, we remove them from 'which' */
  1027. router_load_routers_from_string(body, SAVED_NOWHERE, which);
  1028. directory_info_has_arrived(time(NULL), 0);
  1029. }
  1030. if (which) { /* mark remaining ones as failed */
  1031. log_info(LD_DIR, "Received %d/%d routers requested from %s:%d",
  1032. n_asked_for-smartlist_len(which), n_asked_for,
  1033. conn->_base.address, (int)conn->_base.port);
  1034. if (smartlist_len(which)) {
  1035. dir_routerdesc_download_failed(which);
  1036. }
  1037. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  1038. smartlist_free(which);
  1039. }
  1040. if (conn->requested_resource &&
  1041. !strcmpstart(conn->requested_resource,"authority")) {
  1042. /* this might have been a dirport reachability test. see if it is. */
  1043. routerinfo_t *me = router_get_my_routerinfo();
  1044. if (me &&
  1045. router_digest_is_me(conn->identity_digest) &&
  1046. me->addr == conn->_base.addr &&
  1047. me->dir_port == conn->_base.port)
  1048. router_dirport_found_reachable();
  1049. }
  1050. }
  1051. if (conn->_base.purpose == DIR_PURPOSE_UPLOAD_DIR) {
  1052. switch (status_code) {
  1053. case 200:
  1054. log_info(LD_GENERAL,"eof (status 200) after uploading server "
  1055. "descriptor: finished.");
  1056. break;
  1057. case 400:
  1058. log_warn(LD_GENERAL,"http status 400 (%s) response from "
  1059. "dirserver '%s:%d'. Please correct.",
  1060. escaped(reason), conn->_base.address, conn->_base.port);
  1061. break;
  1062. case 403:
  1063. log_warn(LD_GENERAL,
  1064. "http status 403 (%s) response from dirserver "
  1065. "'%s:%d'. Is your clock skewed? Have you mailed us your key "
  1066. "fingerprint? Are you using the right key? Are you using a "
  1067. "private IP address? See http://tor.eff.org/doc/"
  1068. "tor-doc-server.html",escaped(reason), conn->_base.address,
  1069. conn->_base.port);
  1070. break;
  1071. default:
  1072. log_warn(LD_GENERAL,
  1073. "http status %d (%s) reason unexpected (server '%s:%d').",
  1074. status_code, escaped(reason), conn->_base.address,
  1075. conn->_base.port);
  1076. break;
  1077. }
  1078. /* return 0 in all cases, since we don't want to mark any
  1079. * dirservers down just because they don't like us. */
  1080. }
  1081. if (conn->_base.purpose == DIR_PURPOSE_FETCH_RENDDESC) {
  1082. log_info(LD_REND,"Received rendezvous descriptor (size %d, status %d "
  1083. "(%s))",
  1084. (int)body_len, status_code, escaped(reason));
  1085. switch (status_code) {
  1086. case 200:
  1087. if (rend_cache_store(body, body_len) < 0) {
  1088. log_warn(LD_REND,"Failed to store rendezvous descriptor.");
  1089. /* alice's ap_stream will notice when connection_mark_for_close
  1090. * cleans it up */
  1091. } else {
  1092. /* success. notify pending connections about this. */
  1093. conn->_base.purpose = DIR_PURPOSE_HAS_FETCHED_RENDDESC;
  1094. rend_client_desc_here(conn->rend_query);
  1095. }
  1096. break;
  1097. case 404:
  1098. /* not there. pending connections will be notified when
  1099. * connection_mark_for_close cleans it up. */
  1100. break;
  1101. case 400:
  1102. log_warn(LD_REND,
  1103. "http status 400 (%s). Dirserver didn't like our "
  1104. "rendezvous query?", escaped(reason));
  1105. break;
  1106. default:
  1107. log_warn(LD_REND,"http status %d (%s) response unexpected (server "
  1108. "'%s:%d').",
  1109. status_code, escaped(reason), conn->_base.address,
  1110. conn->_base.port);
  1111. break;
  1112. }
  1113. }
  1114. if (conn->_base.purpose == DIR_PURPOSE_UPLOAD_RENDDESC) {
  1115. switch (status_code) {
  1116. case 200:
  1117. log_info(LD_REND,
  1118. "Uploading rendezvous descriptor: finished with status "
  1119. "200 (%s)", escaped(reason));
  1120. break;
  1121. case 400:
  1122. log_warn(LD_REND,"http status 400 (%s) response from dirserver "
  1123. "'%s:%d'. Malformed rendezvous descriptor?",
  1124. escaped(reason), conn->_base.address, conn->_base.port);
  1125. break;
  1126. default:
  1127. log_warn(LD_REND,"http status %d (%s) response unexpected (server "
  1128. "'%s:%d').",
  1129. status_code, escaped(reason), conn->_base.address,
  1130. conn->_base.port);
  1131. break;
  1132. }
  1133. }
  1134. tor_free(body); tor_free(headers); tor_free(reason);
  1135. return 0;
  1136. }
  1137. /** Called when a directory connection reaches EOF */
  1138. int
  1139. connection_dir_reached_eof(dir_connection_t *conn)
  1140. {
  1141. int retval;
  1142. if (conn->_base.state != DIR_CONN_STATE_CLIENT_READING) {
  1143. log_info(LD_HTTP,"conn reached eof, not reading. Closing.");
  1144. connection_close_immediate(TO_CONN(conn)); /* error: give up on flushing */
  1145. connection_mark_for_close(TO_CONN(conn));
  1146. return -1;
  1147. }
  1148. retval = connection_dir_client_reached_eof(conn);
  1149. if (retval == 0) /* success */
  1150. conn->_base.state = DIR_CONN_STATE_CLIENT_FINISHED;
  1151. connection_mark_for_close(TO_CONN(conn));
  1152. return retval;
  1153. }
  1154. /** Read handler for directory connections. (That's connections <em>to</em>
  1155. * directory servers and connections <em>at</em> directory servers.)
  1156. */
  1157. int
  1158. connection_dir_process_inbuf(dir_connection_t *conn)
  1159. {
  1160. tor_assert(conn);
  1161. tor_assert(conn->_base.type == CONN_TYPE_DIR);
  1162. /* Directory clients write, then read data until they receive EOF;
  1163. * directory servers read data until they get an HTTP command, then
  1164. * write their response (when it's finished flushing, they mark for
  1165. * close).
  1166. */
  1167. /* If we're on the dirserver side, look for a command. */
  1168. if (conn->_base.state == DIR_CONN_STATE_SERVER_COMMAND_WAIT) {
  1169. if (directory_handle_command(conn) < 0) {
  1170. connection_mark_for_close(TO_CONN(conn));
  1171. return -1;
  1172. }
  1173. return 0;
  1174. }
  1175. /* XXX for READ states, might want to make sure inbuf isn't too big */
  1176. if (!conn->_base.inbuf_reached_eof)
  1177. log_debug(LD_HTTP,"Got data, not eof. Leaving on inbuf.");
  1178. return 0;
  1179. }
  1180. /** Create an http response for the client <b>conn</b> out of
  1181. * <b>status</b> and <b>reason_phrase</b>. Write it to <b>conn</b>.
  1182. */
  1183. static void
  1184. write_http_status_line(dir_connection_t *conn, int status,
  1185. const char *reason_phrase)
  1186. {
  1187. char buf[256];
  1188. if (tor_snprintf(buf, sizeof(buf), "HTTP/1.0 %d %s\r\n\r\n",
  1189. status, reason_phrase) < 0) {
  1190. log_warn(LD_BUG,"Bug: status line too long.");
  1191. return;
  1192. }
  1193. connection_write_to_buf(buf, strlen(buf), TO_CONN(conn));
  1194. }
  1195. /** DOCDOC */
  1196. static void
  1197. write_http_response_header(dir_connection_t *conn, ssize_t length,
  1198. const char *type, const char *encoding)
  1199. {
  1200. char date[RFC1123_TIME_LEN+1];
  1201. char tmp[1024];
  1202. char *cp;
  1203. tor_assert(conn);
  1204. tor_assert(type);
  1205. format_rfc1123_time(date, time(NULL));
  1206. cp = tmp;
  1207. tor_snprintf(cp, sizeof(tmp),
  1208. "HTTP/1.0 200 OK\r\nDate: %s\r\nContent-Type: %s\r\n"
  1209. X_ADDRESS_HEADER "%s\r\n",
  1210. date, type, conn->_base.address);
  1211. cp += strlen(tmp);
  1212. if (encoding) {
  1213. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  1214. "Content-Encoding: %s\r\n", encoding);
  1215. cp += strlen(cp);
  1216. }
  1217. if (length >= 0) {
  1218. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  1219. "Content-Length: %ld\r\n", (long)length);
  1220. cp += strlen(cp);
  1221. }
  1222. if (sizeof(tmp)-(cp-tmp) > 3)
  1223. memcpy(cp, "\r\n", 3);
  1224. else
  1225. tor_assert(0);
  1226. connection_write_to_buf(tmp, strlen(tmp), TO_CONN(conn));
  1227. }
  1228. /** Helper function: return 1 if there are any dir conns of purpose
  1229. * <b>purpose</b> that are going elsewhere than our own ORPort/Dirport.
  1230. * Else return 0.
  1231. */
  1232. static int
  1233. already_fetching_directory(int purpose)
  1234. {
  1235. int i, n;
  1236. connection_t *conn;
  1237. connection_t **carray;
  1238. get_connection_array(&carray,&n);
  1239. for (i=0;i<n;i++) {
  1240. conn = carray[i];
  1241. if (conn->type == CONN_TYPE_DIR &&
  1242. conn->purpose == purpose &&
  1243. !conn->marked_for_close &&
  1244. !router_digest_is_me(TO_DIR_CONN(conn)->identity_digest))
  1245. return 1;
  1246. }
  1247. return 0;
  1248. }
  1249. #undef INSTRUMENT_DOWNLOADS
  1250. #ifdef INSTRUMENT_DOWNLOADS
  1251. /** DOCDOC */
  1252. static strmap_t *request_bytes_map = NULL;
  1253. /** DOCDOC */
  1254. static void
  1255. note_request(const char *key, size_t bytes)
  1256. {
  1257. uint64_t *n;
  1258. if (!request_bytes_map)
  1259. request_bytes_map = strmap_new();
  1260. n = strmap_get(request_bytes_map, key);
  1261. if (!n) {
  1262. n = tor_malloc_zero(sizeof(uint64_t));
  1263. strmap_set(request_bytes_map, key, n);
  1264. }
  1265. *n += bytes;
  1266. }
  1267. /** DOCDOC */
  1268. char *
  1269. directory_dump_request_log(void)
  1270. {
  1271. smartlist_t *lines;
  1272. char tmp[256];
  1273. char *result;
  1274. strmap_iter_t *iter;
  1275. if (!request_bytes_map)
  1276. request_bytes_map = strmap_new();
  1277. lines = smartlist_create();
  1278. for (iter = strmap_iter_init(request_bytes_map);
  1279. !strmap_iter_done(iter);
  1280. iter = strmap_iter_next(request_bytes_map, iter)) {
  1281. const char *key;
  1282. void *val;
  1283. uint64_t *n;
  1284. strmap_iter_get(iter, &key, &val);
  1285. n = val;
  1286. tor_snprintf(tmp, sizeof(tmp), "%s "U64_FORMAT"\n",
  1287. key, U64_PRINTF_ARG(*n));
  1288. smartlist_add(lines, tor_strdup(tmp));
  1289. }
  1290. smartlist_sort_strings(lines);
  1291. result = smartlist_join_strings(lines, "", 0, NULL);
  1292. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1293. smartlist_free(lines);
  1294. return result;
  1295. }
  1296. #else
  1297. static void
  1298. note_request(const char *key, size_t bytes)
  1299. {
  1300. (void)key;
  1301. (void)bytes;
  1302. }
  1303. char *
  1304. directory_dump_request_log(void)
  1305. {
  1306. return tor_strdup("Not supported.");
  1307. }
  1308. #endif
  1309. /** Helper function: called when a dirserver gets a complete HTTP GET
  1310. * request. Look for a request for a directory or for a rendezvous
  1311. * service descriptor. On finding one, write a response into
  1312. * conn-\>outbuf. If the request is unrecognized, send a 400.
  1313. * Always return 0. */
  1314. static int
  1315. directory_handle_command_get(dir_connection_t *conn, char *headers,
  1316. char *body, size_t body_len)
  1317. {
  1318. size_t dlen;
  1319. const char *cp;
  1320. char *url = NULL;
  1321. /* We ignore the body of a GET request. */
  1322. (void)body;
  1323. (void)body_len;
  1324. log_debug(LD_DIRSERV,"Received GET command.");
  1325. conn->_base.state = DIR_CONN_STATE_SERVER_WRITING;
  1326. if (parse_http_url(headers, &url) < 0) {
  1327. write_http_status_line(conn, 400, "Bad request");
  1328. return 0;
  1329. }
  1330. log_debug(LD_DIRSERV,"rewritten url as '%s'.", url);
  1331. if (!strcmp(url,"/tor/") || !strcmp(url,"/tor/dir.z")) { /* dir fetch */
  1332. int deflated = !strcmp(url,"/tor/dir.z");
  1333. cached_dir_t *d = dirserv_get_directory();
  1334. if (!d) {
  1335. log_notice(LD_DIRSERV,"Client asked for the mirrored directory, but we "
  1336. "don't have a good one yet. Sending 503 Dir not available.");
  1337. write_http_status_line(conn, 503, "Directory unavailable");
  1338. /* try to get a new one now */
  1339. if (!already_fetching_directory(DIR_PURPOSE_FETCH_DIR))
  1340. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
  1341. tor_free(url);
  1342. return 0;
  1343. }
  1344. dlen = deflated ? d->dir_z_len : d->dir_len;
  1345. if (global_write_bucket_empty()) {
  1346. log_info(LD_DIRSERV,
  1347. "Client asked for the mirrored directory, but we've been "
  1348. "writing too many bytes lately. Sending 503 Dir busy.");
  1349. write_http_status_line(conn, 503, "Directory busy, try again later");
  1350. tor_free(url);
  1351. return 0;
  1352. }
  1353. note_request(url, dlen);
  1354. tor_free(url);
  1355. log_debug(LD_DIRSERV,"Dumping %sdirectory to client.",
  1356. deflated?"deflated ":"");
  1357. write_http_response_header(conn, dlen,
  1358. deflated?"application/octet-stream":"text/plain",
  1359. deflated?"deflate":"identity");
  1360. conn->cached_dir = d;
  1361. conn->cached_dir_offset = 0;
  1362. if (! deflated)
  1363. conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
  1364. ++d->refcnt;
  1365. /* Prime the connection with some data. */
  1366. conn->dir_spool_src = DIR_SPOOL_CACHED_DIR;
  1367. connection_dirserv_flushed_some(conn);
  1368. return 0;
  1369. }
  1370. if (!strcmp(url,"/tor/running-routers") ||
  1371. !strcmp(url,"/tor/running-routers.z")) { /* running-routers fetch */
  1372. int deflated = !strcmp(url,"/tor/running-routers.z");
  1373. dlen = dirserv_get_runningrouters(&cp, deflated);
  1374. note_request(url, dlen);
  1375. tor_free(url);
  1376. if (!dlen) { /* we failed to create/cache cp */
  1377. write_http_status_line(conn, 503, "Directory unavailable");
  1378. /* try to get a new one now */
  1379. if (!already_fetching_directory(DIR_PURPOSE_FETCH_RUNNING_LIST))
  1380. directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST, NULL, 1);
  1381. return 0;
  1382. }
  1383. write_http_response_header(conn, dlen,
  1384. deflated?"application/octet-stream":"text/plain",
  1385. deflated?"deflate":"identity");
  1386. connection_write_to_buf(cp, strlen(cp), TO_CONN(conn));
  1387. return 0;
  1388. }
  1389. if (!strcmpstart(url,"/tor/status/")) {
  1390. /* v2 network status fetch. */
  1391. size_t url_len = strlen(url);
  1392. int deflated = !strcmp(url+url_len-2, ".z");
  1393. smartlist_t *dir_fps = smartlist_create();
  1394. const char *request_type = NULL;
  1395. const char *key = url + strlen("/tor/status/");
  1396. if (deflated)
  1397. url[url_len-2] = '\0';
  1398. dirserv_get_networkstatus_v2_fingerprints(dir_fps, key);
  1399. if (!strcmpstart(key, "fp/"))
  1400. request_type = deflated?"/tor/status/fp.z":"/tor/status/fp";
  1401. else if (!strcmpstart(key, "authority"))
  1402. request_type = deflated?"/tor/status/authority.z":
  1403. "/tor/status/authority";
  1404. else if (!strcmpstart(key, "all"))
  1405. request_type = deflated?"/tor/status/all.z":"/tor/status/all";
  1406. else
  1407. request_type = "/tor/status/?";
  1408. tor_free(url);
  1409. if (!smartlist_len(dir_fps)) { /* we failed to create/cache cp */
  1410. write_http_status_line(conn, 503, "Network status object unavailable");
  1411. smartlist_free(dir_fps);
  1412. return 0;
  1413. }
  1414. // note_request(request_type,dlen);
  1415. write_http_response_header(conn, -1,
  1416. deflated?"application/octet_stream":"text/plain",
  1417. deflated?"deflate":NULL);
  1418. conn->fingerprint_stack = dir_fps;
  1419. if (! deflated)
  1420. conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
  1421. /* Prime the connection with some data. */
  1422. conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
  1423. connection_dirserv_flushed_some(conn);
  1424. return 0;
  1425. }
  1426. if (!strcmpstart(url,"/tor/server/")) {
  1427. size_t url_len = strlen(url);
  1428. int deflated = !strcmp(url+url_len-2, ".z");
  1429. int res;
  1430. const char *msg;
  1431. const char *request_type = NULL;
  1432. if (deflated)
  1433. url[url_len-2] = '\0';
  1434. conn->fingerprint_stack = smartlist_create();
  1435. res = dirserv_get_routerdesc_fingerprints(conn->fingerprint_stack, url,
  1436. &msg);
  1437. if (!strcmpstart(url, "/tor/server/fp/"))
  1438. request_type = deflated?"/tor/server/fp.z":"/tor/server/fp";
  1439. else if (!strcmpstart(url, "/tor/server/authority"))
  1440. request_type = deflated?"/tor/server/authority.z":
  1441. "/tor/server/authority";
  1442. else if (!strcmpstart(url, "/tor/server/all"))
  1443. request_type = deflated?"/tor/server/all.z":"/tor/server/all";
  1444. else if (!strcmpstart(url, "/tor/server/d/"))
  1445. request_type = deflated?"/tor/server/d.z":"/tor/server/d";
  1446. else
  1447. request_type = "/tor/server/?";
  1448. if (!strcmpstart(url, "/tor/server/d/"))
  1449. conn->dir_spool_src = DIR_SPOOL_SERVER_BY_DIGEST;
  1450. else
  1451. conn->dir_spool_src = DIR_SPOOL_SERVER_BY_FP;
  1452. tor_free(url);
  1453. if (res < 0)
  1454. write_http_status_line(conn, 404, msg);
  1455. else {
  1456. write_http_response_header(conn, -1,
  1457. deflated?"application/octet_stream":"text/plain",
  1458. deflated?"deflate":NULL);
  1459. if (deflated)
  1460. conn->zlib_state = tor_zlib_new(1, ZLIB_METHOD);
  1461. /* Prime the connection with some data. */
  1462. connection_dirserv_flushed_some(conn);
  1463. }
  1464. return 0;
  1465. }
  1466. if (!strcmpstart(url,"/tor/rendezvous/") ||
  1467. !strcmpstart(url,"/tor/rendezvous1/")) {
  1468. /* rendezvous descriptor fetch */
  1469. const char *descp;
  1470. size_t desc_len;
  1471. int versioned = !strcmpstart(url,"/tor/rendezvous1/");
  1472. const char *query = url+strlen("/tor/rendezvous/")+(versioned?1:0);
  1473. if (!authdir_mode(get_options())) {
  1474. /* We don't hand out rend descs. In fact, it could be a security
  1475. * risk, since rend_cache_lookup_desc() below would provide it
  1476. * if we're gone to the site recently, and 404 if we haven't.
  1477. *
  1478. * Reject. */
  1479. write_http_status_line(conn, 400, "Nonauthoritative directory does not "
  1480. "store rendezvous descriptors");
  1481. tor_free(url);
  1482. return 0;
  1483. }
  1484. switch (rend_cache_lookup_desc(query, versioned?-1:0, &descp, &desc_len)) {
  1485. case 1: /* valid */
  1486. write_http_response_header(conn, desc_len, "application/octet-stream",
  1487. NULL);
  1488. note_request("/tor/rendezvous?/", desc_len);
  1489. /* need to send descp separately, because it may include nuls */
  1490. connection_write_to_buf(descp, desc_len, TO_CONN(conn));
  1491. break;
  1492. case 0: /* well-formed but not present */
  1493. write_http_status_line(conn, 404, "Not found");
  1494. break;
  1495. case -1: /* not well-formed */
  1496. write_http_status_line(conn, 400, "Bad request");
  1497. break;
  1498. }
  1499. tor_free(url);
  1500. return 0;
  1501. }
  1502. if (!strcmpstart(url,"/tor/bytes.txt")) {
  1503. char *bytes = directory_dump_request_log();
  1504. size_t len = strlen(bytes);
  1505. write_http_response_header(conn, len, "text/plain", NULL);
  1506. connection_write_to_buf(bytes, len, TO_CONN(conn));
  1507. tor_free(bytes);
  1508. tor_free(url);
  1509. return 0;
  1510. }
  1511. if (!strcmp(url,"/tor/robots.txt")) { /* /robots.txt will have been
  1512. rewritten to /tor/robots.txt */
  1513. char robots[] = "User-agent: *\r\nDisallow: /\r\n";
  1514. size_t len = strlen(robots);
  1515. write_http_response_header(conn, len, "text/plain", NULL);
  1516. connection_write_to_buf(robots, len, TO_CONN(conn));
  1517. tor_free(url);
  1518. return 0;
  1519. }
  1520. if (!strcmp(url,"/tor/dir-all-weaselhack") &&
  1521. (conn->_base.addr == 0x7f000001ul) &&
  1522. authdir_mode(get_options())) {
  1523. /* XXX until weasel rewrites his scripts XXXX012 */
  1524. char *new_directory=NULL;
  1525. if (dirserv_dump_directory_to_string(&new_directory,
  1526. get_identity_key(), 1)) {
  1527. log_warn(LD_BUG, "Error creating full v1 directory.");
  1528. tor_free(new_directory);
  1529. write_http_status_line(conn, 503, "Directory unavailable");
  1530. return 0;
  1531. }
  1532. dlen = strlen(new_directory);
  1533. write_http_response_header(conn, dlen, "text/plain", "identity");
  1534. connection_write_to_buf(new_directory, dlen, TO_CONN(conn));
  1535. tor_free(new_directory);
  1536. tor_free(url);
  1537. return 0;
  1538. }
  1539. /* we didn't recognize the url */
  1540. write_http_status_line(conn, 404, "Not found");
  1541. tor_free(url);
  1542. return 0;
  1543. }
  1544. /** Helper function: called when a dirserver gets a complete HTTP POST
  1545. * request. Look for an uploaded server descriptor or rendezvous
  1546. * service descriptor. On finding one, process it and write a
  1547. * response into conn-\>outbuf. If the request is unrecognized, send a
  1548. * 400. Always return 0. */
  1549. static int
  1550. directory_handle_command_post(dir_connection_t *conn, char *headers,
  1551. char *body, size_t body_len)
  1552. {
  1553. char *url = NULL;
  1554. log_debug(LD_DIRSERV,"Received POST command.");
  1555. conn->_base.state = DIR_CONN_STATE_SERVER_WRITING;
  1556. if (!authdir_mode(get_options())) {
  1557. /* we just provide cached directories; we don't want to
  1558. * receive anything. */
  1559. write_http_status_line(conn, 400, "Nonauthoritative directory does not "
  1560. "accept posted server descriptors");
  1561. return 0;
  1562. }
  1563. if (parse_http_url(headers, &url) < 0) {
  1564. write_http_status_line(conn, 400, "Bad request");
  1565. return 0;
  1566. }
  1567. log_debug(LD_DIRSERV,"rewritten url as '%s'.", url);
  1568. if (!strcmp(url,"/tor/")) { /* server descriptor post */
  1569. const char *msg;
  1570. int r = dirserv_add_descriptor(body, &msg);
  1571. tor_assert(msg);
  1572. if (r > 0)
  1573. dirserv_get_directory(); /* rebuild and write to disk */
  1574. switch (r) {
  1575. case -2:
  1576. case -1:
  1577. case 1:
  1578. log_notice(LD_DIRSERV,"Rejected router descriptor from %s.",
  1579. conn->_base.address);
  1580. /* malformed descriptor, or something wrong */
  1581. write_http_status_line(conn, 400, msg);
  1582. break;
  1583. case 0: /* accepted but discarded */
  1584. case 2: /* accepted */
  1585. write_http_status_line(conn, 200, msg);
  1586. break;
  1587. }
  1588. goto done;
  1589. }
  1590. if (!strcmpstart(url,"/tor/rendezvous/publish")) {
  1591. /* rendezvous descriptor post */
  1592. if (rend_cache_store(body, body_len) < 0) {
  1593. // char tmp[1024*2+1];
  1594. log_fn(LOG_PROTOCOL_WARN, LD_DIRSERV,
  1595. "Rejected rend descriptor (length %d) from %s.",
  1596. (int)body_len, conn->_base.address);
  1597. #if 0
  1598. if (body_len <= 1024) {
  1599. base16_encode(tmp, sizeof(tmp), body, body_len);
  1600. log_notice(LD_DIRSERV,"Body was: %s", escaped(tmp));
  1601. }
  1602. #endif
  1603. write_http_status_line(conn, 400, "Invalid service descriptor rejected");
  1604. } else {
  1605. write_http_status_line(conn, 200, "Service descriptor stored");
  1606. }
  1607. goto done;
  1608. }
  1609. /* we didn't recognize the url */
  1610. write_http_status_line(conn, 404, "Not found");
  1611. done:
  1612. tor_free(url);
  1613. return 0;
  1614. }
  1615. /** Called when a dirserver receives data on a directory connection;
  1616. * looks for an HTTP request. If the request is complete, remove it
  1617. * from the inbuf, try to process it; otherwise, leave it on the
  1618. * buffer. Return a 0 on success, or -1 on error.
  1619. */
  1620. static int
  1621. directory_handle_command(dir_connection_t *conn)
  1622. {
  1623. char *headers=NULL, *body=NULL;
  1624. size_t body_len=0;
  1625. int r;
  1626. tor_assert(conn);
  1627. tor_assert(conn->_base.type == CONN_TYPE_DIR);
  1628. switch (fetch_from_buf_http(conn->_base.inbuf,
  1629. &headers, MAX_HEADERS_SIZE,
  1630. &body, &body_len, MAX_BODY_SIZE, 0)) {
  1631. case -1: /* overflow */
  1632. log_warn(LD_DIRSERV,
  1633. "Invalid input from address '%s'. Closing.",
  1634. conn->_base.address);
  1635. return -1;
  1636. case 0:
  1637. log_debug(LD_DIRSERV,"command not all here yet.");
  1638. return 0;
  1639. /* case 1, fall through */
  1640. }
  1641. http_set_address_origin(headers, TO_CONN(conn));
  1642. //log_debug(LD_DIRSERV,"headers %s, body %s.", headers, body);
  1643. if (!strncasecmp(headers,"GET",3))
  1644. r = directory_handle_command_get(conn, headers, body, body_len);
  1645. else if (!strncasecmp(headers,"POST",4))
  1646. r = directory_handle_command_post(conn, headers, body, body_len);
  1647. else {
  1648. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1649. "Got headers %s with unknown command. Closing.",
  1650. escaped(headers));
  1651. r = -1;
  1652. }
  1653. tor_free(headers); tor_free(body);
  1654. return r;
  1655. }
  1656. /** Write handler for directory connections; called when all data has
  1657. * been flushed. Close the connection or wait for a response as
  1658. * appropriate.
  1659. */
  1660. int
  1661. connection_dir_finished_flushing(dir_connection_t *conn)
  1662. {
  1663. tor_assert(conn);
  1664. tor_assert(conn->_base.type == CONN_TYPE_DIR);
  1665. switch (conn->_base.state) {
  1666. case DIR_CONN_STATE_CLIENT_SENDING:
  1667. log_debug(LD_DIR,"client finished sending command.");
  1668. conn->_base.state = DIR_CONN_STATE_CLIENT_READING;
  1669. connection_stop_writing(TO_CONN(conn));
  1670. return 0;
  1671. case DIR_CONN_STATE_SERVER_WRITING:
  1672. log_debug(LD_DIRSERV,"Finished writing server response. Closing.");
  1673. connection_mark_for_close(TO_CONN(conn));
  1674. return 0;
  1675. default:
  1676. log_warn(LD_BUG,"Bug: called in unexpected state %d.",
  1677. conn->_base.state);
  1678. tor_fragile_assert();
  1679. return -1;
  1680. }
  1681. return 0;
  1682. }
  1683. /** Connected handler for directory connections: begin sending data to the
  1684. * server */
  1685. int
  1686. connection_dir_finished_connecting(dir_connection_t *conn)
  1687. {
  1688. tor_assert(conn);
  1689. tor_assert(conn->_base.type == CONN_TYPE_DIR);
  1690. tor_assert(conn->_base.state == DIR_CONN_STATE_CONNECTING);
  1691. log_debug(LD_HTTP,"Dir connection to router %s:%u established.",
  1692. conn->_base.address,conn->_base.port);
  1693. conn->_base.state = DIR_CONN_STATE_CLIENT_SENDING; /* start flushing conn */
  1694. return 0;
  1695. }
  1696. /** Called when one or more networkstatus fetches have failed (with uppercase
  1697. * fingerprints listed in <b>failed</>). Mark those fingerprints as having
  1698. * failed once. */
  1699. static void
  1700. dir_networkstatus_download_failed(smartlist_t *failed)
  1701. {
  1702. SMARTLIST_FOREACH(failed, const char *, fp,
  1703. {
  1704. char digest[DIGEST_LEN];
  1705. trusted_dir_server_t *dir;
  1706. base16_decode(digest, DIGEST_LEN, fp, strlen(fp));
  1707. dir = router_get_trusteddirserver_by_digest(digest);
  1708. if (dir)
  1709. ++dir->n_networkstatus_failures;
  1710. });
  1711. }
  1712. /** Called when one or more routerdesc fetches have failed (with uppercase
  1713. * fingerprints listed in <b>failed</b>). */
  1714. static void
  1715. dir_routerdesc_download_failed(smartlist_t *failed)
  1716. {
  1717. char digest[DIGEST_LEN];
  1718. local_routerstatus_t *rs;
  1719. time_t now = time(NULL);
  1720. int server = server_mode(get_options()) && get_options()->DirPort;
  1721. SMARTLIST_FOREACH(failed, const char *, cp,
  1722. {
  1723. base16_decode(digest, DIGEST_LEN, cp, strlen(cp));
  1724. rs = router_get_combined_status_by_digest(digest);
  1725. if (!rs || rs->n_download_failures >= MAX_ROUTERDESC_DOWNLOAD_FAILURES)
  1726. continue;
  1727. ++rs->n_download_failures;
  1728. if (server) {
  1729. switch (rs->n_download_failures) {
  1730. case 1: rs->next_attempt_at = 0; break;
  1731. case 2: rs->next_attempt_at = 0; break;
  1732. case 3: rs->next_attempt_at = now+60; break;
  1733. case 4: rs->next_attempt_at = now+60; break;
  1734. case 5: rs->next_attempt_at = now+60*2; break;
  1735. case 6: rs->next_attempt_at = now+60*5; break;
  1736. case 7: rs->next_attempt_at = now+60*15; break;
  1737. default: rs->next_attempt_at = TIME_MAX; break;
  1738. }
  1739. } else {
  1740. switch (rs->n_download_failures) {
  1741. case 1: rs->next_attempt_at = 0; break;
  1742. case 2: rs->next_attempt_at = now+60; break;
  1743. case 3: rs->next_attempt_at = now+60*5; break;
  1744. case 4: rs->next_attempt_at = now+60*10; break;
  1745. default: rs->next_attempt_at = TIME_MAX; break;
  1746. }
  1747. }
  1748. if (rs->next_attempt_at == 0)
  1749. log_debug(LD_DIR, "%s failed %d time(s); I'll try again immediately.",
  1750. cp, (int)rs->n_download_failures);
  1751. else if (rs->next_attempt_at < TIME_MAX)
  1752. log_debug(LD_DIR, "%s failed %d time(s); I'll try again in %d seconds.",
  1753. cp, (int)rs->n_download_failures,
  1754. (int)(rs->next_attempt_at-now));
  1755. else
  1756. log_debug(LD_DIR, "%s failed %d time(s); Giving up for a while.",
  1757. cp, (int)rs->n_download_failures);
  1758. });
  1759. /* update_router_descriptor_downloads(time(NULL)); */
  1760. }
  1761. /* Given a directory <b>resource</b> request, containing zero
  1762. * or more strings separated by plus signs, followed optionally by ".z", store
  1763. * the strings, in order, into <b>fp_out</b>. If <b>compressed_out</b> is
  1764. * non-NULL, set it to 1 if the resource ends in ".z", else set it to 0. If
  1765. * decode_hex is true, then delete all elements that aren't hex digests, and
  1766. * decode the rest. If sort_uniq is true, then sort the list and remove
  1767. * all duplicates.
  1768. */
  1769. int
  1770. dir_split_resource_into_fingerprints(const char *resource,
  1771. smartlist_t *fp_out, int *compressed_out,
  1772. int decode_hex, int sort_uniq)
  1773. {
  1774. smartlist_t *fp_tmp = smartlist_create();
  1775. tor_assert(fp_out);
  1776. smartlist_split_string(fp_tmp, resource, "+", 0, 0);
  1777. if (compressed_out)
  1778. *compressed_out = 0;
  1779. if (smartlist_len(fp_tmp)) {
  1780. char *last = smartlist_get(fp_tmp,smartlist_len(fp_tmp)-1);
  1781. size_t last_len = strlen(last);
  1782. if (last_len > 2 && !strcmp(last+last_len-2, ".z")) {
  1783. last[last_len-2] = '\0';
  1784. if (compressed_out)
  1785. *compressed_out = 1;
  1786. }
  1787. }
  1788. if (decode_hex) {
  1789. int i;
  1790. char *cp, *d = NULL;
  1791. for (i = 0; i < smartlist_len(fp_tmp); ++i) {
  1792. cp = smartlist_get(fp_tmp, i);
  1793. if (strlen(cp) != HEX_DIGEST_LEN) {
  1794. log_info(LD_DIR,
  1795. "Skipping digest %s with non-standard length.", escaped(cp));
  1796. smartlist_del_keeporder(fp_tmp, i--);
  1797. goto again;
  1798. }
  1799. d = tor_malloc_zero(DIGEST_LEN);
  1800. if (base16_decode(d, DIGEST_LEN, cp, HEX_DIGEST_LEN)<0) {
  1801. log_info(LD_DIR, "Skipping non-decodable digest %s", escaped(cp));
  1802. smartlist_del_keeporder(fp_tmp, i--);
  1803. goto again;
  1804. }
  1805. smartlist_set(fp_tmp, i, d);
  1806. d = NULL;
  1807. again:
  1808. tor_free(cp);
  1809. tor_free(d);
  1810. }
  1811. }
  1812. if (sort_uniq) {
  1813. smartlist_t *fp_tmp2 = smartlist_create();
  1814. int i;
  1815. if (decode_hex)
  1816. smartlist_sort_digests(fp_tmp);
  1817. else
  1818. smartlist_sort_strings(fp_tmp);
  1819. if (smartlist_len(fp_tmp))
  1820. smartlist_add(fp_tmp2, smartlist_get(fp_tmp, 0));
  1821. for (i = 1; i < smartlist_len(fp_tmp); ++i) {
  1822. char *cp = smartlist_get(fp_tmp, i);
  1823. char *last = smartlist_get(fp_tmp2, smartlist_len(fp_tmp2)-1);
  1824. if ((decode_hex && memcmp(cp, last, DIGEST_LEN))
  1825. || (!decode_hex && strcasecmp(cp, last)))
  1826. smartlist_add(fp_tmp2, cp);
  1827. else
  1828. tor_free(cp);
  1829. }
  1830. smartlist_free(fp_tmp);
  1831. fp_tmp = fp_tmp2;
  1832. }
  1833. smartlist_add_all(fp_out, fp_tmp);
  1834. smartlist_free(fp_tmp);
  1835. return 0;
  1836. }