connection_edge.c 61 KB

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