connection_edge.c 61 KB

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