connection_edge.c 59 KB

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