connection_edge.c 64 KB

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