connection_edge.c 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char connection_edge_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file connection_edge.c
  10. * \brief Handle edge streams.
  11. **/
  12. #include "or.h"
  13. static addr_policy_t *socks_policy = NULL;
  14. /* List of exit_redirect_t */
  15. static smartlist_t *redirect_exit_list = NULL;
  16. static int connection_ap_handshake_process_socks(connection_t *conn);
  17. /** An AP stream has failed/finished. If it hasn't already sent back
  18. * a socks reply, send one now (based on endreason). Also set
  19. * has_sent_end to 1, and mark the conn.
  20. */
  21. void
  22. _connection_mark_unattached_ap(connection_t *conn, int endreason,
  23. int line, const char *file)
  24. {
  25. tor_assert(conn->type == CONN_TYPE_AP);
  26. conn->has_sent_end = 1; /* no circ yet */
  27. if (conn->marked_for_close) {
  28. /* This call will warn as appropriate. */
  29. _connection_mark_for_close(conn, line, file);
  30. return;
  31. }
  32. if (!conn->socks_request->has_finished) {
  33. socks5_reply_status_t socksreason =
  34. connection_edge_end_reason_socks5_response(endreason);
  35. if (endreason == END_STREAM_REASON_ALREADY_SOCKS_REPLIED)
  36. log_warn(LD_BUG,
  37. "Bug: stream (marked at %s:%d) sending two socks replies?",
  38. file, line);
  39. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT)
  40. connection_ap_handshake_socks_reply(conn, NULL, 0, socksreason);
  41. else
  42. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
  43. 0, NULL, -1);
  44. }
  45. _connection_mark_for_close(conn, line, file);
  46. conn->hold_open_until_flushed = 1;
  47. }
  48. /** There was an EOF. Send an end and mark the connection for close.
  49. */
  50. int
  51. connection_edge_reached_eof(connection_t *conn)
  52. {
  53. #ifdef HALF_OPEN
  54. /* eof reached; we're done reading, but we might want to write more. */
  55. conn->done_receiving = 1;
  56. shutdown(conn->s, 0); /* XXX check return, refactor NM */
  57. if (conn->done_sending) {
  58. connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
  59. connection_mark_for_close(conn);
  60. } else {
  61. connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
  62. RELAY_COMMAND_END,
  63. NULL, 0, conn->cpath_layer);
  64. }
  65. return 0;
  66. #else
  67. if (buf_datalen(conn->inbuf) && connection_state_is_open(conn)) {
  68. /* it still has stuff to process. don't let it die yet. */
  69. return 0;
  70. }
  71. log_info(LD_EDGE,"conn (fd %d) reached eof. Closing.", conn->s);
  72. if (!conn->marked_for_close) {
  73. /* only mark it if not already marked. it's possible to
  74. * get the 'end' right around when the client hangs up on us. */
  75. connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
  76. if (conn->socks_request) /* eof, so don't send a socks reply back */
  77. conn->socks_request->has_finished = 1;
  78. connection_mark_for_close(conn);
  79. }
  80. return 0;
  81. #endif
  82. }
  83. /** Handle new bytes on conn->inbuf based on state:
  84. * - If it's waiting for socks info, try to read another step of the
  85. * socks handshake out of conn->inbuf.
  86. * - If it's open, then package more relay cells from the stream.
  87. * - Else, leave the bytes on inbuf alone for now.
  88. *
  89. * Mark and return -1 if there was an unexpected error with the conn,
  90. * else return 0.
  91. */
  92. int
  93. connection_edge_process_inbuf(connection_t *conn, int package_partial)
  94. {
  95. tor_assert(conn);
  96. tor_assert(CONN_IS_EDGE(conn));
  97. switch (conn->state) {
  98. case AP_CONN_STATE_SOCKS_WAIT:
  99. if (connection_ap_handshake_process_socks(conn) < 0) {
  100. /* already marked */
  101. return -1;
  102. }
  103. return 0;
  104. case AP_CONN_STATE_OPEN:
  105. case EXIT_CONN_STATE_OPEN:
  106. if (connection_edge_package_raw_inbuf(conn, package_partial) < 0) {
  107. /* (We already sent an end cell if possible) */
  108. connection_mark_for_close(conn);
  109. return -1;
  110. }
  111. return 0;
  112. case EXIT_CONN_STATE_CONNECTING:
  113. case AP_CONN_STATE_RENDDESC_WAIT:
  114. case AP_CONN_STATE_CIRCUIT_WAIT:
  115. case AP_CONN_STATE_CONNECT_WAIT:
  116. case AP_CONN_STATE_RESOLVE_WAIT:
  117. case AP_CONN_STATE_CONTROLLER_WAIT:
  118. log_info(LD_EDGE,
  119. "data from edge while in '%s' state. Leaving it on buffer.",
  120. conn_state_to_string(conn->type, conn->state));
  121. return 0;
  122. }
  123. log_warn(LD_BUG,"Bug: Got unexpected state %d. Closing.",conn->state);
  124. tor_fragile_assert();
  125. connection_edge_end(conn, END_STREAM_REASON_INTERNAL, conn->cpath_layer);
  126. connection_mark_for_close(conn);
  127. return -1;
  128. }
  129. /** This edge needs to be closed, because its circuit has closed.
  130. * Mark it for close and return 0.
  131. */
  132. int
  133. connection_edge_destroy(uint16_t circ_id, connection_t *conn)
  134. {
  135. tor_assert(CONN_IS_EDGE(conn));
  136. if (!conn->marked_for_close) {
  137. log_info(LD_EDGE,
  138. "CircID %d: At an edge. Marking connection for close.", circ_id);
  139. if (conn->type == CONN_TYPE_AP) {
  140. connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
  141. } else {
  142. conn->has_sent_end = 1; /* closing the circuit, nothing to send to */
  143. connection_mark_for_close(conn);
  144. conn->hold_open_until_flushed = 1;
  145. }
  146. }
  147. conn->cpath_layer = NULL;
  148. conn->on_circuit = NULL;
  149. return 0;
  150. }
  151. /** Send a relay end cell from stream <b>conn</b> to conn's circuit,
  152. * with a destination of cpath_layer. (If cpath_layer is NULL, the
  153. * destination is the circuit's origin.) Mark the relay end cell as
  154. * closing because of <b>reason</b>.
  155. *
  156. * Return -1 if this function has already been called on this conn,
  157. * else return 0.
  158. */
  159. int
  160. connection_edge_end(connection_t *conn, char reason, crypt_path_t *cpath_layer)
  161. {
  162. char payload[RELAY_PAYLOAD_SIZE];
  163. size_t payload_len=1;
  164. circuit_t *circ;
  165. if (conn->has_sent_end) {
  166. log_warn(LD_BUG,"Harmless bug: Calling connection_edge_end (reason %d) "
  167. "on an already ended stream?", reason);
  168. tor_fragile_assert();
  169. return -1;
  170. }
  171. if (conn->marked_for_close) {
  172. log_warn(LD_BUG,
  173. "Bug: called on conn that's already marked for close at %s:%d.",
  174. conn->marked_for_close_file, conn->marked_for_close);
  175. return 0;
  176. }
  177. payload[0] = reason;
  178. if (reason == END_STREAM_REASON_EXITPOLICY &&
  179. !connection_edge_is_rendezvous_stream(conn)) {
  180. set_uint32(payload+1, htonl(conn->addr));
  181. /* XXXX fill with a real TTL! */
  182. set_uint32(payload+5, htonl(MAX_DNS_ENTRY_AGE));
  183. payload_len += 8;
  184. }
  185. circ = circuit_get_by_edge_conn(conn);
  186. if (circ && !circ->marked_for_close) {
  187. log_debug(LD_EDGE,"Marking conn (fd %d) and sending end.",conn->s);
  188. connection_edge_send_command(conn, circ, RELAY_COMMAND_END,
  189. payload, payload_len, cpath_layer);
  190. } else {
  191. log_debug(LD_EDGE,"Marking conn (fd %d); no circ to send end.",conn->s);
  192. }
  193. conn->has_sent_end = 1;
  194. return 0;
  195. }
  196. /** An error has just occured on an operation on an edge connection
  197. * <b>conn</b>. Extract the errno; convert it to an end reason, and send
  198. * an appropriate relay end cell to <b>cpath_layer</b>.
  199. **/
  200. int
  201. connection_edge_end_errno(connection_t *conn, crypt_path_t *cpath_layer)
  202. {
  203. uint8_t reason;
  204. tor_assert(conn);
  205. reason = (uint8_t)errno_to_end_reason(tor_socket_errno(conn->s));
  206. return connection_edge_end(conn, reason, cpath_layer);
  207. }
  208. /** Connection <b>conn</b> has finished writing and has no bytes left on
  209. * its outbuf.
  210. *
  211. * If it's in state 'open', stop writing, consider responding with a
  212. * sendme, and return.
  213. * Otherwise, stop writing and return.
  214. *
  215. * If <b>conn</b> is broken, mark it for close and return -1, else
  216. * return 0.
  217. */
  218. int
  219. connection_edge_finished_flushing(connection_t *conn)
  220. {
  221. tor_assert(conn);
  222. tor_assert(CONN_IS_EDGE(conn));
  223. switch (conn->state) {
  224. case AP_CONN_STATE_OPEN:
  225. case EXIT_CONN_STATE_OPEN:
  226. connection_stop_writing(conn);
  227. connection_edge_consider_sending_sendme(conn);
  228. return 0;
  229. case AP_CONN_STATE_SOCKS_WAIT:
  230. case AP_CONN_STATE_RENDDESC_WAIT:
  231. case AP_CONN_STATE_CIRCUIT_WAIT:
  232. case AP_CONN_STATE_CONNECT_WAIT:
  233. case AP_CONN_STATE_CONTROLLER_WAIT:
  234. connection_stop_writing(conn);
  235. return 0;
  236. default:
  237. log_warn(LD_BUG,"BUG: called in unexpected state %d.", conn->state);
  238. tor_fragile_assert();
  239. return -1;
  240. }
  241. return 0;
  242. }
  243. /** Connected handler for exit connections: start writing pending
  244. * data, deliver 'CONNECTED' relay cells as appropriate, and check
  245. * any pending data that may have been received. */
  246. int
  247. connection_edge_finished_connecting(connection_t *conn)
  248. {
  249. char valbuf[INET_NTOA_BUF_LEN];
  250. struct in_addr in;
  251. tor_assert(conn);
  252. tor_assert(conn->type == CONN_TYPE_EXIT);
  253. tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
  254. in.s_addr = htonl(conn->addr);
  255. tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
  256. log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
  257. safe_str(conn->address),conn->port,safe_str(valbuf));
  258. conn->state = EXIT_CONN_STATE_OPEN;
  259. connection_watch_events(conn, EV_READ); /* stop writing, continue reading */
  260. if (connection_wants_to_flush(conn)) /* in case there are any queued relay
  261. * cells */
  262. connection_start_writing(conn);
  263. /* deliver a 'connected' relay cell back through the circuit. */
  264. if (connection_edge_is_rendezvous_stream(conn)) {
  265. if (connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
  266. RELAY_COMMAND_CONNECTED, NULL, 0,
  267. conn->cpath_layer) < 0)
  268. return 0; /* circuit is closed, don't continue */
  269. } else {
  270. char connected_payload[8];
  271. set_uint32(connected_payload, htonl(conn->addr));
  272. set_uint32(connected_payload+4,
  273. htonl(MAX_DNS_ENTRY_AGE)); /* XXXX fill with a real TTL */
  274. if (connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
  275. RELAY_COMMAND_CONNECTED, connected_payload, 8, conn->cpath_layer) < 0)
  276. return 0; /* circuit is closed, don't continue */
  277. }
  278. tor_assert(conn->package_window > 0);
  279. /* in case the server has written anything */
  280. return connection_edge_process_inbuf(conn, 1);
  281. }
  282. /** Find all general-purpose AP streams waiting for a response that sent their
  283. * begin/resolve cell >=15 seconds ago. Detach from their current circuit, and
  284. * mark their current circuit as unsuitable for new streams. Then call
  285. * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
  286. * available) or launch a new one.
  287. *
  288. * For rendezvous streams, simply give up after 45 seconds (with no
  289. * retry attempt).
  290. */
  291. void
  292. connection_ap_expire_beginning(void)
  293. {
  294. connection_t **carray;
  295. connection_t *conn;
  296. circuit_t *circ;
  297. const char *nickname;
  298. int n, i;
  299. time_t now = time(NULL);
  300. or_options_t *options = get_options();
  301. get_connection_array(&carray, &n);
  302. for (i = 0; i < n; ++i) {
  303. conn = carray[i];
  304. if (conn->type != CONN_TYPE_AP)
  305. continue;
  306. if (conn->state == AP_CONN_STATE_CONTROLLER_WAIT) {
  307. if (now - conn->timestamp_lastread >= 120) {
  308. log_notice(LD_APP, "Closing unattached stream.");
  309. connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
  310. }
  311. continue;
  312. }
  313. else if (conn->state != AP_CONN_STATE_RESOLVE_WAIT &&
  314. conn->state != AP_CONN_STATE_CONNECT_WAIT)
  315. continue;
  316. if (now - conn->timestamp_lastread < 15)
  317. continue;
  318. circ = circuit_get_by_edge_conn(conn);
  319. if (!circ) { /* it's vanished? */
  320. log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
  321. safe_str(conn->socks_request->address));
  322. connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
  323. continue;
  324. }
  325. if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  326. if (now - conn->timestamp_lastread > 45) {
  327. log_notice(LD_REND,
  328. "Rend stream is %d seconds late. Giving up on address"
  329. " '%s.onion'.",
  330. (int)(now - conn->timestamp_lastread),
  331. safe_str(conn->socks_request->address));
  332. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT,
  333. conn->cpath_layer);
  334. connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
  335. }
  336. continue;
  337. }
  338. tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
  339. nickname = build_state_get_exit_nickname(circ->build_state);
  340. log_notice(LD_APP,
  341. "We tried for %d seconds to connect to '%s' using exit '%s'."
  342. " Retrying on a new circuit.",
  343. (int)(now - conn->timestamp_lastread),
  344. safe_str(conn->socks_request->address),
  345. nickname ? nickname : "*unnamed*");
  346. /* send an end down the circuit */
  347. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
  348. /* un-mark it as ending, since we're going to reuse it */
  349. conn->has_sent_end = 0;
  350. /* kludge to make us not try this circuit again, yet to allow
  351. * current streams on it to survive if they can: make it
  352. * unattractive to use for new streams */
  353. tor_assert(circ->timestamp_dirty);
  354. circ->timestamp_dirty -= options->MaxCircuitDirtiness;
  355. /* give our stream another 15 seconds to try */
  356. conn->timestamp_lastread += 15;
  357. /* move it back into 'pending' state, and try to attach. */
  358. if (connection_ap_detach_retriable(conn, circ)<0) {
  359. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  360. }
  361. } /* end for */
  362. }
  363. /** Tell any AP streams that are waiting for a new circuit that one is
  364. * available.
  365. */
  366. void
  367. connection_ap_attach_pending(void)
  368. {
  369. connection_t **carray;
  370. connection_t *conn;
  371. int n, i;
  372. get_connection_array(&carray, &n);
  373. for (i = 0; i < n; ++i) {
  374. conn = carray[i];
  375. if (conn->marked_for_close ||
  376. conn->type != CONN_TYPE_AP ||
  377. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  378. continue;
  379. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  380. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  381. }
  382. }
  383. }
  384. /** The AP connection <b>conn</b> has just failed while attaching or
  385. * sending a BEGIN or resolving on <b>circ</b>, but another circuit
  386. * might work. Detach the circuit, and either reattach it, launch a
  387. * new circuit, tell the controller, or give up as a appropriate.
  388. *
  389. * Returns -1 on err, 1 on success, 0 on not-yet-sure.
  390. */
  391. int
  392. connection_ap_detach_retriable(connection_t *conn, circuit_t *circ)
  393. {
  394. control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE);
  395. conn->timestamp_lastread = time(NULL);
  396. if (! get_options()->LeaveStreamsUnattached) {
  397. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  398. circuit_detach_stream(circ,conn);
  399. return connection_ap_handshake_attach_circuit(conn);
  400. } else {
  401. conn->state = AP_CONN_STATE_CONTROLLER_WAIT;
  402. circuit_detach_stream(circ,conn);
  403. return 0;
  404. }
  405. }
  406. /** A client-side struct to remember requests to rewrite addresses
  407. * to new addresses. These structs are stored in the hash table
  408. * "addressmap" below.
  409. *
  410. * There are 5 ways to set an address mapping:
  411. * - A MapAddress command from the controller [permanent]
  412. * - An AddressMap directive in the torrc [permanent]
  413. * - When a TrackHostExits torrc directive is triggered [temporary]
  414. * - When a dns resolve succeeds [temporary]
  415. * - When a dns resolve fails [temporary]
  416. *
  417. * When an addressmap request is made but one is already registered,
  418. * the new one is replaced only if the currently registered one has
  419. * no "new_address" (that is, it's in the process of dns resolve),
  420. * or if the new one is permanent (expires==0 or 1).
  421. *
  422. * (We overload the 'expires' field, using "0" for mappings set via
  423. * the configuration file, "1" for mappings set from the control
  424. * interface, and other values for DNS mappings that can expire.)
  425. */
  426. typedef struct {
  427. char *new_address;
  428. time_t expires;
  429. int num_resolve_failures;
  430. } addressmap_entry_t;
  431. /** Entry for mapping addresses to which virtual address we mapped them to. */
  432. typedef struct {
  433. char *ipv4_address;
  434. char *hostname_address;
  435. } virtaddress_entry_t;
  436. /** A hash table to store client-side address rewrite instructions. */
  437. static strmap_t *addressmap=NULL;
  438. /**
  439. * Table mapping addresses to which virtual address, if any, we
  440. * assigned them to.
  441. *
  442. * We maintain the following invariant: if [A,B] is in
  443. * virtaddress_reversemap, then B must be a virtual address, and [A,B]
  444. * must be in addressmap. We do not require that the converse hold:
  445. * if it fails, then we could end up mapping two virtual addresses to
  446. * the same address, which is no disaster.
  447. **/
  448. static strmap_t *virtaddress_reversemap=NULL;
  449. /** Initialize addressmap. */
  450. void
  451. addressmap_init(void)
  452. {
  453. addressmap = strmap_new();
  454. virtaddress_reversemap = strmap_new();
  455. }
  456. /** Free the memory associated with the addressmap entry <b>_ent</b>. */
  457. static void
  458. addressmap_ent_free(void *_ent)
  459. {
  460. addressmap_entry_t *ent = _ent;
  461. tor_free(ent->new_address);
  462. tor_free(ent);
  463. }
  464. /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b> */
  465. static void
  466. addressmap_virtaddress_ent_free(void *_ent)
  467. {
  468. virtaddress_entry_t *ent = _ent;
  469. tor_free(ent->ipv4_address);
  470. tor_free(ent->hostname_address);
  471. tor_free(ent);
  472. }
  473. /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b> */
  474. static void
  475. addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
  476. {
  477. if (ent && ent->new_address &&
  478. address_is_in_virtual_range(ent->new_address)) {
  479. virtaddress_entry_t *ve =
  480. strmap_get(virtaddress_reversemap, ent->new_address);
  481. /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
  482. if (ve) {
  483. if (!strcmp(address, ve->ipv4_address))
  484. tor_free(ve->ipv4_address);
  485. if (!strcmp(address, ve->hostname_address))
  486. tor_free(ve->hostname_address);
  487. if (!ve->ipv4_address && !ve->hostname_address) {
  488. tor_free(ve);
  489. strmap_remove(virtaddress_reversemap, ent->new_address);
  490. }
  491. }
  492. }
  493. }
  494. /* DOCDOC */
  495. static void
  496. addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
  497. {
  498. addressmap_virtaddress_remove(address, ent);
  499. addressmap_ent_free(ent);
  500. }
  501. /** Remove all entries from the addressmap that were set via the
  502. * configuration file or the command line. */
  503. void
  504. addressmap_clear_configured(void)
  505. {
  506. addressmap_get_mappings(NULL, 0, 0);
  507. }
  508. /** Remove all entries from the addressmap that are set to expire, ever. */
  509. void
  510. addressmap_clear_transient(void)
  511. {
  512. addressmap_get_mappings(NULL, 2, TIME_MAX);
  513. }
  514. /** Clean out entries from the addressmap cache that were
  515. * added long enough ago that they are no longer valid.
  516. */
  517. void
  518. addressmap_clean(time_t now)
  519. {
  520. addressmap_get_mappings(NULL, 2, now);
  521. }
  522. /** Free all the elements in the addressmap, and free the addressmap
  523. * itself. */
  524. void
  525. addressmap_free_all(void)
  526. {
  527. if (addressmap) {
  528. strmap_free(addressmap, addressmap_ent_free);
  529. addressmap = NULL;
  530. }
  531. if (virtaddress_reversemap) {
  532. strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
  533. virtaddress_reversemap = NULL;
  534. }
  535. }
  536. /** Look at address, and rewrite it until it doesn't want any
  537. * more rewrites; but don't get into an infinite loop.
  538. * Don't write more than maxlen chars into address.
  539. */
  540. void
  541. addressmap_rewrite(char *address, size_t maxlen)
  542. {
  543. addressmap_entry_t *ent;
  544. int rewrites;
  545. for (rewrites = 0; rewrites < 16; rewrites++) {
  546. ent = strmap_get(addressmap, address);
  547. if (!ent || !ent->new_address)
  548. return; /* done, no rewrite needed */
  549. log_info(LD_APP, "Addressmap: rewriting '%s' to '%s'",
  550. safe_str(address), safe_str(ent->new_address));
  551. strlcpy(address, ent->new_address, maxlen);
  552. }
  553. log_warn(LD_CONFIG,
  554. "Loop detected: we've rewritten '%s' 16 times! Using it as-is.",
  555. safe_str(address));
  556. /* it's fine to rewrite a rewrite, but don't loop forever */
  557. }
  558. /** Return 1 if <b>address</b> is already registered, else return 0 */
  559. int
  560. addressmap_already_mapped(const char *address)
  561. {
  562. return strmap_get(addressmap, address) ? 1 : 0;
  563. }
  564. /** Register a request to map <b>address</b> to <b>new_address</b>,
  565. * which will expire on <b>expires</b> (or 0 if never expires from
  566. * config file, 1 if never expires from controller, 2 if never expires
  567. * (virtual address mapping) from the controller.)
  568. *
  569. * <b>new_address</b> should be a newly dup'ed string, which we'll use or
  570. * free as appropriate. We will leave address alone.
  571. *
  572. * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
  573. * any mappings that exist from <b>address</b>.
  574. */
  575. void
  576. addressmap_register(const char *address, char *new_address, time_t expires)
  577. {
  578. addressmap_entry_t *ent;
  579. ent = strmap_get(addressmap, address);
  580. if (!new_address || !strcasecmp(address,new_address)) {
  581. /* Remove the mapping, if any. */
  582. tor_free(new_address);
  583. if (ent) {
  584. addressmap_ent_remove(address,ent);
  585. strmap_remove(addressmap, address);
  586. }
  587. return;
  588. }
  589. if (!ent) { /* make a new one and register it */
  590. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  591. strmap_set(addressmap, address, ent);
  592. } else if (ent->new_address) { /* we need to clean up the old mapping. */
  593. if (expires > 1) {
  594. log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
  595. "since it's already mapped to '%s'",
  596. safe_str(address), safe_str(new_address), safe_str(ent->new_address));
  597. tor_free(new_address);
  598. return;
  599. }
  600. if (address_is_in_virtual_range(ent->new_address) &&
  601. expires != 2) {
  602. /* XXX This isn't the perfect test; we want to avoid removing
  603. * mappings set from the control interface _as virtual mapping */
  604. addressmap_virtaddress_remove(address, ent);
  605. }
  606. tor_free(ent->new_address);
  607. } /* else { we have an in-progress resolve with no mapping. } */
  608. ent->new_address = new_address;
  609. ent->expires = expires==2 ? 1 : expires;
  610. ent->num_resolve_failures = 0;
  611. log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
  612. safe_str(address), safe_str(ent->new_address));
  613. control_event_address_mapped(address, ent->new_address, expires);
  614. }
  615. /** An attempt to resolve <b>address</b> failed at some OR.
  616. * Increment the number of resolve failures we have on record
  617. * for it, and then return that number.
  618. */
  619. int
  620. client_dns_incr_failures(const char *address)
  621. {
  622. addressmap_entry_t *ent = strmap_get(addressmap, address);
  623. if (!ent) {
  624. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  625. ent->expires = time(NULL)+MAX_DNS_ENTRY_AGE;
  626. strmap_set(addressmap,address,ent);
  627. }
  628. ++ent->num_resolve_failures;
  629. log_info(LD_APP, "Address %s now has %d resolve failures.",
  630. safe_str(address), ent->num_resolve_failures);
  631. return ent->num_resolve_failures;
  632. }
  633. /** If <b>address</b> is in the client dns addressmap, reset
  634. * the number of resolve failures we have on record for it.
  635. * This is used when we fail a stream because it won't resolve:
  636. * otherwise future attempts on that address will only try once.
  637. */
  638. void
  639. client_dns_clear_failures(const char *address)
  640. {
  641. addressmap_entry_t *ent = strmap_get(addressmap, address);
  642. if (ent)
  643. ent->num_resolve_failures = 0;
  644. }
  645. /** Record the fact that <b>address</b> resolved to <b>val</b>.
  646. * We can now use this in subsequent streams via addressmap_rewrite()
  647. * so we can more correctly choose an exit that will allow <b>address</b>.
  648. *
  649. * If <b>exitname</b> is defined, then append the addresses with
  650. * ".exitname.exit" before registering the mapping.
  651. *
  652. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  653. * <b>ttl</b>seconds.
  654. */
  655. void
  656. client_dns_set_addressmap(const char *address, uint32_t val,
  657. const char *exitname,
  658. int ttl)
  659. {
  660. struct in_addr in;
  661. char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_HEX_NICKNAME_LEN+10];
  662. char valbuf[INET_NTOA_BUF_LEN];
  663. char extendedval[INET_NTOA_BUF_LEN+MAX_HEX_NICKNAME_LEN+10];
  664. tor_assert(address); tor_assert(val);
  665. if (ttl<0 || ttl>MAX_DNS_ENTRY_AGE)
  666. ttl = MAX_DNS_ENTRY_AGE;
  667. if (tor_inet_aton(address, &in))
  668. return; /* If address was an IP address already, don't add a mapping. */
  669. in.s_addr = htonl(val);
  670. tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
  671. if (exitname) {
  672. tor_snprintf(extendedaddress, sizeof(extendedaddress),
  673. "%s.%s.exit", address, exitname);
  674. tor_snprintf(extendedval, sizeof(extendedval),
  675. "%s.%s.exit", valbuf, exitname);
  676. } else {
  677. tor_snprintf(extendedaddress, sizeof(extendedaddress),
  678. "%s", address);
  679. tor_snprintf(extendedval, sizeof(extendedval),
  680. "%s", valbuf);
  681. }
  682. addressmap_register(extendedaddress, tor_strdup(extendedval),
  683. time(NULL) + ttl);
  684. }
  685. /* Currently, we hand out 127.192.0.1 through 127.254.254.254.
  686. * These addresses should map to localhost, so even if the
  687. * application accidentally tried to connect to them directly (not
  688. * via Tor), it wouldn't get too far astray.
  689. *
  690. * Eventually, we should probably make this configurable.
  691. */
  692. #define MIN_UNUSED_IPV4 0x7fc00001u
  693. #define MAX_UNUSED_IPV4 0x7ffefefeu
  694. /**
  695. * Return true iff <b>addr</b> is likely to have been returned by
  696. * client_dns_get_unused_address.
  697. **/
  698. int
  699. address_is_in_virtual_range(const char *address)
  700. {
  701. struct in_addr in;
  702. tor_assert(address);
  703. if (!strcasecmpend(address, ".virtual")) {
  704. return 1;
  705. } else if (tor_inet_aton(address, &in)) {
  706. uint32_t addr = ntohl(in.s_addr);
  707. if (addr >= MIN_UNUSED_IPV4 && addr <= MAX_UNUSED_IPV4)
  708. return 1;
  709. }
  710. return 0;
  711. }
  712. /** Return a newly allocated string holding an address of <b>type</b>
  713. * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
  714. * and that is very unlikely to be the address of any real host.
  715. */
  716. static char *
  717. addressmap_get_virtual_address(int type)
  718. {
  719. char buf[64];
  720. static uint32_t next_ipv4 = MIN_UNUSED_IPV4;
  721. struct in_addr in;
  722. if (type == RESOLVED_TYPE_HOSTNAME) {
  723. char rand[10];
  724. do {
  725. crypto_rand(rand, sizeof(rand));
  726. base32_encode(buf,sizeof(buf),rand,sizeof(rand));
  727. strlcat(buf, ".virtual", sizeof(buf));
  728. } while (strmap_get(addressmap, buf));
  729. return tor_strdup(buf);
  730. } else if (type == RESOLVED_TYPE_IPV4) {
  731. while (1) {
  732. /* Don't hand out any .0 or .255 address. */
  733. while ((next_ipv4 & 0xff) == 0 ||
  734. (next_ipv4 & 0xff) == 0xff)
  735. ++next_ipv4;
  736. in.s_addr = htonl(next_ipv4);
  737. tor_inet_ntoa(&in, buf, sizeof(buf));
  738. if (!strmap_get(addressmap, buf))
  739. break;
  740. ++next_ipv4;
  741. if (next_ipv4 > MAX_UNUSED_IPV4)
  742. next_ipv4 = MIN_UNUSED_IPV4;
  743. }
  744. return tor_strdup(buf);
  745. } else {
  746. log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
  747. return NULL;
  748. }
  749. }
  750. /** A controller has requested that we map some address of type
  751. * <b>type</b> to the address <b>new_address</b>. Choose an address
  752. * that is unlikely to be used, and map it, and return it in a newly
  753. * allocated string. If another address of the same type is already
  754. * mapped to <b>new_address</b>, try to return a copy of that address.
  755. *
  756. * The string in <b>new_address</b> may be freed, or inserted into a map
  757. * as appropriate.
  758. **/
  759. const char *
  760. addressmap_register_virtual_address(int type, char *new_address)
  761. {
  762. char **addrp;
  763. virtaddress_entry_t *vent;
  764. tor_assert(new_address);
  765. tor_assert(addressmap);
  766. tor_assert(virtaddress_reversemap);
  767. vent = strmap_get(virtaddress_reversemap, new_address);
  768. if (!vent) {
  769. vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
  770. strmap_set(virtaddress_reversemap, new_address, vent);
  771. }
  772. addrp = (type == RESOLVED_TYPE_IPV4) ?
  773. &vent->ipv4_address : &vent->hostname_address;
  774. if (*addrp) {
  775. addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
  776. if (ent && ent->new_address &&
  777. !strcasecmp(new_address, ent->new_address)) {
  778. tor_free(new_address);
  779. return tor_strdup(*addrp);
  780. } else
  781. log_warn(LD_BUG,
  782. "Internal confusion: I thought that '%s' was mapped to by "
  783. "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
  784. safe_str(new_address), safe_str(*addrp), safe_str(*addrp),
  785. ent?safe_str(ent->new_address):"(nothing)");
  786. }
  787. tor_free(*addrp);
  788. *addrp = addressmap_get_virtual_address(type);
  789. addressmap_register(*addrp, new_address, 2);
  790. #if 0
  791. {
  792. /* Try to catch possible bugs */
  793. addressmap_entry_t *ent;
  794. ent = strmap_get(addressmap, *addrp);
  795. tor_assert(ent);
  796. tor_assert(!strcasecmp(ent->new_address,new_address));
  797. vent = strmap_get(virtaddress_reversemap, new_address);
  798. tor_assert(vent);
  799. tor_assert(!strcasecmp(*addrp,
  800. (type == RESOLVED_TYPE_IPV4) ?
  801. vent->ipv4_address : vent->hostname_address));
  802. log_fn(LOG_INFO, "Map from %s to %s okay.",
  803. safe_str(*addrp),safe_str(new_address));
  804. }
  805. #endif
  806. return *addrp;
  807. }
  808. /** Return 1 if <b>address</b> has funny characters in it like
  809. * colons. Return 0 if it's fine.
  810. */
  811. static int
  812. address_is_invalid_destination(const char *address)
  813. {
  814. /* FFFF should flesh this out */
  815. if (strchr(address,':'))
  816. return 1;
  817. return 0;
  818. }
  819. /** Iterate over all address mapings which have expiry times between
  820. * min_expires and max_expires, inclusive. If sl is provided, add an
  821. * "old-addr new-addr" string to sl for each mapping. If sl is NULL,
  822. * remove the mappings.
  823. */
  824. void
  825. addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
  826. time_t max_expires)
  827. {
  828. strmap_iter_t *iter;
  829. const char *key;
  830. void *_val;
  831. addressmap_entry_t *val;
  832. if (!addressmap)
  833. addressmap_init();
  834. for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
  835. strmap_iter_get(iter, &key, &_val);
  836. val = _val;
  837. if (val->expires >= min_expires && val->expires <= max_expires) {
  838. if (!sl) {
  839. iter = strmap_iter_next_rmv(addressmap,iter);
  840. addressmap_ent_remove(key, val);
  841. continue;
  842. } else if (val->new_address) {
  843. size_t len = strlen(key)+strlen(val->new_address)+2;
  844. char *line = tor_malloc(len);
  845. tor_snprintf(line, len, "%s %s", key, val->new_address);
  846. smartlist_add(sl, line);
  847. }
  848. }
  849. iter = strmap_iter_next(addressmap,iter);
  850. }
  851. }
  852. /* Connection <b>conn</b> just finished its socks handshake, or the
  853. * controller asked us to take care of it. If <b>circ</b> is defined,
  854. * then that's where we'll want to attach it. Otherwise we have to
  855. * figure it out ourselves.
  856. *
  857. * First, parse whether it's a .exit address, remap it, and so on. Then
  858. * it's for a general circuit, try to attach it to a circuit (or launch
  859. * one as needed), else if it's for a rendezvous circuit, fetch a
  860. * rendezvous descriptor first (or attach/launch a circuit if the
  861. * rendezvous descriptor is already here and fresh enough).
  862. */
  863. int
  864. connection_ap_handshake_rewrite_and_attach(connection_t *conn,
  865. circuit_t *circ)
  866. {
  867. socks_request_t *socks = conn->socks_request;
  868. hostname_type_t addresstype;
  869. tor_strlower(socks->address); /* normalize it */
  870. log_debug(LD_APP,"Client asked for %s:%d",
  871. safe_str(socks->address),
  872. socks->port);
  873. /* For address map controls, remap the address */
  874. addressmap_rewrite(socks->address, sizeof(socks->address));
  875. if (address_is_in_virtual_range(socks->address)) {
  876. /* This address was probably handed out by client_dns_get_unmapped_address,
  877. * but the mapping was discarded for some reason. We *don't* want to send
  878. * the address through Tor; that's likely to fail, and may leak
  879. * information.
  880. */
  881. log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
  882. socks->address); /* don't safe_str() this yet. */
  883. connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
  884. return -1;
  885. }
  886. /* Parse the address provided by SOCKS. Modify it in-place if it
  887. * specifies a hidden-service (.onion) or particular exit node (.exit).
  888. */
  889. addresstype = parse_extended_hostname(socks->address);
  890. if (addresstype == BAD_HOSTNAME) {
  891. log_warn(LD_APP, "Invalid hostname %s; rejecting", socks->address);
  892. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  893. return -1;
  894. }
  895. if (addresstype == EXIT_HOSTNAME) {
  896. /* foo.exit -- modify conn->chosen_exit_node to specify the exit
  897. * node, and conn->address to hold only the address portion.*/
  898. char *s = strrchr(socks->address,'.');
  899. if (s) {
  900. if (s[1] != '\0') {
  901. conn->chosen_exit_name = tor_strdup(s+1);
  902. *s = 0;
  903. } else {
  904. log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
  905. safe_str(socks->address));
  906. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  907. return -1;
  908. }
  909. } else {
  910. struct in_addr in;
  911. routerinfo_t *r;
  912. conn->chosen_exit_name = tor_strdup(socks->address);
  913. r = router_get_by_nickname(conn->chosen_exit_name, 1);
  914. *socks->address = 0;
  915. if (r) {
  916. /* XXXX Should this use server->address instead? */
  917. in.s_addr = htonl(r->addr);
  918. strlcpy(socks->address, inet_ntoa(in), sizeof(socks->address));
  919. } else {
  920. log_warn(LD_APP,
  921. "Unrecognized server in exit address '%s.exit'. Refusing.",
  922. safe_str(socks->address));
  923. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  924. return -1;
  925. }
  926. }
  927. }
  928. if (addresstype != ONION_HOSTNAME) {
  929. /* not a hidden-service request (i.e. normal or .exit) */
  930. if (address_is_invalid_destination(socks->address)) {
  931. log_warn(LD_APP,
  932. "Destination '%s' seems to be an invalid hostname. Failing.",
  933. safe_str(socks->address));
  934. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  935. return -1;
  936. }
  937. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  938. uint32_t answer;
  939. struct in_addr in;
  940. /* Reply to resolves immediately if we can. */
  941. if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
  942. log_warn(LD_APP,"Address to be resolved is too large. Failing.");
  943. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
  944. 0,NULL,-1);
  945. connection_mark_unattached_ap(conn,
  946. END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  947. return -1;
  948. }
  949. if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
  950. answer = in.s_addr; /* leave it in network order */
  951. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
  952. (char*)&answer,-1);
  953. connection_mark_unattached_ap(conn,
  954. END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  955. return 0;
  956. }
  957. rep_hist_note_used_resolve(time(NULL)); /* help predict this next time */
  958. } else { /* socks->command == SOCKS_COMMAND_CONNECT */
  959. if (socks->port == 0) {
  960. log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
  961. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  962. return -1;
  963. }
  964. if (!conn->chosen_exit_name && !circ) {
  965. /* see if we can find a suitable enclave exit */
  966. routerinfo_t *r =
  967. router_find_exact_exit_enclave(socks->address, socks->port);
  968. if (r) {
  969. log_info(LD_APP,
  970. "Redirecting address %s to exit at enclave router %s",
  971. safe_str(socks->address), r->nickname);
  972. /* use the hex digest, not nickname, in case there are two
  973. routers with this nickname */
  974. conn->chosen_exit_name =
  975. tor_strdup(hex_str(r->cache_info.identity_digest, DIGEST_LEN));
  976. }
  977. }
  978. /* help predict this next time */
  979. rep_hist_note_used_port(socks->port, time(NULL));
  980. }
  981. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  982. if ((circ &&
  983. connection_ap_handshake_attach_chosen_circuit(conn, circ) < 0) ||
  984. (!circ &&
  985. connection_ap_handshake_attach_circuit(conn) < 0)) {
  986. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  987. return -1;
  988. }
  989. return 0;
  990. } else {
  991. /* it's a hidden-service request */
  992. rend_cache_entry_t *entry;
  993. int r;
  994. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  995. /* if it's a resolve request, fail it right now, rather than
  996. * building all the circuits and then realizing it won't work. */
  997. log_warn(LD_APP,
  998. "Resolve requests to hidden services not allowed. Failing.");
  999. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
  1000. 0,NULL,-1);
  1001. connection_mark_unattached_ap(conn,
  1002. END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  1003. return -1;
  1004. }
  1005. if (circ) {
  1006. log_warn(LD_CONTROL, "Attachstream to a circuit is not "
  1007. "supported for .onion addresses currently. Failing.");
  1008. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1009. return -1;
  1010. }
  1011. strlcpy(conn->rend_query, socks->address, sizeof(conn->rend_query));
  1012. log_info(LD_REND,"Got a hidden service request for ID '%s'",
  1013. safe_str(conn->rend_query));
  1014. /* see if we already have it cached */
  1015. r = rend_cache_lookup_entry(conn->rend_query, -1, &entry);
  1016. if (r<0) {
  1017. log_warn(LD_BUG,"Bug: Invalid service name '%s'",
  1018. safe_str(conn->rend_query));
  1019. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1020. return -1;
  1021. }
  1022. if (r==0) {
  1023. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  1024. log_info(LD_REND, "Unknown descriptor %s. Fetching.",
  1025. safe_str(conn->rend_query));
  1026. rend_client_refetch_renddesc(conn->rend_query);
  1027. } else { /* r > 0 */
  1028. #define NUM_SECONDS_BEFORE_REFETCH (60*15)
  1029. if (time(NULL) - entry->received < NUM_SECONDS_BEFORE_REFETCH) {
  1030. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1031. log_info(LD_REND, "Descriptor is here and fresh enough. Great.");
  1032. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  1033. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1034. return -1;
  1035. }
  1036. } else {
  1037. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  1038. log_info(LD_REND, "Stale descriptor %s. Refetching.",
  1039. safe_str(conn->rend_query));
  1040. rend_client_refetch_renddesc(conn->rend_query);
  1041. }
  1042. }
  1043. return 0;
  1044. }
  1045. return 0; /* unreached but keeps the compiler happy */
  1046. }
  1047. /** connection_edge_process_inbuf() found a conn in state
  1048. * socks_wait. See if conn->inbuf has the right bytes to proceed with
  1049. * the socks handshake.
  1050. *
  1051. * If the handshake is complete, send it to
  1052. * connection_ap_handshake_rewrite_and_attach().
  1053. *
  1054. * Return -1 if an unexpected error with conn (and it should be marked
  1055. * for close), else return 0.
  1056. */
  1057. static int
  1058. connection_ap_handshake_process_socks(connection_t *conn)
  1059. {
  1060. socks_request_t *socks;
  1061. int sockshere;
  1062. or_options_t *options = get_options();
  1063. tor_assert(conn);
  1064. tor_assert(conn->type == CONN_TYPE_AP);
  1065. tor_assert(conn->state == AP_CONN_STATE_SOCKS_WAIT);
  1066. tor_assert(conn->socks_request);
  1067. socks = conn->socks_request;
  1068. log_debug(LD_APP,"entered.");
  1069. sockshere = fetch_from_buf_socks(conn->inbuf, socks, options->TestSocks);
  1070. if (sockshere == 0) {
  1071. if (socks->replylen) {
  1072. connection_write_to_buf(socks->reply, socks->replylen, conn);
  1073. /* zero it out so we can do another round of negotiation */
  1074. socks->replylen = 0;
  1075. } else {
  1076. log_debug(LD_APP,"socks handshake not all here yet.");
  1077. }
  1078. return 0;
  1079. } else if (sockshere == -1) {
  1080. if (socks->replylen) { /* we should send reply back */
  1081. log_debug(LD_APP,"reply is already set for us. Using it.");
  1082. connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
  1083. SOCKS5_GENERAL_ERROR);
  1084. } else {
  1085. log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
  1086. connection_ap_handshake_socks_reply(conn, NULL, 0, SOCKS5_GENERAL_ERROR);
  1087. }
  1088. connection_mark_unattached_ap(conn,
  1089. END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  1090. return -1;
  1091. } /* else socks handshake is done, continue processing */
  1092. if (socks->command == SOCKS_COMMAND_CONNECT)
  1093. control_event_stream_status(conn, STREAM_EVENT_NEW);
  1094. else
  1095. control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE);
  1096. if (options->LeaveStreamsUnattached) {
  1097. conn->state = AP_CONN_STATE_CONTROLLER_WAIT;
  1098. return 0;
  1099. }
  1100. return connection_ap_handshake_rewrite_and_attach(conn, NULL);
  1101. }
  1102. /** Iterate over the two bytes of stream_id until we get one that is not
  1103. * already in use; return it. Return 0 if can't get a unique stream_id.
  1104. */
  1105. static uint16_t
  1106. get_unique_stream_id_by_circ(circuit_t *circ)
  1107. {
  1108. connection_t *tmpconn;
  1109. uint16_t test_stream_id;
  1110. uint32_t attempts=0;
  1111. again:
  1112. test_stream_id = circ->next_stream_id++;
  1113. if (++attempts > 1<<16) {
  1114. /* Make sure we don't loop forever if all stream_id's are used. */
  1115. log_warn(LD_APP,"No unused stream IDs. Failing.");
  1116. return 0;
  1117. }
  1118. if (test_stream_id == 0)
  1119. goto again;
  1120. for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  1121. if (tmpconn->stream_id == test_stream_id)
  1122. goto again;
  1123. return test_stream_id;
  1124. }
  1125. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  1126. * socks_request field, and send it down circ.
  1127. *
  1128. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  1129. */
  1130. int
  1131. connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ)
  1132. {
  1133. char payload[CELL_PAYLOAD_SIZE];
  1134. int payload_len;
  1135. tor_assert(ap_conn->type == CONN_TYPE_AP);
  1136. tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1137. tor_assert(ap_conn->socks_request);
  1138. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  1139. if (ap_conn->stream_id==0) {
  1140. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1141. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  1142. return -1;
  1143. }
  1144. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
  1145. (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
  1146. ap_conn->socks_request->address : "",
  1147. ap_conn->socks_request->port);
  1148. payload_len = strlen(payload)+1;
  1149. log_debug(LD_APP,
  1150. "Sending relay cell to begin stream %d.", ap_conn->stream_id);
  1151. if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_BEGIN,
  1152. payload, payload_len,
  1153. ap_conn->cpath_layer) < 0)
  1154. return -1; /* circuit is closed, don't continue */
  1155. ap_conn->package_window = STREAMWINDOW_START;
  1156. ap_conn->deliver_window = STREAMWINDOW_START;
  1157. ap_conn->state = AP_CONN_STATE_CONNECT_WAIT;
  1158. log_info(LD_APP,"Address/port sent, ap socket %d, n_circ_id %d",
  1159. ap_conn->s, circ->n_circ_id);
  1160. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT);
  1161. return 0;
  1162. }
  1163. /** Write a relay resolve cell, using destaddr and destport from ap_conn's
  1164. * socks_request field, and send it down circ.
  1165. *
  1166. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  1167. */
  1168. int
  1169. connection_ap_handshake_send_resolve(connection_t *ap_conn, circuit_t *circ)
  1170. {
  1171. int payload_len;
  1172. const char *string_addr;
  1173. tor_assert(ap_conn->type == CONN_TYPE_AP);
  1174. tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1175. tor_assert(ap_conn->socks_request);
  1176. tor_assert(ap_conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
  1177. tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
  1178. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  1179. if (ap_conn->stream_id==0) {
  1180. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1181. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  1182. return -1;
  1183. }
  1184. string_addr = ap_conn->socks_request->address;
  1185. payload_len = strlen(string_addr)+1;
  1186. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  1187. log_debug(LD_APP,
  1188. "Sending relay cell to begin stream %d.", ap_conn->stream_id);
  1189. if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_RESOLVE,
  1190. string_addr, payload_len, ap_conn->cpath_layer) < 0)
  1191. return -1; /* circuit is closed, don't continue */
  1192. ap_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
  1193. log_info(LD_APP,"Address sent for resolve, ap socket %d, n_circ_id %d",
  1194. ap_conn->s, circ->n_circ_id);
  1195. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE);
  1196. return 0;
  1197. }
  1198. /** Make an AP connection_t, do a socketpair and attach one side
  1199. * to the conn, connection_add it, initialize it to circuit_wait,
  1200. * and call connection_ap_handshake_attach_circuit(conn) on it.
  1201. *
  1202. * Return the other end of the socketpair, or -1 if error.
  1203. */
  1204. int
  1205. connection_ap_make_bridge(char *address, uint16_t port)
  1206. {
  1207. int fd[2];
  1208. connection_t *conn;
  1209. int err;
  1210. log_info(LD_APP,"Making AP bridge to %s:%d ...",safe_str(address),port);
  1211. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) < 0) {
  1212. log_warn(LD_NET,
  1213. "Couldn't construct socketpair (%s). Network down? Delaying.",
  1214. tor_socket_strerror(-err));
  1215. return -1;
  1216. }
  1217. set_socket_nonblocking(fd[0]);
  1218. set_socket_nonblocking(fd[1]);
  1219. conn = connection_new(CONN_TYPE_AP);
  1220. conn->s = fd[0];
  1221. /* populate conn->socks_request */
  1222. /* leave version at zero, so the socks_reply is empty */
  1223. conn->socks_request->socks_version = 0;
  1224. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  1225. strlcpy(conn->socks_request->address, address,
  1226. sizeof(conn->socks_request->address));
  1227. conn->socks_request->port = port;
  1228. conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  1229. conn->address = tor_strdup("(local bridge)");
  1230. conn->addr = 0;
  1231. conn->port = 0;
  1232. if (connection_add(conn) < 0) { /* no space, forget it */
  1233. connection_free(conn); /* this closes fd[0] */
  1234. tor_close_socket(fd[1]);
  1235. return -1;
  1236. }
  1237. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1238. connection_start_reading(conn);
  1239. /* attaching to a dirty circuit is fine */
  1240. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  1241. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1242. tor_close_socket(fd[1]);
  1243. return -1;
  1244. }
  1245. log_info(LD_APP,"... AP bridge created and connected.");
  1246. return fd[1];
  1247. }
  1248. /** Send an answer to an AP connection that has requested a DNS lookup
  1249. * via SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6) or
  1250. * -1 for unreachable; the answer should be in the format specified
  1251. * in the socks extensions document.
  1252. **/
  1253. void
  1254. connection_ap_handshake_socks_resolved(connection_t *conn,
  1255. int answer_type,
  1256. size_t answer_len,
  1257. const char *answer,
  1258. int ttl)
  1259. {
  1260. char buf[256];
  1261. size_t replylen;
  1262. if (answer_type == RESOLVED_TYPE_IPV4) {
  1263. uint32_t a = ntohl(get_uint32(answer));
  1264. if (a)
  1265. client_dns_set_addressmap(conn->socks_request->address, a,
  1266. conn->chosen_exit_name, ttl);
  1267. }
  1268. if (conn->socks_request->socks_version == 4) {
  1269. buf[0] = 0x00; /* version */
  1270. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  1271. buf[1] = 90; /* "Granted" */
  1272. set_uint16(buf+2, 0);
  1273. memcpy(buf+4, answer, 4); /* address */
  1274. replylen = SOCKS4_NETWORK_LEN;
  1275. } else {
  1276. buf[1] = 91; /* "error" */
  1277. memset(buf+2, 0, 6);
  1278. replylen = SOCKS4_NETWORK_LEN;
  1279. }
  1280. } else {
  1281. /* SOCKS5 */
  1282. buf[0] = 0x05; /* version */
  1283. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  1284. buf[1] = SOCKS5_SUCCEEDED;
  1285. buf[2] = 0; /* reserved */
  1286. buf[3] = 0x01; /* IPv4 address type */
  1287. memcpy(buf+4, answer, 4); /* address */
  1288. set_uint16(buf+8, 0); /* port == 0. */
  1289. replylen = 10;
  1290. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  1291. buf[1] = SOCKS5_SUCCEEDED;
  1292. buf[2] = 0; /* reserved */
  1293. buf[3] = 0x04; /* IPv6 address type */
  1294. memcpy(buf+4, answer, 16); /* address */
  1295. set_uint16(buf+20, 0); /* port == 0. */
  1296. replylen = 22;
  1297. } else {
  1298. buf[1] = SOCKS5_HOST_UNREACHABLE;
  1299. memset(buf+2, 0, 8);
  1300. replylen = 10;
  1301. }
  1302. }
  1303. connection_ap_handshake_socks_reply(conn, buf, replylen,
  1304. (answer_type == RESOLVED_TYPE_IPV4 ||
  1305. answer_type == RESOLVED_TYPE_IPV6) ?
  1306. SOCKS5_SUCCEEDED : SOCKS5_HOST_UNREACHABLE);
  1307. }
  1308. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  1309. * socks version, etc, and mark <b>conn</b> as completed with SOCKS
  1310. * handshaking.
  1311. *
  1312. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it
  1313. * to conn and return, else reply based on <b>status</b>.
  1314. *
  1315. * If <b>reply</b> is undefined, <b>status</b> can't be 0.
  1316. */
  1317. void
  1318. connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
  1319. size_t replylen,
  1320. socks5_reply_status_t status) {
  1321. char buf[256];
  1322. tor_assert(conn->socks_request); /* make sure it's an AP stream */
  1323. control_event_stream_status(conn,
  1324. status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED);
  1325. if (conn->socks_request->has_finished) {
  1326. log_warn(LD_BUG, "Harmless bug: duplicate calls to "
  1327. "connection_ap_handshake_socks_reply.");
  1328. return;
  1329. }
  1330. if (replylen) { /* we already have a reply in mind */
  1331. connection_write_to_buf(reply, replylen, conn);
  1332. conn->socks_request->has_finished = 1;
  1333. return;
  1334. }
  1335. if (conn->socks_request->socks_version == 4) {
  1336. memset(buf,0,SOCKS4_NETWORK_LEN);
  1337. #define SOCKS4_GRANTED 90
  1338. #define SOCKS4_REJECT 91
  1339. buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
  1340. /* leave version, destport, destip zero */
  1341. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, conn);
  1342. } else if (conn->socks_request->socks_version == 5) {
  1343. buf[0] = 5; /* version 5 */
  1344. buf[1] = (char)status;
  1345. buf[2] = 0;
  1346. buf[3] = 1; /* ipv4 addr */
  1347. memset(buf+4,0,6); /* Set external addr/port to 0.
  1348. The spec doesn't seem to say what to do here. -RD */
  1349. connection_write_to_buf(buf,10,conn);
  1350. }
  1351. /* If socks_version isn't 4 or 5, don't send anything.
  1352. * This can happen in the case of AP bridges. */
  1353. conn->socks_request->has_finished = 1;
  1354. return;
  1355. }
  1356. /** A relay 'begin' cell has arrived, and either we are an exit hop
  1357. * for the circuit, or we are the origin and it is a rendezvous begin.
  1358. *
  1359. * Launch a new exit connection and initialize things appropriately.
  1360. *
  1361. * If it's a rendezvous stream, call connection_exit_connect() on
  1362. * it.
  1363. *
  1364. * For general streams, call dns_resolve() on it first, and only call
  1365. * connection_exit_connect() if the dns answer is already known.
  1366. *
  1367. * Note that we don't call connection_add() on the new stream! We wait
  1368. * for connection_exit_connect() to do that.
  1369. *
  1370. * Return -1 if we want to tear down <b>circ</b>. Else return 0.
  1371. */
  1372. int
  1373. connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
  1374. {
  1375. connection_t *n_stream;
  1376. relay_header_t rh;
  1377. char *address=NULL;
  1378. uint16_t port;
  1379. assert_circuit_ok(circ);
  1380. relay_header_unpack(&rh, cell->payload);
  1381. /* XXX currently we don't send an end cell back if we drop the
  1382. * begin because it's malformed.
  1383. */
  1384. if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
  1385. log_warn(LD_PROTOCOL,"relay begin cell has no \\0. Dropping.");
  1386. return 0;
  1387. }
  1388. if (parse_addr_port(cell->payload+RELAY_HEADER_SIZE,&address,NULL,&port)<0) {
  1389. log_warn(LD_PROTOCOL,"Unable to parse addr:port in relay begin cell. "
  1390. "Dropping.");
  1391. return 0;
  1392. }
  1393. if (port==0) {
  1394. log_warn(LD_PROTOCOL,"Missing port in relay begin cell. Dropping.");
  1395. tor_free(address);
  1396. return 0;
  1397. }
  1398. if (!tor_strisprint(address)) {
  1399. log_warn(LD_PROTOCOL,"Non-printing characters in address %s in relay "
  1400. "begin cell. Dropping.", escaped(address));
  1401. tor_free(address);
  1402. return 0;
  1403. }
  1404. log_debug(LD_EXIT,"Creating new exit connection.");
  1405. n_stream = connection_new(CONN_TYPE_EXIT);
  1406. n_stream->purpose = EXIT_PURPOSE_CONNECT;
  1407. n_stream->stream_id = rh.stream_id;
  1408. n_stream->port = port;
  1409. /* leave n_stream->s at -1, because it's not yet valid */
  1410. n_stream->package_window = STREAMWINDOW_START;
  1411. n_stream->deliver_window = STREAMWINDOW_START;
  1412. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  1413. log_debug(LD_REND,"begin is for rendezvous. configuring stream.");
  1414. n_stream->address = tor_strdup("(rendezvous)");
  1415. n_stream->state = EXIT_CONN_STATE_CONNECTING;
  1416. strlcpy(n_stream->rend_query, circ->rend_query,
  1417. sizeof(n_stream->rend_query));
  1418. tor_assert(connection_edge_is_rendezvous_stream(n_stream));
  1419. assert_circuit_ok(circ);
  1420. if (rend_service_set_connection_addr_port(n_stream, circ) < 0) {
  1421. log_info(LD_REND,"Didn't find rendezvous service (port %d)",
  1422. n_stream->port);
  1423. connection_edge_end(n_stream, END_STREAM_REASON_EXITPOLICY,
  1424. n_stream->cpath_layer);
  1425. connection_free(n_stream);
  1426. /* knock the whole thing down, somebody screwed up */
  1427. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  1428. tor_free(address);
  1429. return 0;
  1430. }
  1431. assert_circuit_ok(circ);
  1432. log_debug(LD_REND,"Finished assigning addr/port");
  1433. n_stream->cpath_layer = circ->cpath->prev; /* link it */
  1434. /* add it into the linked list of n_streams on this circuit */
  1435. n_stream->next_stream = circ->n_streams;
  1436. n_stream->on_circuit = circ;
  1437. circ->n_streams = n_stream;
  1438. assert_circuit_ok(circ);
  1439. connection_exit_connect(n_stream);
  1440. tor_free(address);
  1441. return 0;
  1442. }
  1443. tor_strlower(address);
  1444. n_stream->address = address;
  1445. n_stream->state = EXIT_CONN_STATE_RESOLVEFAILED;
  1446. /* default to failed, change in dns_resolve if it turns out not to fail */
  1447. if (we_are_hibernating()) {
  1448. connection_edge_end(n_stream, END_STREAM_REASON_HIBERNATING,
  1449. n_stream->cpath_layer);
  1450. connection_free(n_stream);
  1451. return 0;
  1452. }
  1453. /* send it off to the gethostbyname farm */
  1454. switch (dns_resolve(n_stream)) {
  1455. case 1: /* resolve worked */
  1456. /* add it into the linked list of n_streams on this circuit */
  1457. n_stream->next_stream = circ->n_streams;
  1458. n_stream->on_circuit = circ;
  1459. circ->n_streams = n_stream;
  1460. assert_circuit_ok(circ);
  1461. connection_exit_connect(n_stream);
  1462. return 0;
  1463. case -1: /* resolve failed */
  1464. /* n_stream got freed. don't touch it. */
  1465. break;
  1466. case 0: /* resolve added to pending list */
  1467. /* add it into the linked list of resolving_streams on this circuit */
  1468. n_stream->next_stream = circ->resolving_streams;
  1469. n_stream->on_circuit = circ;
  1470. circ->resolving_streams = n_stream;
  1471. assert_circuit_ok(circ);
  1472. ;
  1473. }
  1474. return 0;
  1475. }
  1476. /**
  1477. * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
  1478. * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
  1479. */
  1480. int
  1481. connection_exit_begin_resolve(cell_t *cell, circuit_t *circ)
  1482. {
  1483. connection_t *dummy_conn;
  1484. relay_header_t rh;
  1485. assert_circuit_ok(circ);
  1486. relay_header_unpack(&rh, cell->payload);
  1487. /* This 'dummy_conn' only exists to remember the stream ID
  1488. * associated with the resolve request; and to make the
  1489. * implementation of dns.c more uniform. (We really only need to
  1490. * remember the circuit, the stream ID, and the hostname to be
  1491. * resolved; but if we didn't store them in a connection like this,
  1492. * the housekeeping in dns.c would get way more complicated.)
  1493. */
  1494. dummy_conn = connection_new(CONN_TYPE_EXIT);
  1495. dummy_conn->stream_id = rh.stream_id;
  1496. dummy_conn->address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
  1497. rh.length);
  1498. dummy_conn->port = 0;
  1499. dummy_conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
  1500. dummy_conn->purpose = EXIT_PURPOSE_RESOLVE;
  1501. /* send it off to the gethostbyname farm */
  1502. switch (dns_resolve(dummy_conn)) {
  1503. case -1: /* Impossible to resolve; a resolved cell was sent. */
  1504. /* Connection freed; don't touch it. */
  1505. return 0;
  1506. case 1: /* The result was cached; a resolved cell was sent. */
  1507. if (!dummy_conn->marked_for_close)
  1508. connection_free(dummy_conn);
  1509. return 0;
  1510. case 0: /* resolve added to pending list */
  1511. dummy_conn->next_stream = circ->resolving_streams;
  1512. dummy_conn->on_circuit = circ;
  1513. circ->resolving_streams = dummy_conn;
  1514. assert_circuit_ok(circ);
  1515. break;
  1516. }
  1517. return 0;
  1518. }
  1519. /** Connect to conn's specified addr and port. If it worked, conn
  1520. * has now been added to the connection_array.
  1521. *
  1522. * Send back a connected cell. Include the resolved IP of the destination
  1523. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  1524. * streams must not reveal what IP they connected to.)
  1525. */
  1526. void
  1527. connection_exit_connect(connection_t *conn)
  1528. {
  1529. uint32_t addr;
  1530. uint16_t port;
  1531. if (!connection_edge_is_rendezvous_stream(conn) &&
  1532. router_compare_to_my_exit_policy(conn)) {
  1533. log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
  1534. safe_str(conn->address), conn->port);
  1535. connection_edge_end(conn, END_STREAM_REASON_EXITPOLICY, conn->cpath_layer);
  1536. circuit_detach_stream(circuit_get_by_edge_conn(conn), conn);
  1537. connection_free(conn);
  1538. return;
  1539. }
  1540. addr = conn->addr;
  1541. port = conn->port;
  1542. if (redirect_exit_list) {
  1543. SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, r,
  1544. {
  1545. if ((addr&r->mask)==(r->addr&r->mask) &&
  1546. (r->port_min <= port) && (port <= r->port_max)) {
  1547. struct in_addr in;
  1548. if (r->is_redirect) {
  1549. char tmpbuf[INET_NTOA_BUF_LEN];
  1550. addr = r->addr_dest;
  1551. port = r->port_dest;
  1552. in.s_addr = htonl(addr);
  1553. tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
  1554. log_debug(LD_EXIT, "Redirecting connection from %s:%d to %s:%d",
  1555. safe_str(conn->address), conn->port,
  1556. safe_str(tmpbuf), port);
  1557. }
  1558. break;
  1559. }
  1560. });
  1561. }
  1562. log_debug(LD_EXIT,"about to try connecting");
  1563. switch (connection_connect(conn, conn->address, addr, port)) {
  1564. case -1:
  1565. connection_edge_end_errno(conn, conn->cpath_layer);
  1566. circuit_detach_stream(circuit_get_by_edge_conn(conn), conn);
  1567. connection_free(conn);
  1568. return;
  1569. case 0:
  1570. conn->state = EXIT_CONN_STATE_CONNECTING;
  1571. connection_watch_events(conn, EV_WRITE | EV_READ);
  1572. /* writable indicates finish;
  1573. * readable/error indicates broken link in windowsland. */
  1574. return;
  1575. /* case 1: fall through */
  1576. }
  1577. conn->state = EXIT_CONN_STATE_OPEN;
  1578. if (connection_wants_to_flush(conn)) {
  1579. /* in case there are any queued data cells */
  1580. log_warn(LD_BUG,"Bug: newly connected conn had data waiting!");
  1581. // connection_start_writing(conn);
  1582. }
  1583. connection_watch_events(conn, EV_READ);
  1584. /* also, deliver a 'connected' cell back through the circuit. */
  1585. if (connection_edge_is_rendezvous_stream(conn)) { /* rendezvous stream */
  1586. /* don't send an address back! */
  1587. connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
  1588. RELAY_COMMAND_CONNECTED,
  1589. NULL, 0, conn->cpath_layer);
  1590. } else { /* normal stream */
  1591. /* This must be the original address, not the redirected address. */
  1592. char connected_payload[8];
  1593. set_uint32(connected_payload, htonl(conn->addr));
  1594. set_uint32(connected_payload+4,
  1595. htonl(MAX_DNS_ENTRY_AGE)); /* XXXX fill with a real TTL */
  1596. connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
  1597. RELAY_COMMAND_CONNECTED,
  1598. connected_payload, 8, conn->cpath_layer);
  1599. }
  1600. }
  1601. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  1602. * it is a general stream.
  1603. */
  1604. int
  1605. connection_edge_is_rendezvous_stream(connection_t *conn)
  1606. {
  1607. tor_assert(conn);
  1608. if (*conn->rend_query) /* XXX */
  1609. return 1;
  1610. return 0;
  1611. }
  1612. /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
  1613. * to exit from it, or 0 if it probably will not allow it.
  1614. * (We might be uncertain if conn's destination address has not yet been
  1615. * resolved.)
  1616. */
  1617. int
  1618. connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit)
  1619. {
  1620. tor_assert(conn);
  1621. tor_assert(conn->type == CONN_TYPE_AP);
  1622. tor_assert(conn->socks_request);
  1623. tor_assert(exit);
  1624. #if 0
  1625. log_fn(LOG_DEBUG,"considering nickname %s, for address %s / port %d:",
  1626. exit->nickname, safe_str(conn->socks_request->address),
  1627. conn->socks_request->port);
  1628. #endif
  1629. /* If a particular exit node has been requested for the new connection,
  1630. * make sure the exit node of the existing circuit matches exactly.
  1631. */
  1632. if (conn->chosen_exit_name) {
  1633. if (router_get_by_nickname(conn->chosen_exit_name, 1) != exit) {
  1634. /* doesn't match */
  1635. log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
  1636. conn->chosen_exit_name, exit->nickname);
  1637. return 0;
  1638. }
  1639. }
  1640. if (conn->socks_request->command != SOCKS_COMMAND_RESOLVE) {
  1641. struct in_addr in;
  1642. uint32_t addr = 0;
  1643. addr_policy_result_t r;
  1644. if (tor_inet_aton(conn->socks_request->address, &in))
  1645. addr = ntohl(in.s_addr);
  1646. r = router_compare_addr_to_addr_policy(addr, conn->socks_request->port,
  1647. exit->exit_policy);
  1648. if (r == ADDR_POLICY_REJECTED || r == ADDR_POLICY_PROBABLY_REJECTED)
  1649. return 0;
  1650. }
  1651. return 1;
  1652. }
  1653. /** A helper function for socks_policy_permits_address() below.
  1654. *
  1655. * Parse options->SocksPolicy in the same way that the exit policy
  1656. * is parsed, and put the processed version in socks_policy.
  1657. * Ignore port specifiers.
  1658. */
  1659. void
  1660. parse_socks_policy(void)
  1661. {
  1662. addr_policy_t *n;
  1663. if (socks_policy) {
  1664. addr_policy_free(socks_policy);
  1665. socks_policy = NULL;
  1666. }
  1667. config_parse_addr_policy(get_options()->SocksPolicy, &socks_policy, -1);
  1668. /* ports aren't used. */
  1669. for (n=socks_policy; n; n = n->next) {
  1670. n->prt_min = 1;
  1671. n->prt_max = 65535;
  1672. }
  1673. }
  1674. /** Free all storage held by our SOCKS allow policy
  1675. */
  1676. void
  1677. free_socks_policy(void)
  1678. {
  1679. addr_policy_free(socks_policy);
  1680. socks_policy = NULL;
  1681. }
  1682. /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
  1683. * based on <b>socks_policy</b>. Else return 0.
  1684. */
  1685. int
  1686. socks_policy_permits_address(uint32_t addr)
  1687. {
  1688. int a;
  1689. if (!socks_policy) /* 'no socks policy' means 'accept' */
  1690. return 1;
  1691. a = router_compare_addr_to_addr_policy(addr, 1, socks_policy);
  1692. if (a==ADDR_POLICY_REJECTED)
  1693. return 0;
  1694. else if (a==ADDR_POLICY_ACCEPTED)
  1695. return 1;
  1696. log_warn(LD_BUG, "Bug: Got unexpected 'maybe' answer from socks policy");
  1697. return 0;
  1698. }
  1699. /** Make connection redirection follow the provided list of
  1700. * exit_redirect_t */
  1701. void
  1702. set_exit_redirects(smartlist_t *lst)
  1703. {
  1704. if (redirect_exit_list) {
  1705. SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, p, tor_free(p));
  1706. smartlist_free(redirect_exit_list);
  1707. }
  1708. redirect_exit_list = lst;
  1709. }
  1710. /** If address is of the form "y.onion" with a well-formed handle y:
  1711. * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
  1712. *
  1713. * If address is of the form "y.exit":
  1714. * Put a NUL after y and return EXIT_HOSTNAME.
  1715. *
  1716. * Otherwise:
  1717. * Return NORMAL_HOSTNAME and change nothing.
  1718. */
  1719. hostname_type_t
  1720. parse_extended_hostname(char *address)
  1721. {
  1722. char *s;
  1723. char query[REND_SERVICE_ID_LEN+1];
  1724. s = strrchr(address,'.');
  1725. if (!s) return 0; /* no dot, thus normal */
  1726. if (!strcmp(s+1,"exit")) {
  1727. *s = 0; /* null-terminate it */
  1728. return EXIT_HOSTNAME; /* .exit */
  1729. }
  1730. if (strcmp(s+1,"onion"))
  1731. return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
  1732. /* so it is .onion */
  1733. *s = 0; /* null-terminate it */
  1734. if (strlcpy(query, address, REND_SERVICE_ID_LEN+1) >=
  1735. REND_SERVICE_ID_LEN+1)
  1736. goto failed;
  1737. if (rend_valid_service_id(query)) {
  1738. return ONION_HOSTNAME; /* success */
  1739. }
  1740. failed:
  1741. /* otherwise, return to previous state and return 0 */
  1742. *s = '.';
  1743. return BAD_HOSTNAME;
  1744. }