connection_edge.c 62 KB

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