connection_edge.c 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char connection_edge_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file connection_edge.c
  10. * \brief Handle edge streams.
  11. **/
  12. #include "or.h"
  13. #ifdef HAVE_LINUX_NETFILTER_IPV4_H
  14. #include <linux/netfilter_ipv4.h>
  15. #define TRANS_NETFILTER
  16. #endif
  17. #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
  18. #include <net/if.h>
  19. #include <net/pfvar.h>
  20. #define TRANS_PF
  21. #endif
  22. /* List of exit_redirect_t */
  23. static smartlist_t *redirect_exit_list = NULL;
  24. static int connection_ap_handshake_process_socks(edge_connection_t *conn);
  25. static int connection_ap_process_natd(edge_connection_t *conn);
  26. static int connection_exit_connect_dir(edge_connection_t *exit_conn);
  27. static int hostname_is_noconnect_address(const char *address);
  28. /** An AP stream has failed/finished. If it hasn't already sent back
  29. * a socks reply, send one now (based on endreason). Also set
  30. * has_sent_end to 1, and mark the conn.
  31. */
  32. void
  33. _connection_mark_unattached_ap(edge_connection_t *conn, int endreason,
  34. int line, const char *file)
  35. {
  36. tor_assert(conn->_base.type == CONN_TYPE_AP);
  37. conn->_base.edge_has_sent_end = 1; /* no circ yet */
  38. if (conn->_base.marked_for_close) {
  39. /* This call will warn as appropriate. */
  40. _connection_mark_for_close(TO_CONN(conn), line, file);
  41. return;
  42. }
  43. if (!conn->socks_request->has_finished) {
  44. if (endreason == END_STREAM_REASON_ALREADY_SOCKS_REPLIED)
  45. log_warn(LD_BUG,
  46. "Bug: stream (marked at %s:%d) sending two socks replies?",
  47. file, line);
  48. if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
  49. connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
  50. else
  51. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
  52. 0, NULL, -1);
  53. }
  54. _connection_mark_for_close(TO_CONN(conn), line, file);
  55. conn->_base.hold_open_until_flushed = 1;
  56. conn->end_reason = endreason;
  57. }
  58. /** There was an EOF. Send an end and mark the connection for close.
  59. */
  60. int
  61. connection_edge_reached_eof(edge_connection_t *conn)
  62. {
  63. if (buf_datalen(conn->_base.inbuf) &&
  64. connection_state_is_open(TO_CONN(conn))) {
  65. /* it still has stuff to process. don't let it die yet. */
  66. return 0;
  67. }
  68. log_info(LD_EDGE,"conn (fd %d) reached eof. Closing.", conn->_base.s);
  69. if (!conn->_base.marked_for_close) {
  70. /* only mark it if not already marked. it's possible to
  71. * get the 'end' right around when the client hangs up on us. */
  72. connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
  73. if (conn->socks_request) /* eof, so don't send a socks reply back */
  74. conn->socks_request->has_finished = 1;
  75. connection_mark_for_close(TO_CONN(conn));
  76. }
  77. return 0;
  78. }
  79. /** Handle new bytes on conn->inbuf based on state:
  80. * - If it's waiting for socks info, try to read another step of the
  81. * socks handshake out of conn->inbuf.
  82. * - If it's waiting for the original destination, fetch it.
  83. * - If it's open, then package more relay cells from the stream.
  84. * - Else, leave the bytes on inbuf alone for now.
  85. *
  86. * Mark and return -1 if there was an unexpected error with the conn,
  87. * else return 0.
  88. */
  89. int
  90. connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
  91. {
  92. tor_assert(conn);
  93. switch (conn->_base.state) {
  94. case AP_CONN_STATE_SOCKS_WAIT:
  95. if (connection_ap_handshake_process_socks(conn) < 0) {
  96. /* already marked */
  97. return -1;
  98. }
  99. return 0;
  100. case AP_CONN_STATE_NATD_WAIT:
  101. if (connection_ap_process_natd(conn) < 0) {
  102. /* already marked */
  103. return -1;
  104. }
  105. return 0;
  106. case AP_CONN_STATE_OPEN:
  107. case EXIT_CONN_STATE_OPEN:
  108. if (connection_edge_package_raw_inbuf(conn, package_partial) < 0) {
  109. /* (We already sent an end cell if possible) */
  110. connection_mark_for_close(TO_CONN(conn));
  111. return -1;
  112. }
  113. return 0;
  114. case EXIT_CONN_STATE_CONNECTING:
  115. case AP_CONN_STATE_RENDDESC_WAIT:
  116. case AP_CONN_STATE_CIRCUIT_WAIT:
  117. case AP_CONN_STATE_CONNECT_WAIT:
  118. case AP_CONN_STATE_RESOLVE_WAIT:
  119. case AP_CONN_STATE_CONTROLLER_WAIT:
  120. log_info(LD_EDGE,
  121. "data from edge while in '%s' state. Leaving it on buffer.",
  122. conn_state_to_string(conn->_base.type, conn->_base.state));
  123. return 0;
  124. }
  125. log_warn(LD_BUG,"Bug: Got unexpected state %d. Closing.",conn->_base.state);
  126. tor_fragile_assert();
  127. connection_edge_end(conn, END_STREAM_REASON_INTERNAL, conn->cpath_layer);
  128. connection_mark_for_close(TO_CONN(conn));
  129. return -1;
  130. }
  131. /** This edge needs to be closed, because its circuit has closed.
  132. * Mark it for close and return 0.
  133. */
  134. int
  135. connection_edge_destroy(uint16_t circ_id, edge_connection_t *conn)
  136. {
  137. if (!conn->_base.marked_for_close) {
  138. log_info(LD_EDGE,
  139. "CircID %d: At an edge. Marking connection for close.", circ_id);
  140. if (conn->_base.type == CONN_TYPE_AP) {
  141. connection_mark_unattached_ap(conn, END_STREAM_REASON_DESTROY);
  142. } else {
  143. /* closing the circuit, nothing to send an END to */
  144. conn->_base.edge_has_sent_end = 1;
  145. conn->end_reason = END_STREAM_REASON_DESTROY;
  146. connection_mark_for_close(TO_CONN(conn));
  147. conn->_base.hold_open_until_flushed = 1;
  148. }
  149. }
  150. conn->cpath_layer = NULL;
  151. conn->on_circuit = NULL;
  152. return 0;
  153. }
  154. /** Send a relay end cell from stream <b>conn</b> to conn's circuit,
  155. * with a destination of cpath_layer. (If cpath_layer is NULL, the
  156. * destination is the circuit's origin.) Mark the relay end cell as
  157. * closing because of <b>reason</b>.
  158. *
  159. * Return -1 if this function has already been called on this conn,
  160. * else return 0.
  161. */
  162. int
  163. connection_edge_end(edge_connection_t *conn, char reason,
  164. crypt_path_t *cpath_layer)
  165. {
  166. char payload[RELAY_PAYLOAD_SIZE];
  167. size_t payload_len=1;
  168. circuit_t *circ;
  169. if (conn->_base.edge_has_sent_end) {
  170. log_warn(LD_BUG,"Harmless bug: Calling connection_edge_end (reason %d) "
  171. "on an already ended stream?", reason);
  172. tor_fragile_assert();
  173. return -1;
  174. }
  175. if (conn->_base.marked_for_close) {
  176. log_warn(LD_BUG,
  177. "Bug: called on conn that's already marked for close at %s:%d.",
  178. conn->_base.marked_for_close_file, conn->_base.marked_for_close);
  179. return 0;
  180. }
  181. payload[0] = reason;
  182. if (reason == END_STREAM_REASON_EXITPOLICY &&
  183. !connection_edge_is_rendezvous_stream(conn)) {
  184. set_uint32(payload+1, htonl(conn->_base.addr));
  185. set_uint32(payload+5, htonl(dns_clip_ttl(conn->address_ttl)));
  186. payload_len += 8;
  187. }
  188. circ = circuit_get_by_edge_conn(conn);
  189. if (circ && !circ->marked_for_close) {
  190. log_debug(LD_EDGE,"Marking conn (fd %d) and sending end.",conn->_base.s);
  191. connection_edge_send_command(conn, circ, RELAY_COMMAND_END,
  192. payload, payload_len, cpath_layer);
  193. } else {
  194. log_debug(LD_EDGE,"Marking conn (fd %d); no circ to send end.",
  195. conn->_base.s);
  196. }
  197. conn->_base.edge_has_sent_end = 1;
  198. conn->end_reason = reason;
  199. return 0;
  200. }
  201. /** An error has just occured on an operation on an edge connection
  202. * <b>conn</b>. Extract the errno; convert it to an end reason, and send
  203. * an appropriate relay end cell to <b>cpath_layer</b>.
  204. **/
  205. int
  206. connection_edge_end_errno(edge_connection_t *conn, crypt_path_t *cpath_layer)
  207. {
  208. uint8_t reason;
  209. tor_assert(conn);
  210. reason = (uint8_t)errno_to_end_reason(tor_socket_errno(conn->_base.s));
  211. return connection_edge_end(conn, reason, cpath_layer);
  212. }
  213. /** Connection <b>conn</b> has finished writing and has no bytes left on
  214. * its outbuf.
  215. *
  216. * If it's in state 'open', stop writing, consider responding with a
  217. * sendme, and return.
  218. * Otherwise, stop writing and return.
  219. *
  220. * If <b>conn</b> is broken, mark it for close and return -1, else
  221. * return 0.
  222. */
  223. int
  224. connection_edge_finished_flushing(edge_connection_t *conn)
  225. {
  226. tor_assert(conn);
  227. switch (conn->_base.state) {
  228. case AP_CONN_STATE_OPEN:
  229. case EXIT_CONN_STATE_OPEN:
  230. connection_stop_writing(TO_CONN(conn));
  231. connection_edge_consider_sending_sendme(conn);
  232. return 0;
  233. case AP_CONN_STATE_SOCKS_WAIT:
  234. case AP_CONN_STATE_NATD_WAIT:
  235. case AP_CONN_STATE_RENDDESC_WAIT:
  236. case AP_CONN_STATE_CIRCUIT_WAIT:
  237. case AP_CONN_STATE_CONNECT_WAIT:
  238. case AP_CONN_STATE_CONTROLLER_WAIT:
  239. connection_stop_writing(TO_CONN(conn));
  240. return 0;
  241. default:
  242. log_warn(LD_BUG,"BUG: called in unexpected state %d.",conn->_base.state);
  243. tor_fragile_assert();
  244. return -1;
  245. }
  246. return 0;
  247. }
  248. /** Connected handler for exit connections: start writing pending
  249. * data, deliver 'CONNECTED' relay cells as appropriate, and check
  250. * any pending data that may have been received. */
  251. int
  252. connection_edge_finished_connecting(edge_connection_t *edge_conn)
  253. {
  254. char valbuf[INET_NTOA_BUF_LEN];
  255. connection_t *conn;
  256. struct in_addr in;
  257. tor_assert(edge_conn);
  258. tor_assert(edge_conn->_base.type == CONN_TYPE_EXIT);
  259. conn = TO_CONN(edge_conn);
  260. tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
  261. in.s_addr = htonl(conn->addr);
  262. tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
  263. log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
  264. escaped_safe_str(conn->address),conn->port,safe_str(valbuf));
  265. conn->state = EXIT_CONN_STATE_OPEN;
  266. connection_watch_events(conn, EV_READ); /* stop writing, continue reading */
  267. if (connection_wants_to_flush(conn)) /* in case there are any queued relay
  268. * cells */
  269. connection_start_writing(conn);
  270. /* deliver a 'connected' relay cell back through the circuit. */
  271. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  272. if (connection_edge_send_command(edge_conn,
  273. circuit_get_by_edge_conn(edge_conn),
  274. RELAY_COMMAND_CONNECTED, NULL, 0,
  275. edge_conn->cpath_layer) < 0)
  276. return 0; /* circuit is closed, don't continue */
  277. } else {
  278. char connected_payload[8];
  279. set_uint32(connected_payload, htonl(conn->addr));
  280. set_uint32(connected_payload+4,
  281. htonl(dns_clip_ttl(edge_conn->address_ttl)));
  282. if (connection_edge_send_command(edge_conn,
  283. circuit_get_by_edge_conn(edge_conn),
  284. RELAY_COMMAND_CONNECTED,
  285. connected_payload, 8,
  286. edge_conn->cpath_layer) < 0)
  287. return 0; /* circuit is closed, don't continue */
  288. }
  289. tor_assert(edge_conn->package_window > 0);
  290. /* in case the server has written anything */
  291. return connection_edge_process_inbuf(edge_conn, 1);
  292. }
  293. /** Define a schedule for how long to wait between retrying
  294. * application connections. Rather than waiting a fixed amount of
  295. * time between each retry, we wait 10 seconds each for the first
  296. * two tries, and 15 seconds for each retry after
  297. * that. Hopefully this will improve the expected user experience. */
  298. static int
  299. compute_socks_timeout(edge_connection_t *conn)
  300. {
  301. if (conn->num_socks_retries < 2) /* try 0 and try 1 */
  302. return 10;
  303. return 15;
  304. }
  305. /** Find all general-purpose AP streams waiting for a response that sent their
  306. * begin/resolve cell >=15 seconds ago. Detach from their current circuit, and
  307. * mark their current circuit as unsuitable for new streams. Then call
  308. * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
  309. * available) or launch a new one.
  310. *
  311. * For rendezvous streams, simply give up after SocksTimeout seconds (with no
  312. * retry attempt).
  313. */
  314. void
  315. connection_ap_expire_beginning(void)
  316. {
  317. connection_t **carray;
  318. edge_connection_t *conn;
  319. circuit_t *circ;
  320. const char *nickname;
  321. int n, i;
  322. time_t now = time(NULL);
  323. or_options_t *options = get_options();
  324. int severity;
  325. int cutoff;
  326. int seconds_idle;
  327. get_connection_array(&carray, &n);
  328. for (i = 0; i < n; ++i) {
  329. if (carray[i]->type != CONN_TYPE_AP)
  330. continue;
  331. conn = TO_EDGE_CONN(carray[i]);
  332. /* if it's an internal bridge connection, don't yell its status. */
  333. severity = (!conn->_base.addr && !conn->_base.port)
  334. ? LOG_INFO : LOG_NOTICE;
  335. seconds_idle = now - conn->_base.timestamp_lastread;
  336. if (AP_CONN_STATE_IS_UNATTACHED(conn->_base.state)) {
  337. if (seconds_idle >= options->SocksTimeout) {
  338. if (conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT) {
  339. log_fn(severity, LD_APP,
  340. "Tried for %d seconds to get a connection to %s:%d. Giving up.",
  341. seconds_idle, safe_str(conn->socks_request->address),
  342. conn->socks_request->port);
  343. } else {
  344. log_fn(severity, LD_APP, "Closing unattached stream (state %d).",
  345. conn->_base.state);
  346. /* XXX012 remove the below clause before stable release -RD */
  347. if (conn->_base.state == AP_CONN_STATE_SOCKS_WAIT) {
  348. /* extra debugging */
  349. log_fn(severity, LD_APP,
  350. "Hints: inbuf len %lu, socks: version %d, command %d, "
  351. "has_finished %d, address %s, port %d.",
  352. (unsigned long)buf_datalen(conn->_base.inbuf),
  353. (int)conn->socks_request->socks_version,
  354. conn->socks_request->command,
  355. conn->socks_request->has_finished,
  356. conn->socks_request->address,
  357. (int)conn->socks_request->port);
  358. }
  359. }
  360. connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
  361. }
  362. continue;
  363. }
  364. if (conn->_base.state == AP_CONN_STATE_OPEN)
  365. continue;
  366. cutoff = compute_socks_timeout(conn);
  367. if (seconds_idle < cutoff)
  368. continue;
  369. circ = circuit_get_by_edge_conn(conn);
  370. if (!circ) { /* it's vanished? */
  371. log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
  372. safe_str(conn->socks_request->address));
  373. connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
  374. continue;
  375. }
  376. if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  377. if (seconds_idle > options->SocksTimeout) {
  378. log_fn(severity, LD_REND,
  379. "Rend stream is %d seconds late. Giving up on address"
  380. " '%s.onion'.",
  381. seconds_idle,
  382. safe_str(conn->socks_request->address));
  383. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT,
  384. conn->cpath_layer);
  385. connection_mark_unattached_ap(conn, END_STREAM_REASON_TIMEOUT);
  386. }
  387. continue;
  388. }
  389. tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
  390. nickname = build_state_get_exit_nickname(
  391. TO_ORIGIN_CIRCUIT(circ)->build_state);
  392. log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
  393. "We tried for %d seconds to connect to '%s' using exit '%s'."
  394. " Retrying on a new circuit.",
  395. seconds_idle, safe_str(conn->socks_request->address),
  396. nickname ? nickname : "*unnamed*");
  397. /* send an end down the circuit */
  398. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
  399. /* un-mark it as ending, since we're going to reuse it */
  400. conn->_base.edge_has_sent_end = 0;
  401. conn->end_reason = 0;
  402. /* kludge to make us not try this circuit again, yet to allow
  403. * current streams on it to survive if they can: make it
  404. * unattractive to use for new streams */
  405. tor_assert(circ->timestamp_dirty);
  406. circ->timestamp_dirty -= options->MaxCircuitDirtiness;
  407. /* give our stream another 'cutoff' seconds to try */
  408. conn->_base.timestamp_lastread += cutoff;
  409. if (conn->num_socks_retries < 250) /* avoid overflow */
  410. conn->num_socks_retries++;
  411. /* move it back into 'pending' state, and try to attach. */
  412. if (connection_ap_detach_retriable(conn, TO_ORIGIN_CIRCUIT(circ),
  413. END_STREAM_REASON_TIMEOUT)<0) {
  414. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  415. }
  416. } /* end for */
  417. }
  418. /** Tell any AP streams that are waiting for a new circuit to try again,
  419. * either attaching to an available circ or launching a new one.
  420. */
  421. void
  422. connection_ap_attach_pending(void)
  423. {
  424. connection_t **carray;
  425. connection_t *conn;
  426. edge_connection_t *edge_conn;
  427. int n, i;
  428. get_connection_array(&carray, &n);
  429. for (i = 0; i < n; ++i) {
  430. conn = carray[i];
  431. if (conn->marked_for_close ||
  432. conn->type != CONN_TYPE_AP ||
  433. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  434. continue;
  435. edge_conn = TO_EDGE_CONN(conn);
  436. if (connection_ap_handshake_attach_circuit(edge_conn) < 0) {
  437. connection_mark_unattached_ap(edge_conn, END_STREAM_REASON_CANT_ATTACH);
  438. }
  439. }
  440. }
  441. /** A circuit failed to finish on its last hop <b>info</b>. If there
  442. * are any streams waiting with this exit node in mind, but they
  443. * don't absolutely require it, make them give up on it.
  444. */
  445. void
  446. circuit_discard_optional_exit_enclaves(extend_info_t *info)
  447. {
  448. connection_t **carray;
  449. connection_t *conn;
  450. edge_connection_t *edge_conn;
  451. routerinfo_t *r1, *r2;
  452. int n, i;
  453. get_connection_array(&carray, &n);
  454. for (i = 0; i < n; ++i) {
  455. conn = carray[i];
  456. if (conn->marked_for_close ||
  457. conn->type != CONN_TYPE_AP ||
  458. !conn->chosen_exit_optional)
  459. continue;
  460. edge_conn = TO_EDGE_CONN(conn);
  461. r1 = router_get_by_nickname(edge_conn->chosen_exit_name, 0);
  462. r2 = router_get_by_nickname(info->nickname, 0);
  463. if (r1 && r2 && r1==r2) {
  464. tor_assert(edge_conn->socks_request);
  465. log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
  466. safe_str(edge_conn->chosen_exit_name),
  467. escaped_safe_str(edge_conn->socks_request->address));
  468. conn->chosen_exit_optional = 0;
  469. tor_free(edge_conn->chosen_exit_name); /* clears it */
  470. }
  471. }
  472. }
  473. /** The AP connection <b>conn</b> has just failed while attaching or
  474. * sending a BEGIN or resolving on <b>circ</b>, but another circuit
  475. * might work. Detach the circuit, and either reattach it, launch a
  476. * new circuit, tell the controller, or give up as a appropriate.
  477. *
  478. * Returns -1 on err, 1 on success, 0 on not-yet-sure.
  479. */
  480. int
  481. connection_ap_detach_retriable(edge_connection_t *conn, origin_circuit_t *circ,
  482. int reason)
  483. {
  484. control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
  485. conn->_base.timestamp_lastread = time(NULL);
  486. if (! get_options()->LeaveStreamsUnattached) {
  487. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  488. circuit_detach_stream(TO_CIRCUIT(circ),conn);
  489. return connection_ap_handshake_attach_circuit(conn);
  490. } else {
  491. conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  492. circuit_detach_stream(TO_CIRCUIT(circ),conn);
  493. return 0;
  494. }
  495. }
  496. /** A client-side struct to remember requests to rewrite addresses
  497. * to new addresses. These structs are stored in the hash table
  498. * "addressmap" below.
  499. *
  500. * There are 5 ways to set an address mapping:
  501. * - A MapAddress command from the controller [permanent]
  502. * - An AddressMap directive in the torrc [permanent]
  503. * - When a TrackHostExits torrc directive is triggered [temporary]
  504. * - When a dns resolve succeeds [temporary]
  505. * - When a dns resolve fails [temporary]
  506. *
  507. * When an addressmap request is made but one is already registered,
  508. * the new one is replaced only if the currently registered one has
  509. * no "new_address" (that is, it's in the process of dns resolve),
  510. * or if the new one is permanent (expires==0 or 1).
  511. *
  512. * (We overload the 'expires' field, using "0" for mappings set via
  513. * the configuration file, "1" for mappings set from the control
  514. * interface, and other values for DNS mappings that can expire.)
  515. */
  516. typedef struct {
  517. char *new_address;
  518. time_t expires;
  519. int num_resolve_failures;
  520. } addressmap_entry_t;
  521. /** Entry for mapping addresses to which virtual address we mapped them to. */
  522. typedef struct {
  523. char *ipv4_address;
  524. char *hostname_address;
  525. } virtaddress_entry_t;
  526. /** A hash table to store client-side address rewrite instructions. */
  527. static strmap_t *addressmap=NULL;
  528. /**
  529. * Table mapping addresses to which virtual address, if any, we
  530. * assigned them to.
  531. *
  532. * We maintain the following invariant: if [A,B] is in
  533. * virtaddress_reversemap, then B must be a virtual address, and [A,B]
  534. * must be in addressmap. We do not require that the converse hold:
  535. * if it fails, then we could end up mapping two virtual addresses to
  536. * the same address, which is no disaster.
  537. **/
  538. static strmap_t *virtaddress_reversemap=NULL;
  539. /** Initialize addressmap. */
  540. void
  541. addressmap_init(void)
  542. {
  543. addressmap = strmap_new();
  544. virtaddress_reversemap = strmap_new();
  545. }
  546. /** Free the memory associated with the addressmap entry <b>_ent</b>. */
  547. static void
  548. addressmap_ent_free(void *_ent)
  549. {
  550. addressmap_entry_t *ent = _ent;
  551. tor_free(ent->new_address);
  552. tor_free(ent);
  553. }
  554. /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b> */
  555. static void
  556. addressmap_virtaddress_ent_free(void *_ent)
  557. {
  558. virtaddress_entry_t *ent = _ent;
  559. tor_free(ent->ipv4_address);
  560. tor_free(ent->hostname_address);
  561. tor_free(ent);
  562. }
  563. /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b> */
  564. static void
  565. addressmap_virtaddress_remove(const char *address, addressmap_entry_t *ent)
  566. {
  567. if (ent && ent->new_address &&
  568. address_is_in_virtual_range(ent->new_address)) {
  569. virtaddress_entry_t *ve =
  570. strmap_get(virtaddress_reversemap, ent->new_address);
  571. /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
  572. if (ve) {
  573. if (!strcmp(address, ve->ipv4_address))
  574. tor_free(ve->ipv4_address);
  575. if (!strcmp(address, ve->hostname_address))
  576. tor_free(ve->hostname_address);
  577. if (!ve->ipv4_address && !ve->hostname_address) {
  578. tor_free(ve);
  579. strmap_remove(virtaddress_reversemap, ent->new_address);
  580. }
  581. }
  582. }
  583. }
  584. /* DOCDOC */
  585. static void
  586. addressmap_ent_remove(const char *address, addressmap_entry_t *ent)
  587. {
  588. addressmap_virtaddress_remove(address, ent);
  589. addressmap_ent_free(ent);
  590. }
  591. /** Remove all entries from the addressmap that were set via the
  592. * configuration file or the command line. */
  593. void
  594. addressmap_clear_configured(void)
  595. {
  596. addressmap_get_mappings(NULL, 0, 0);
  597. }
  598. /** Remove all entries from the addressmap that are set to expire, ever. */
  599. void
  600. addressmap_clear_transient(void)
  601. {
  602. addressmap_get_mappings(NULL, 2, TIME_MAX);
  603. }
  604. /** Clean out entries from the addressmap cache that were
  605. * added long enough ago that they are no longer valid.
  606. */
  607. void
  608. addressmap_clean(time_t now)
  609. {
  610. addressmap_get_mappings(NULL, 2, now);
  611. }
  612. /** Free all the elements in the addressmap, and free the addressmap
  613. * itself. */
  614. void
  615. addressmap_free_all(void)
  616. {
  617. if (addressmap) {
  618. strmap_free(addressmap, addressmap_ent_free);
  619. addressmap = NULL;
  620. }
  621. if (virtaddress_reversemap) {
  622. strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
  623. virtaddress_reversemap = NULL;
  624. }
  625. }
  626. /** Look at address, and rewrite it until it doesn't want any
  627. * more rewrites; but don't get into an infinite loop.
  628. * Don't write more than maxlen chars into address.
  629. */
  630. void
  631. addressmap_rewrite(char *address, size_t maxlen)
  632. {
  633. addressmap_entry_t *ent;
  634. int rewrites;
  635. char *cp;
  636. for (rewrites = 0; rewrites < 16; rewrites++) {
  637. ent = strmap_get(addressmap, address);
  638. if (!ent || !ent->new_address)
  639. return; /* done, no rewrite needed */
  640. cp = tor_strdup(escaped_safe_str(ent->new_address));
  641. log_info(LD_APP, "Addressmap: rewriting %s to %s",
  642. escaped_safe_str(address), cp);
  643. tor_free(cp);
  644. strlcpy(address, ent->new_address, maxlen);
  645. }
  646. log_warn(LD_CONFIG,
  647. "Loop detected: we've rewritten %s 16 times! Using it as-is.",
  648. escaped_safe_str(address));
  649. /* it's fine to rewrite a rewrite, but don't loop forever */
  650. }
  651. /* DOCDOC */
  652. static int
  653. addressmap_rewrite_reverse(char *address, size_t maxlen)
  654. {
  655. size_t len = maxlen + 16;
  656. char *s = tor_malloc(len), *cp;
  657. addressmap_entry_t *ent;
  658. int r = 0;
  659. tor_snprintf(s, len, "REVERSE[%s]", address);
  660. ent = strmap_get(addressmap, s);
  661. if (ent) {
  662. cp = tor_strdup(escaped_safe_str(ent->new_address));
  663. log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
  664. escaped_safe_str(s), cp);
  665. tor_free(cp);
  666. strlcpy(address, ent->new_address, maxlen);
  667. r = 1;
  668. }
  669. tor_free(s);
  670. return r;
  671. }
  672. /** Return 1 if <b>address</b> is already registered, else return 0 */
  673. int
  674. addressmap_have_mapping(const char *address)
  675. {
  676. return strmap_get_lc(addressmap, address) ? 1 : 0;
  677. }
  678. /** Register a request to map <b>address</b> to <b>new_address</b>,
  679. * which will expire on <b>expires</b> (or 0 if never expires from
  680. * config file, 1 if never expires from controller, 2 if never expires
  681. * (virtual address mapping) from the controller.)
  682. *
  683. * <b>new_address</b> should be a newly dup'ed string, which we'll use or
  684. * free as appropriate. We will leave address alone.
  685. *
  686. * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
  687. * any mappings that exist from <b>address</b>.
  688. */
  689. void
  690. addressmap_register(const char *address, char *new_address, time_t expires)
  691. {
  692. addressmap_entry_t *ent;
  693. ent = strmap_get(addressmap, address);
  694. if (!new_address || !strcasecmp(address,new_address)) {
  695. /* Remove the mapping, if any. */
  696. tor_free(new_address);
  697. if (ent) {
  698. addressmap_ent_remove(address,ent);
  699. strmap_remove(addressmap, address);
  700. }
  701. return;
  702. }
  703. if (!ent) { /* make a new one and register it */
  704. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  705. strmap_set(addressmap, address, ent);
  706. } else if (ent->new_address) { /* we need to clean up the old mapping. */
  707. if (expires > 1) {
  708. log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
  709. "since it's already mapped to '%s'",
  710. safe_str(address), safe_str(new_address), safe_str(ent->new_address));
  711. tor_free(new_address);
  712. return;
  713. }
  714. if (address_is_in_virtual_range(ent->new_address) &&
  715. expires != 2) {
  716. /* XXX This isn't the perfect test; we want to avoid removing
  717. * mappings set from the control interface _as virtual mapping */
  718. addressmap_virtaddress_remove(address, ent);
  719. }
  720. tor_free(ent->new_address);
  721. } /* else { we have an in-progress resolve with no mapping. } */
  722. ent->new_address = new_address;
  723. ent->expires = expires==2 ? 1 : expires;
  724. ent->num_resolve_failures = 0;
  725. log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
  726. safe_str(address), safe_str(ent->new_address));
  727. control_event_address_mapped(address, ent->new_address, expires);
  728. }
  729. /** An attempt to resolve <b>address</b> failed at some OR.
  730. * Increment the number of resolve failures we have on record
  731. * for it, and then return that number.
  732. */
  733. int
  734. client_dns_incr_failures(const char *address)
  735. {
  736. addressmap_entry_t *ent = strmap_get(addressmap, address);
  737. if (!ent) {
  738. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  739. ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
  740. strmap_set(addressmap,address,ent);
  741. }
  742. ++ent->num_resolve_failures;
  743. log_info(LD_APP, "Address %s now has %d resolve failures.",
  744. safe_str(address), ent->num_resolve_failures);
  745. return ent->num_resolve_failures;
  746. }
  747. /** If <b>address</b> is in the client dns addressmap, reset
  748. * the number of resolve failures we have on record for it.
  749. * This is used when we fail a stream because it won't resolve:
  750. * otherwise future attempts on that address will only try once.
  751. */
  752. void
  753. client_dns_clear_failures(const char *address)
  754. {
  755. addressmap_entry_t *ent = strmap_get(addressmap, address);
  756. if (ent)
  757. ent->num_resolve_failures = 0;
  758. }
  759. /** Record the fact that <b>address</b> resolved to <b>name</b>.
  760. * We can now use this in subsequent streams via addressmap_rewrite()
  761. * so we can more correctly choose an exit that will allow <b>address</b>.
  762. *
  763. * If <b>exitname</b> is defined, then append the addresses with
  764. * ".exitname.exit" before registering the mapping.
  765. *
  766. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  767. * <b>ttl</b>seconds; otherwise, we use the default.
  768. */
  769. static void
  770. client_dns_set_addressmap_impl(const char *address, const char *name,
  771. const char *exitname,
  772. int ttl)
  773. {
  774. /* <address>.<hex or nickname>.exit\0 or just <address>\0 */
  775. char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
  776. /* 123.123.123.123.<hex or nickname>.exit\0 or just 123.123.123.123\0 */
  777. char extendedval[INET_NTOA_BUF_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
  778. tor_assert(address);
  779. tor_assert(name);
  780. if (ttl<0)
  781. ttl = DEFAULT_DNS_TTL;
  782. else
  783. ttl = dns_clip_ttl(ttl);
  784. if (exitname) {
  785. /* XXXX fails to ever get attempts to get an exit address of
  786. * google.com.digest[=~]nickname.exit; we need a syntax for this that
  787. * won't make strict RFC952-compliant applications (like us) barf. */
  788. tor_snprintf(extendedaddress, sizeof(extendedaddress),
  789. "%s.%s.exit", address, exitname);
  790. tor_snprintf(extendedval, sizeof(extendedval),
  791. "%s.%s.exit", name, exitname);
  792. } else {
  793. tor_snprintf(extendedaddress, sizeof(extendedaddress),
  794. "%s", address);
  795. tor_snprintf(extendedval, sizeof(extendedval),
  796. "%s", name);
  797. }
  798. addressmap_register(extendedaddress, tor_strdup(extendedval),
  799. time(NULL) + ttl);
  800. }
  801. /** Record the fact that <b>address</b> resolved to <b>val</b>.
  802. * We can now use this in subsequent streams via addressmap_rewrite()
  803. * so we can more correctly choose an exit that will allow <b>address</b>.
  804. *
  805. * If <b>exitname</b> is defined, then append the addresses with
  806. * ".exitname.exit" before registering the mapping.
  807. *
  808. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  809. * <b>ttl</b>seconds; otherwise, we use the default.
  810. */
  811. void
  812. client_dns_set_addressmap(const char *address, uint32_t val,
  813. const char *exitname,
  814. int ttl)
  815. {
  816. struct in_addr in;
  817. char valbuf[INET_NTOA_BUF_LEN];
  818. tor_assert(address);
  819. if (tor_inet_aton(address, &in))
  820. return; /* If address was an IP address already, don't add a mapping. */
  821. in.s_addr = htonl(val);
  822. tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
  823. client_dns_set_addressmap_impl(address, valbuf, exitname, ttl);
  824. }
  825. /** DOCDOC */
  826. static void
  827. client_dns_set_reverse_addressmap(const char *address, const char *v,
  828. const char *exitname,
  829. int ttl)
  830. {
  831. size_t len = strlen(address) + 16;
  832. char *s = tor_malloc(len);
  833. tor_snprintf(s, len, "REVERSE[%s]", address);
  834. client_dns_set_addressmap_impl(s, v, exitname, ttl);
  835. tor_free(s);
  836. }
  837. /* By default, we hand out 127.192.0.1 through 127.254.254.254.
  838. * These addresses should map to localhost, so even if the
  839. * application accidentally tried to connect to them directly (not
  840. * via Tor), it wouldn't get too far astray.
  841. *
  842. * Eventually, we should probably make this configurable.
  843. */
  844. static uint32_t virtual_addr_network = 0x7fc00000u;
  845. static uint32_t virtual_addr_netmask = 0xffc00000u;
  846. static int virtual_addr_netmask_bits = 10;
  847. static uint32_t next_virtual_addr = 0x7fc00000u;
  848. /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
  849. * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
  850. * requests. Return 0 on success; set *msg (if provided) to a newly allocated
  851. * string and return -1 on failure. If validate_only is false, sets the
  852. * actual virtual address range to the parsed value. */
  853. int
  854. parse_virtual_addr_network(const char *val, int validate_only,
  855. char **msg)
  856. {
  857. uint32_t addr, mask;
  858. uint16_t port_min, port_max;
  859. int bits;
  860. if (parse_addr_and_port_range(val, &addr, &mask, &port_min, &port_max)) {
  861. if (msg) *msg = tor_strdup("Error parsing VirtualAddressNetwork");
  862. return -1;
  863. }
  864. if (port_min != 1 || port_max != 65535) {
  865. if (msg) *msg = tor_strdup("Can't specify ports on VirtualAddressNetwork");
  866. return -1;
  867. }
  868. bits = addr_mask_get_bits(mask);
  869. if (bits < 0) {
  870. if (msg) *msg = tor_strdup("VirtualAddressNetwork must have a mask that "
  871. "can be expressed as a prefix");
  872. return -1;
  873. }
  874. if (bits > 16) {
  875. if (msg) *msg = tor_strdup("VirtualAddressNetwork expects a /16 "
  876. "network or larger");
  877. return -1;
  878. }
  879. if (validate_only)
  880. return 0;
  881. virtual_addr_network = addr & mask;
  882. virtual_addr_netmask = mask;
  883. virtual_addr_netmask_bits = bits;
  884. if ((next_virtual_addr & mask) != addr)
  885. next_virtual_addr = addr;
  886. return 0;
  887. }
  888. /**
  889. * Return true iff <b>addr</b> is likely to have been returned by
  890. * client_dns_get_unused_address.
  891. **/
  892. int
  893. address_is_in_virtual_range(const char *address)
  894. {
  895. struct in_addr in;
  896. tor_assert(address);
  897. if (!strcasecmpend(address, ".virtual")) {
  898. return 1;
  899. } else if (tor_inet_aton(address, &in)) {
  900. uint32_t addr = ntohl(in.s_addr);
  901. if ((addr & virtual_addr_netmask) == virtual_addr_network)
  902. return 1;
  903. }
  904. return 0;
  905. }
  906. /** Return a newly allocated string holding an address of <b>type</b>
  907. * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
  908. * and that is very unlikely to be the address of any real host.
  909. */
  910. static char *
  911. addressmap_get_virtual_address(int type)
  912. {
  913. char buf[64];
  914. struct in_addr in;
  915. if (type == RESOLVED_TYPE_HOSTNAME) {
  916. char rand[10];
  917. do {
  918. crypto_rand(rand, sizeof(rand));
  919. base32_encode(buf,sizeof(buf),rand,sizeof(rand));
  920. strlcat(buf, ".virtual", sizeof(buf));
  921. } while (strmap_get(addressmap, buf));
  922. return tor_strdup(buf);
  923. } else if (type == RESOLVED_TYPE_IPV4) {
  924. // This is an imperfect estimate of how many addresses are available, but
  925. // that's ok.
  926. uint32_t available = 1u << (32-virtual_addr_netmask_bits);
  927. while (available) {
  928. /* Don't hand out any .0 or .255 address. */
  929. while ((next_virtual_addr & 0xff) == 0 ||
  930. (next_virtual_addr & 0xff) == 0xff) {
  931. ++next_virtual_addr;
  932. }
  933. in.s_addr = htonl(next_virtual_addr);
  934. tor_inet_ntoa(&in, buf, sizeof(buf));
  935. if (!strmap_get(addressmap, buf))
  936. break;
  937. ++next_virtual_addr;
  938. --available;
  939. log_notice(LD_CONFIG, "%d addrs available", (int)available);
  940. if (! --available) {
  941. log_warn(LD_CONFIG, "Ran out of virtual addresses!");
  942. return NULL;
  943. }
  944. if ((next_virtual_addr & virtual_addr_netmask) != virtual_addr_network)
  945. next_virtual_addr = virtual_addr_network;
  946. }
  947. return tor_strdup(buf);
  948. } else {
  949. log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
  950. return NULL;
  951. }
  952. }
  953. /** A controller has requested that we map some address of type
  954. * <b>type</b> to the address <b>new_address</b>. Choose an address
  955. * that is unlikely to be used, and map it, and return it in a newly
  956. * allocated string. If another address of the same type is already
  957. * mapped to <b>new_address</b>, try to return a copy of that address.
  958. *
  959. * The string in <b>new_address</b> may be freed, or inserted into a map
  960. * as appropriate.
  961. **/
  962. const char *
  963. addressmap_register_virtual_address(int type, char *new_address)
  964. {
  965. char **addrp;
  966. virtaddress_entry_t *vent;
  967. tor_assert(new_address);
  968. tor_assert(addressmap);
  969. tor_assert(virtaddress_reversemap);
  970. vent = strmap_get(virtaddress_reversemap, new_address);
  971. if (!vent) {
  972. vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
  973. strmap_set(virtaddress_reversemap, new_address, vent);
  974. }
  975. addrp = (type == RESOLVED_TYPE_IPV4) ?
  976. &vent->ipv4_address : &vent->hostname_address;
  977. if (*addrp) {
  978. addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
  979. if (ent && ent->new_address &&
  980. !strcasecmp(new_address, ent->new_address)) {
  981. tor_free(new_address);
  982. return tor_strdup(*addrp);
  983. } else
  984. log_warn(LD_BUG,
  985. "Internal confusion: I thought that '%s' was mapped to by "
  986. "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
  987. safe_str(new_address), safe_str(*addrp), safe_str(*addrp),
  988. ent?safe_str(ent->new_address):"(nothing)");
  989. }
  990. tor_free(*addrp);
  991. *addrp = addressmap_get_virtual_address(type);
  992. addressmap_register(*addrp, new_address, 2);
  993. #if 0
  994. {
  995. /* Try to catch possible bugs */
  996. addressmap_entry_t *ent;
  997. ent = strmap_get(addressmap, *addrp);
  998. tor_assert(ent);
  999. tor_assert(!strcasecmp(ent->new_address,new_address));
  1000. vent = strmap_get(virtaddress_reversemap, new_address);
  1001. tor_assert(vent);
  1002. tor_assert(!strcasecmp(*addrp,
  1003. (type == RESOLVED_TYPE_IPV4) ?
  1004. vent->ipv4_address : vent->hostname_address));
  1005. log_fn(LOG_INFO, "Map from %s to %s okay.",
  1006. safe_str(*addrp),safe_str(new_address));
  1007. }
  1008. #endif
  1009. return *addrp;
  1010. }
  1011. /** Return 1 if <b>address</b> has funny characters in it like colons. Return
  1012. * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
  1013. * should be true if we're using this address as a client; false if we're
  1014. * using it as a server.
  1015. */
  1016. int
  1017. address_is_invalid_destination(const char *address, int client)
  1018. {
  1019. if (client) {
  1020. if (get_options()->AllowNonRFC953Hostnames)
  1021. return 0;
  1022. } else {
  1023. if (get_options()->ServerDNSAllowNonRFC953Hostnames)
  1024. return 0;
  1025. }
  1026. while (*address) {
  1027. if (TOR_ISALNUM(*address) ||
  1028. *address == '-' ||
  1029. *address == '.' ||
  1030. *address == '_') /* Underscore is not allowed, but Windows does it
  1031. * sometimes, just to thumb its nose at the IETF. */
  1032. ++address;
  1033. else
  1034. return 1;
  1035. }
  1036. return 0;
  1037. }
  1038. /** Iterate over all address mappings which have expiry times between
  1039. * min_expires and max_expires, inclusive. If sl is provided, add an
  1040. * "old-addr new-addr" string to sl for each mapping. If sl is NULL,
  1041. * remove the mappings.
  1042. */
  1043. void
  1044. addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
  1045. time_t max_expires)
  1046. {
  1047. strmap_iter_t *iter;
  1048. const char *key;
  1049. void *_val;
  1050. addressmap_entry_t *val;
  1051. if (!addressmap)
  1052. addressmap_init();
  1053. for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
  1054. strmap_iter_get(iter, &key, &_val);
  1055. val = _val;
  1056. if (val->expires >= min_expires && val->expires <= max_expires) {
  1057. if (!sl) {
  1058. iter = strmap_iter_next_rmv(addressmap,iter);
  1059. addressmap_ent_remove(key, val);
  1060. continue;
  1061. } else if (val->new_address) {
  1062. size_t len = strlen(key)+strlen(val->new_address)+2;
  1063. char *line = tor_malloc(len);
  1064. tor_snprintf(line, len, "%s %s", key, val->new_address);
  1065. smartlist_add(sl, line);
  1066. }
  1067. }
  1068. iter = strmap_iter_next(addressmap,iter);
  1069. }
  1070. }
  1071. /* Connection <b>conn</b> just finished its socks handshake, or the
  1072. * controller asked us to take care of it. If <b>circ</b> is defined,
  1073. * then that's where we'll want to attach it. Otherwise we have to
  1074. * figure it out ourselves.
  1075. *
  1076. * First, parse whether it's a .exit address, remap it, and so on. Then
  1077. * if it's for a general circuit, try to attach it to a circuit (or launch
  1078. * one as needed), else if it's for a rendezvous circuit, fetch a
  1079. * rendezvous descriptor first (or attach/launch a circuit if the
  1080. * rendezvous descriptor is already here and fresh enough).
  1081. */
  1082. int
  1083. connection_ap_handshake_rewrite_and_attach(edge_connection_t *conn,
  1084. origin_circuit_t *circ)
  1085. {
  1086. socks_request_t *socks = conn->socks_request;
  1087. hostname_type_t addresstype;
  1088. tor_strlower(socks->address); /* normalize it */
  1089. log_debug(LD_APP,"Client asked for %s:%d",
  1090. safe_str(socks->address),
  1091. socks->port);
  1092. if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1093. if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address))) {
  1094. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
  1095. strlen(socks->address),
  1096. socks->address, -1);
  1097. connection_mark_unattached_ap(conn,
  1098. END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  1099. return 0;
  1100. }
  1101. } else {
  1102. /* For address map controls, remap the address */
  1103. addressmap_rewrite(socks->address, sizeof(socks->address));
  1104. }
  1105. if (address_is_in_virtual_range(socks->address)) {
  1106. /* This address was probably handed out by client_dns_get_unmapped_address,
  1107. * but the mapping was discarded for some reason. We *don't* want to send
  1108. * the address through Tor; that's likely to fail, and may leak
  1109. * information.
  1110. */
  1111. log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
  1112. socks->address); /* don't safe_str() this yet. */
  1113. connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
  1114. return -1;
  1115. }
  1116. /* Parse the address provided by SOCKS. Modify it in-place if it
  1117. * specifies a hidden-service (.onion) or particular exit node (.exit).
  1118. */
  1119. addresstype = parse_extended_hostname(socks->address);
  1120. if (addresstype == BAD_HOSTNAME) {
  1121. log_warn(LD_APP, "Invalid hostname %s; rejecting", socks->address);
  1122. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1123. escaped(socks->address));
  1124. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1125. return -1;
  1126. }
  1127. if (addresstype == EXIT_HOSTNAME) {
  1128. /* foo.exit -- modify conn->chosen_exit_node to specify the exit
  1129. * node, and conn->address to hold only the address portion.*/
  1130. char *s = strrchr(socks->address,'.');
  1131. if (s) {
  1132. if (s[1] != '\0') {
  1133. conn->chosen_exit_name = tor_strdup(s+1);
  1134. *s = 0;
  1135. } else {
  1136. log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
  1137. safe_str(socks->address));
  1138. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1139. escaped(socks->address));
  1140. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1141. return -1;
  1142. }
  1143. } else {
  1144. routerinfo_t *r;
  1145. conn->chosen_exit_name = tor_strdup(socks->address);
  1146. r = router_get_by_nickname(conn->chosen_exit_name, 1);
  1147. *socks->address = 0;
  1148. if (r) {
  1149. strlcpy(socks->address, r->address, sizeof(socks->address));
  1150. } else {
  1151. log_warn(LD_APP,
  1152. "Unrecognized server in exit address '%s.exit'. Refusing.",
  1153. safe_str(socks->address));
  1154. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1155. return -1;
  1156. }
  1157. }
  1158. }
  1159. if (addresstype != ONION_HOSTNAME) {
  1160. /* not a hidden-service request (i.e. normal or .exit) */
  1161. if (address_is_invalid_destination(socks->address, 1)) {
  1162. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1163. escaped(socks->address));
  1164. log_warn(LD_APP,
  1165. "Destination '%s' seems to be an invalid hostname. Failing.",
  1166. safe_str(socks->address));
  1167. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1168. return -1;
  1169. }
  1170. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  1171. uint32_t answer;
  1172. struct in_addr in;
  1173. /* Reply to resolves immediately if we can. */
  1174. if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
  1175. log_warn(LD_APP,"Address to be resolved is too large. Failing.");
  1176. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1177. escaped(socks->address));
  1178. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
  1179. 0,NULL,-1);
  1180. connection_mark_unattached_ap(conn,
  1181. END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  1182. return -1;
  1183. }
  1184. if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
  1185. answer = in.s_addr; /* leave it in network order */
  1186. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
  1187. (char*)&answer,-1);
  1188. connection_mark_unattached_ap(conn,
  1189. END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  1190. return 0;
  1191. }
  1192. rep_hist_note_used_resolve(time(NULL)); /* help predict this next time */
  1193. } else if (socks->command == SOCKS_COMMAND_CONNECT) {
  1194. if (socks->port == 0) {
  1195. log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
  1196. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1197. return -1;
  1198. }
  1199. if (!conn->chosen_exit_name && !circ) {
  1200. /* see if we can find a suitable enclave exit */
  1201. routerinfo_t *r =
  1202. router_find_exact_exit_enclave(socks->address, socks->port);
  1203. if (r) {
  1204. log_info(LD_APP,
  1205. "Redirecting address %s to exit at enclave router %s",
  1206. safe_str(socks->address), r->nickname);
  1207. /* use the hex digest, not nickname, in case there are two
  1208. routers with this nickname */
  1209. conn->chosen_exit_name =
  1210. tor_strdup(hex_str(r->cache_info.identity_digest, DIGEST_LEN));
  1211. conn->_base.chosen_exit_optional = 1;
  1212. }
  1213. }
  1214. /* help predict this next time */
  1215. rep_hist_note_used_port(socks->port, time(NULL));
  1216. } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1217. rep_hist_note_used_resolve(time(NULL)); /* help predict this next time */
  1218. } else if (socks->command == SOCKS_COMMAND_CONNECT_DIR) {
  1219. ; /* nothing */
  1220. } else {
  1221. tor_fragile_assert();
  1222. }
  1223. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1224. if ((circ &&
  1225. connection_ap_handshake_attach_chosen_circuit(conn, circ) < 0) ||
  1226. (!circ &&
  1227. connection_ap_handshake_attach_circuit(conn) < 0)) {
  1228. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1229. return -1;
  1230. }
  1231. return 0;
  1232. } else {
  1233. /* it's a hidden-service request */
  1234. rend_cache_entry_t *entry;
  1235. int r;
  1236. if (!SOCKS_COMMAND_IS_CONNECT(socks->command)) {
  1237. /* if it's a resolve request, fail it right now, rather than
  1238. * building all the circuits and then realizing it won't work. */
  1239. log_warn(LD_APP,
  1240. "Resolve requests to hidden services not allowed. Failing.");
  1241. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
  1242. 0,NULL,-1);
  1243. connection_mark_unattached_ap(conn,
  1244. END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  1245. return -1;
  1246. }
  1247. if (circ) {
  1248. log_warn(LD_CONTROL, "Attachstream to a circuit is not "
  1249. "supported for .onion addresses currently. Failing.");
  1250. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1251. return -1;
  1252. }
  1253. strlcpy(conn->rend_query, socks->address, sizeof(conn->rend_query));
  1254. log_info(LD_REND,"Got a hidden service request for ID '%s'",
  1255. safe_str(conn->rend_query));
  1256. /* see if we already have it cached */
  1257. r = rend_cache_lookup_entry(conn->rend_query, -1, &entry);
  1258. if (r<0) {
  1259. log_warn(LD_BUG,"Bug: Invalid service name '%s'",
  1260. safe_str(conn->rend_query));
  1261. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1262. return -1;
  1263. }
  1264. if (r==0) {
  1265. conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
  1266. log_info(LD_REND, "Unknown descriptor %s. Fetching.",
  1267. safe_str(conn->rend_query));
  1268. rend_client_refetch_renddesc(conn->rend_query);
  1269. } else { /* r > 0 */
  1270. #define NUM_SECONDS_BEFORE_REFETCH (60*15)
  1271. if (time(NULL) - entry->received < NUM_SECONDS_BEFORE_REFETCH) {
  1272. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1273. log_info(LD_REND, "Descriptor is here and fresh enough. Great.");
  1274. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  1275. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1276. return -1;
  1277. }
  1278. } else {
  1279. conn->_base.state = AP_CONN_STATE_RENDDESC_WAIT;
  1280. log_info(LD_REND, "Stale descriptor %s. Refetching.",
  1281. safe_str(conn->rend_query));
  1282. rend_client_refetch_renddesc(conn->rend_query);
  1283. }
  1284. }
  1285. return 0;
  1286. }
  1287. return 0; /* unreached but keeps the compiler happy */
  1288. }
  1289. #ifdef TRANS_PF
  1290. static int pf_socket = -1;
  1291. static int
  1292. get_pf_socket(void)
  1293. {
  1294. int pf;
  1295. /* Ideally, this should be opened before dropping privs. */
  1296. if (pf_socket >= 0)
  1297. return pf_socket;
  1298. #ifdef OPENBSD
  1299. /* only works on OpenBSD */
  1300. pf = open("/dev/pf", O_RDONLY);
  1301. #else
  1302. /* works on NetBSD and FreeBSD */
  1303. pf = open("/dev/pf", O_RDWR);
  1304. #endif
  1305. if (pf < 0) {
  1306. log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
  1307. return -1;
  1308. }
  1309. pf_socket = pf;
  1310. return pf_socket;
  1311. }
  1312. #endif
  1313. /** Fetch the original destination address and port from a
  1314. * system-specific interface and put them into a
  1315. * socks_request_t as if they came from a socks request.
  1316. *
  1317. * Return -1 if an error prevents fetching the destination,
  1318. * else return 0.
  1319. */
  1320. static int
  1321. connection_ap_get_original_destination(edge_connection_t *conn,
  1322. socks_request_t *req)
  1323. {
  1324. #ifdef TRANS_NETFILTER
  1325. /* Linux 2.4+ */
  1326. struct sockaddr_in orig_dst;
  1327. socklen_t orig_dst_len = sizeof(orig_dst);
  1328. char tmpbuf[INET_NTOA_BUF_LEN];
  1329. if (getsockopt(conn->_base.s, SOL_IP, SO_ORIGINAL_DST,
  1330. (struct sockaddr*)&orig_dst, &orig_dst_len) < 0) {
  1331. int e = tor_socket_errno(conn->_base.s);
  1332. log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
  1333. return -1;
  1334. }
  1335. tor_inet_ntoa(&orig_dst.sin_addr, tmpbuf, sizeof(tmpbuf));
  1336. strlcpy(req->address, tmpbuf, sizeof(req->address));
  1337. req->port = ntohs(orig_dst.sin_port);
  1338. return 0;
  1339. #elif defined(TRANS_PF)
  1340. struct sockaddr_in proxy_addr;
  1341. socklen_t proxy_addr_len = sizeof(proxy_addr);
  1342. char tmpbuf[INET_NTOA_BUF_LEN];
  1343. struct pfioc_natlook pnl;
  1344. int pf = -1;
  1345. if (getsockname(conn->_base.s, (struct sockaddr*)&proxy_addr,
  1346. &proxy_addr_len) < 0) {
  1347. int e = tor_socket_errno(conn->_base.s);
  1348. log_warn(LD_NET, "getsockname() to determine transocks destination "
  1349. "failed: %s", tor_socket_strerror(e));
  1350. return -1;
  1351. }
  1352. memset(&pnl, 0, sizeof(pnl));
  1353. pnl.af = AF_INET;
  1354. pnl.proto = IPPROTO_TCP;
  1355. pnl.direction = PF_OUT;
  1356. pnl.saddr.v4.s_addr = htonl(conn->_base.addr);
  1357. pnl.sport = htons(conn->_base.port);
  1358. pnl.daddr.v4.s_addr = proxy_addr.sin_addr.s_addr;
  1359. pnl.dport = proxy_addr.sin_port;
  1360. pf = get_pf_socket();
  1361. if (pf<0)
  1362. return -1;
  1363. if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
  1364. log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
  1365. return -1;
  1366. }
  1367. tor_inet_ntoa(&pnl.rdaddr.v4, tmpbuf, sizeof(tmpbuf));
  1368. strlcpy(req->address, tmpbuf, sizeof(req->address));
  1369. req->port = ntohs(pnl.rdport);
  1370. return 0;
  1371. #else
  1372. (void)conn;
  1373. (void)req;
  1374. log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
  1375. "transparent proxy method was configured.");
  1376. return -1;
  1377. #endif
  1378. }
  1379. /** connection_edge_process_inbuf() found a conn in state
  1380. * socks_wait. See if conn->inbuf has the right bytes to proceed with
  1381. * the socks handshake.
  1382. *
  1383. * If the handshake is complete, send it to
  1384. * connection_ap_handshake_rewrite_and_attach().
  1385. *
  1386. * Return -1 if an unexpected error with conn occurs (and mark it for close),
  1387. * else return 0.
  1388. */
  1389. static int
  1390. connection_ap_handshake_process_socks(edge_connection_t *conn)
  1391. {
  1392. socks_request_t *socks;
  1393. int sockshere;
  1394. or_options_t *options = get_options();
  1395. tor_assert(conn);
  1396. tor_assert(conn->_base.type == CONN_TYPE_AP);
  1397. tor_assert(conn->_base.state == AP_CONN_STATE_SOCKS_WAIT);
  1398. tor_assert(conn->socks_request);
  1399. socks = conn->socks_request;
  1400. log_debug(LD_APP,"entered.");
  1401. sockshere = fetch_from_buf_socks(conn->_base.inbuf, socks,
  1402. options->TestSocks, options->SafeSocks);
  1403. if (sockshere == 0) {
  1404. if (socks->replylen) {
  1405. connection_write_to_buf(socks->reply, socks->replylen, TO_CONN(conn));
  1406. /* zero it out so we can do another round of negotiation */
  1407. socks->replylen = 0;
  1408. } else {
  1409. log_debug(LD_APP,"socks handshake not all here yet.");
  1410. }
  1411. return 0;
  1412. } else if (sockshere == -1) {
  1413. if (socks->replylen) { /* we should send reply back */
  1414. log_debug(LD_APP,"reply is already set for us. Using it.");
  1415. connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
  1416. END_STREAM_REASON_SOCKSPROTOCOL);
  1417. } else {
  1418. log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
  1419. connection_ap_handshake_socks_reply(conn, NULL, 0,
  1420. END_STREAM_REASON_SOCKSPROTOCOL);
  1421. }
  1422. connection_mark_unattached_ap(conn,
  1423. END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  1424. return -1;
  1425. } /* else socks handshake is done, continue processing */
  1426. if (hostname_is_noconnect_address(socks->address))
  1427. {
  1428. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1429. control_event_stream_status(conn, STREAM_EVENT_CLOSED, 0);
  1430. connection_mark_unattached_ap(conn, END_STREAM_REASON_DONE);
  1431. return -1;
  1432. }
  1433. if (SOCKS_COMMAND_IS_CONNECT(socks->command))
  1434. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1435. else
  1436. control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
  1437. if (options->LeaveStreamsUnattached) {
  1438. conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  1439. return 0;
  1440. }
  1441. return connection_ap_handshake_rewrite_and_attach(conn, NULL);
  1442. }
  1443. /** connection_init_accepted_conn() found a new trans AP conn.
  1444. * Get the original destination and send it to
  1445. * connection_ap_handshake_rewrite_and_attach().
  1446. *
  1447. * Return -1 if an unexpected error with conn (and it should be marked
  1448. * for close), else return 0.
  1449. */
  1450. int
  1451. connection_ap_process_transparent(edge_connection_t *conn)
  1452. {
  1453. socks_request_t *socks;
  1454. or_options_t *options = get_options();
  1455. tor_assert(conn);
  1456. tor_assert(conn->_base.type == CONN_TYPE_AP);
  1457. tor_assert(conn->socks_request);
  1458. socks = conn->socks_request;
  1459. /* pretend that a socks handshake completed so we don't try to
  1460. * send a socks reply down a transparent conn */
  1461. socks->command = SOCKS_COMMAND_CONNECT;
  1462. socks->has_finished = 1;
  1463. log_debug(LD_APP,"entered.");
  1464. if (connection_ap_get_original_destination(conn, socks) < 0) {
  1465. log_warn(LD_APP,"Fetching original destination failed. Closing.");
  1466. connection_mark_unattached_ap(conn,
  1467. END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
  1468. return -1;
  1469. }
  1470. /* we have the original destination */
  1471. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1472. if (options->LeaveStreamsUnattached) {
  1473. conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  1474. return 0;
  1475. }
  1476. return connection_ap_handshake_rewrite_and_attach(conn, NULL);
  1477. }
  1478. /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
  1479. * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
  1480. * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
  1481. * form of the original destination.
  1482. *
  1483. * If the original destination is complete, send it to
  1484. * connection_ap_handshake_rewrite_and_attach().
  1485. *
  1486. * Return -1 if an unexpected error with conn (and it should be marked
  1487. * for close), else return 0.
  1488. */
  1489. static int
  1490. connection_ap_process_natd(edge_connection_t *conn)
  1491. {
  1492. char tmp_buf[36], *tbuf, *daddr;
  1493. size_t tlen = 30;
  1494. int err, port_ok;
  1495. socks_request_t *socks;
  1496. or_options_t *options = get_options();
  1497. tor_assert(conn);
  1498. tor_assert(conn->_base.type == CONN_TYPE_AP);
  1499. tor_assert(conn->_base.state == AP_CONN_STATE_NATD_WAIT);
  1500. tor_assert(conn->socks_request);
  1501. socks = conn->socks_request;
  1502. log_debug(LD_APP,"entered.");
  1503. /* look for LF-terminated "[DEST ip_addr port]"
  1504. * where ip_addr is a dotted-quad and port is in string form */
  1505. err = fetch_from_buf_line_lf(conn->_base.inbuf, tmp_buf, &tlen);
  1506. if (err == 0)
  1507. return 0;
  1508. if (err < 0) {
  1509. log_warn(LD_APP,"Natd handshake failed (DEST too long). Closing");
  1510. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1511. return -1;
  1512. }
  1513. if (strcmpstart(tmp_buf, "[DEST ")) {
  1514. log_warn(LD_APP,"Natd handshake was ill-formed; closing. The client "
  1515. "said: %s",
  1516. escaped(tmp_buf));
  1517. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1518. return -1;
  1519. }
  1520. daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
  1521. while (*tbuf != '\0' && *tbuf != ' ')
  1522. tbuf++;
  1523. *tbuf = '\0';
  1524. tbuf++;
  1525. /* pretend that a socks handshake completed so we don't try to
  1526. * send a socks reply down a natd conn */
  1527. strlcpy(socks->address, daddr, sizeof(socks->address));
  1528. socks->port = (uint16_t)
  1529. tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
  1530. if (!port_ok) {
  1531. log_warn(LD_APP,"Natd handshake failed; port %s is ill-formed or out "
  1532. "of range.", escaped(tbuf));
  1533. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1534. return -1;
  1535. }
  1536. socks->command = SOCKS_COMMAND_CONNECT;
  1537. socks->has_finished = 1;
  1538. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1539. if (options->LeaveStreamsUnattached) {
  1540. conn->_base.state = AP_CONN_STATE_CONTROLLER_WAIT;
  1541. return 0;
  1542. }
  1543. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1544. return connection_ap_handshake_rewrite_and_attach(conn, NULL);
  1545. }
  1546. /** Iterate over the two bytes of stream_id until we get one that is not
  1547. * already in use; return it. Return 0 if can't get a unique stream_id.
  1548. */
  1549. static uint16_t
  1550. get_unique_stream_id_by_circ(origin_circuit_t *circ)
  1551. {
  1552. edge_connection_t *tmpconn;
  1553. uint16_t test_stream_id;
  1554. uint32_t attempts=0;
  1555. again:
  1556. test_stream_id = circ->next_stream_id++;
  1557. if (++attempts > 1<<16) {
  1558. /* Make sure we don't loop forever if all stream_id's are used. */
  1559. log_warn(LD_APP,"No unused stream IDs. Failing.");
  1560. return 0;
  1561. }
  1562. if (test_stream_id == 0)
  1563. goto again;
  1564. for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  1565. if (tmpconn->stream_id == test_stream_id)
  1566. goto again;
  1567. return test_stream_id;
  1568. }
  1569. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  1570. * socks_request field, and send it down circ.
  1571. *
  1572. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  1573. */
  1574. int
  1575. connection_ap_handshake_send_begin(edge_connection_t *ap_conn,
  1576. origin_circuit_t *circ)
  1577. {
  1578. char payload[CELL_PAYLOAD_SIZE];
  1579. int payload_len;
  1580. int begin_type;
  1581. tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
  1582. tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  1583. tor_assert(ap_conn->socks_request);
  1584. tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
  1585. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  1586. if (ap_conn->stream_id==0) {
  1587. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1588. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
  1589. return -1;
  1590. }
  1591. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
  1592. (circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
  1593. ap_conn->socks_request->address : "",
  1594. ap_conn->socks_request->port);
  1595. payload_len = strlen(payload)+1;
  1596. log_debug(LD_APP,
  1597. "Sending relay cell to begin stream %d.", ap_conn->stream_id);
  1598. begin_type = ap_conn->socks_request->command == SOCKS_COMMAND_CONNECT ?
  1599. RELAY_COMMAND_BEGIN : RELAY_COMMAND_BEGIN_DIR;
  1600. if (begin_type == RELAY_COMMAND_BEGIN) {
  1601. tor_assert(circ->build_state->onehop_tunnel == 0);
  1602. }
  1603. if (connection_edge_send_command(ap_conn, TO_CIRCUIT(circ), begin_type,
  1604. begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
  1605. begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0,
  1606. ap_conn->cpath_layer) < 0)
  1607. return -1; /* circuit is closed, don't continue */
  1608. ap_conn->package_window = STREAMWINDOW_START;
  1609. ap_conn->deliver_window = STREAMWINDOW_START;
  1610. ap_conn->_base.state = AP_CONN_STATE_CONNECT_WAIT;
  1611. log_info(LD_APP,"Address/port sent, ap socket %d, n_circ_id %d",
  1612. ap_conn->_base.s, circ->_base.n_circ_id);
  1613. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
  1614. return 0;
  1615. }
  1616. /** Write a relay resolve cell, using destaddr and destport from ap_conn's
  1617. * socks_request field, and send it down circ.
  1618. *
  1619. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  1620. */
  1621. int
  1622. connection_ap_handshake_send_resolve(edge_connection_t *ap_conn,
  1623. origin_circuit_t *circ)
  1624. {
  1625. int payload_len, command;
  1626. const char *string_addr;
  1627. char inaddr_buf[32];
  1628. tor_assert(ap_conn->_base.type == CONN_TYPE_AP);
  1629. tor_assert(ap_conn->_base.state == AP_CONN_STATE_CIRCUIT_WAIT);
  1630. tor_assert(ap_conn->socks_request);
  1631. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL);
  1632. command = ap_conn->socks_request->command;
  1633. tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
  1634. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  1635. if (ap_conn->stream_id==0) {
  1636. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1637. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
  1638. return -1;
  1639. }
  1640. if (command == SOCKS_COMMAND_RESOLVE) {
  1641. string_addr = ap_conn->socks_request->address;
  1642. payload_len = strlen(string_addr)+1;
  1643. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  1644. } else {
  1645. struct in_addr in;
  1646. uint32_t a;
  1647. if (tor_inet_aton(ap_conn->socks_request->address, &in) == 0) {
  1648. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1649. return -1;
  1650. }
  1651. a = ntohl(in.s_addr);
  1652. tor_snprintf(inaddr_buf, sizeof(inaddr_buf), "%d.%d.%d.%d.in-addr.arpa",
  1653. (int)(uint8_t)((a )&0xff),
  1654. (int)(uint8_t)((a>>8 )&0xff),
  1655. (int)(uint8_t)((a>>16)&0xff),
  1656. (int)(uint8_t)((a>>24)&0xff));
  1657. string_addr = inaddr_buf;
  1658. payload_len = strlen(inaddr_buf)+1;
  1659. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  1660. }
  1661. log_debug(LD_APP,
  1662. "Sending relay cell to begin stream %d.", ap_conn->stream_id);
  1663. if (connection_edge_send_command(ap_conn, TO_CIRCUIT(circ),
  1664. RELAY_COMMAND_RESOLVE,
  1665. string_addr, payload_len, ap_conn->cpath_layer) < 0)
  1666. return -1; /* circuit is closed, don't continue */
  1667. ap_conn->_base.state = AP_CONN_STATE_RESOLVE_WAIT;
  1668. log_info(LD_APP,"Address sent for resolve, ap socket %d, n_circ_id %d",
  1669. ap_conn->_base.s, circ->_base.n_circ_id);
  1670. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
  1671. return 0;
  1672. }
  1673. /** Make an AP connection_t, do a socketpair and attach one side
  1674. * to the conn, connection_add it, initialize it to circuit_wait,
  1675. * and call connection_ap_handshake_attach_circuit(conn) on it.
  1676. *
  1677. * Return the other end of the socketpair, or -1 if error.
  1678. */
  1679. int
  1680. connection_ap_make_bridge(char *address, uint16_t port,
  1681. const char *digest, int command)
  1682. {
  1683. int fd[2];
  1684. edge_connection_t *conn;
  1685. int err;
  1686. log_info(LD_APP,"Making AP bridge to %s:%d ...",safe_str(address),port);
  1687. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) < 0) {
  1688. log_warn(LD_NET,
  1689. "Couldn't construct socketpair (%s). Network down? Delaying.",
  1690. tor_socket_strerror(-err));
  1691. return -1;
  1692. }
  1693. tor_assert(fd[0] >= 0);
  1694. tor_assert(fd[1] >= 0);
  1695. set_socket_nonblocking(fd[0]);
  1696. set_socket_nonblocking(fd[1]);
  1697. conn = TO_EDGE_CONN(connection_new(CONN_TYPE_AP));
  1698. conn->_base.s = fd[0];
  1699. /* populate conn->socks_request */
  1700. /* leave version at zero, so the socks_reply is empty */
  1701. conn->socks_request->socks_version = 0;
  1702. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  1703. strlcpy(conn->socks_request->address, address,
  1704. sizeof(conn->socks_request->address));
  1705. conn->socks_request->port = port;
  1706. conn->socks_request->command = command;
  1707. if (command == SOCKS_COMMAND_CONNECT_DIR) {
  1708. conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
  1709. conn->chosen_exit_name[0] = '$';
  1710. base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
  1711. digest, DIGEST_LEN);
  1712. }
  1713. conn->_base.address = tor_strdup("(local bridge)");
  1714. conn->_base.addr = 0;
  1715. conn->_base.port = 0;
  1716. if (connection_add(TO_CONN(conn)) < 0) { /* no space, forget it */
  1717. connection_free(TO_CONN(conn)); /* this closes fd[0] */
  1718. tor_close_socket(fd[1]);
  1719. return -1;
  1720. }
  1721. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  1722. connection_start_reading(TO_CONN(conn));
  1723. /* attaching to a dirty circuit is fine */
  1724. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  1725. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1726. tor_close_socket(fd[1]);
  1727. return -1;
  1728. }
  1729. log_info(LD_APP,"... AP bridge created and connected.");
  1730. return fd[1];
  1731. }
  1732. /** Send an answer to an AP connection that has requested a DNS lookup
  1733. * via SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or
  1734. * -1 for unreachable; the answer should be in the format specified
  1735. * in the socks extensions document.
  1736. **/
  1737. void
  1738. connection_ap_handshake_socks_resolved(edge_connection_t *conn,
  1739. int answer_type,
  1740. size_t answer_len,
  1741. const char *answer,
  1742. int ttl)
  1743. {
  1744. char buf[384];
  1745. size_t replylen;
  1746. if (ttl >= 0) {
  1747. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  1748. uint32_t a = ntohl(get_uint32(answer));
  1749. if (a)
  1750. client_dns_set_addressmap(conn->socks_request->address, a,
  1751. conn->chosen_exit_name, ttl);
  1752. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  1753. char *cp = tor_strndup(answer, answer_len);
  1754. client_dns_set_reverse_addressmap(conn->socks_request->address,
  1755. cp,
  1756. conn->chosen_exit_name, ttl);
  1757. tor_free(cp);
  1758. }
  1759. }
  1760. if (conn->socks_request->socks_version == 4) {
  1761. buf[0] = 0x00; /* version */
  1762. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  1763. buf[1] = 90; /* "Granted" */
  1764. set_uint16(buf+2, 0);
  1765. memcpy(buf+4, answer, 4); /* address */
  1766. replylen = SOCKS4_NETWORK_LEN;
  1767. } else {
  1768. buf[1] = 91; /* "error" */
  1769. memset(buf+2, 0, 6);
  1770. replylen = SOCKS4_NETWORK_LEN;
  1771. }
  1772. } else {
  1773. /* SOCKS5 */
  1774. buf[0] = 0x05; /* version */
  1775. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  1776. buf[1] = SOCKS5_SUCCEEDED;
  1777. buf[2] = 0; /* reserved */
  1778. buf[3] = 0x01; /* IPv4 address type */
  1779. memcpy(buf+4, answer, 4); /* address */
  1780. set_uint16(buf+8, 0); /* port == 0. */
  1781. replylen = 10;
  1782. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  1783. buf[1] = SOCKS5_SUCCEEDED;
  1784. buf[2] = 0; /* reserved */
  1785. buf[3] = 0x04; /* IPv6 address type */
  1786. memcpy(buf+4, answer, 16); /* address */
  1787. set_uint16(buf+20, 0); /* port == 0. */
  1788. replylen = 22;
  1789. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  1790. buf[1] = SOCKS5_SUCCEEDED;
  1791. buf[2] = 0; /* reserved */
  1792. buf[3] = 0x03; /* Domainname address type */
  1793. buf[4] = (char)answer_len;
  1794. memcpy(buf+5, answer, answer_len); /* address */
  1795. set_uint16(buf+5+answer_len, 0); /* port == 0. */
  1796. replylen = 5+answer_len+2;
  1797. } else {
  1798. buf[1] = SOCKS5_HOST_UNREACHABLE;
  1799. memset(buf+2, 0, 8);
  1800. replylen = 10;
  1801. }
  1802. }
  1803. connection_ap_handshake_socks_reply(conn, buf, replylen,
  1804. (answer_type == RESOLVED_TYPE_IPV4 ||
  1805. answer_type == RESOLVED_TYPE_IPV6) ?
  1806. 0 : END_STREAM_REASON_RESOLVEFAILED);
  1807. }
  1808. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  1809. * socks version, etc, and mark <b>conn</b> as completed with SOCKS
  1810. * handshaking.
  1811. *
  1812. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it
  1813. * to conn and return, else reply based on <b>status</b>.
  1814. *
  1815. * If <b>reply</b> is undefined, <b>status</b> can't be 0.
  1816. * DOCDOC endreason
  1817. */
  1818. void
  1819. connection_ap_handshake_socks_reply(edge_connection_t *conn, char *reply,
  1820. size_t replylen, int endreason)
  1821. {
  1822. char buf[256];
  1823. socks5_reply_status_t status =
  1824. connection_edge_end_reason_socks5_response(endreason);
  1825. tor_assert(conn->socks_request); /* make sure it's an AP stream */
  1826. control_event_stream_status(conn,
  1827. status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
  1828. endreason);
  1829. if (conn->socks_request->has_finished) {
  1830. log_warn(LD_BUG, "Harmless bug: duplicate calls to "
  1831. "connection_ap_handshake_socks_reply.");
  1832. return;
  1833. }
  1834. if (replylen) { /* we already have a reply in mind */
  1835. connection_write_to_buf(reply, replylen, TO_CONN(conn));
  1836. conn->socks_request->has_finished = 1;
  1837. return;
  1838. }
  1839. if (conn->socks_request->socks_version == 4) {
  1840. memset(buf,0,SOCKS4_NETWORK_LEN);
  1841. #define SOCKS4_GRANTED 90
  1842. #define SOCKS4_REJECT 91
  1843. buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
  1844. /* leave version, destport, destip zero */
  1845. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, TO_CONN(conn));
  1846. } else if (conn->socks_request->socks_version == 5) {
  1847. buf[0] = 5; /* version 5 */
  1848. buf[1] = (char)status;
  1849. buf[2] = 0;
  1850. buf[3] = 1; /* ipv4 addr */
  1851. memset(buf+4,0,6); /* Set external addr/port to 0.
  1852. The spec doesn't seem to say what to do here. -RD */
  1853. connection_write_to_buf(buf,10,TO_CONN(conn));
  1854. }
  1855. /* If socks_version isn't 4 or 5, don't send anything.
  1856. * This can happen in the case of AP bridges. */
  1857. conn->socks_request->has_finished = 1;
  1858. return;
  1859. }
  1860. /** A relay 'begin' cell has arrived, and either we are an exit hop
  1861. * for the circuit, or we are the origin and it is a rendezvous begin.
  1862. *
  1863. * Launch a new exit connection and initialize things appropriately.
  1864. *
  1865. * If it's a rendezvous stream, call connection_exit_connect() on
  1866. * it.
  1867. *
  1868. * For general streams, call dns_resolve() on it first, and only call
  1869. * connection_exit_connect() if the dns answer is already known.
  1870. *
  1871. * Note that we don't call connection_add() on the new stream! We wait
  1872. * for connection_exit_connect() to do that.
  1873. *
  1874. * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
  1875. * Else return 0.
  1876. */
  1877. int
  1878. connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
  1879. {
  1880. edge_connection_t *n_stream;
  1881. relay_header_t rh;
  1882. char *address=NULL;
  1883. uint16_t port;
  1884. char end_payload[1];
  1885. or_circuit_t *or_circ = NULL;
  1886. assert_circuit_ok(circ);
  1887. if (!CIRCUIT_IS_ORIGIN(circ))
  1888. or_circ = TO_OR_CIRCUIT(circ);
  1889. relay_header_unpack(&rh, cell->payload);
  1890. /* Note: we have to use relay_send_command_from_edge here, not
  1891. * connection_edge_end or connection_edge_send_command, since those require
  1892. * that we have a stream connected to a circuit, and we don't connect to a
  1893. * circuit until we have a pending/successful resolve. */
  1894. if (!server_mode(get_options()) &&
  1895. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  1896. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1897. "Relay begin cell at non-server. Closing.");
  1898. end_payload[0] = END_STREAM_REASON_EXITPOLICY;
  1899. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1900. end_payload, 1, NULL);
  1901. return 0;
  1902. }
  1903. if (rh.command == RELAY_COMMAND_BEGIN) {
  1904. if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
  1905. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1906. "Relay begin cell has no \\0. Closing.");
  1907. end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
  1908. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1909. end_payload, 1, NULL);
  1910. return 0;
  1911. }
  1912. if (parse_addr_port(LOG_PROTOCOL_WARN, cell->payload+RELAY_HEADER_SIZE,
  1913. &address,NULL,&port)<0) {
  1914. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1915. "Unable to parse addr:port in relay begin cell. Closing.");
  1916. end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
  1917. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1918. end_payload, 1, NULL);
  1919. return 0;
  1920. }
  1921. if (port==0) {
  1922. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1923. "Missing port in relay begin cell. Closing.");
  1924. end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
  1925. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1926. end_payload, 1, NULL);
  1927. tor_free(address);
  1928. return 0;
  1929. }
  1930. if (or_circ && or_circ->is_first_hop) {
  1931. /* Don't let clients use us as a single-hop proxy; it attracts attackers
  1932. * and users who'd be better off with, well, single-hop proxies.
  1933. */
  1934. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1935. "Attempt to open a stream on first hop of circuit. Closing.");
  1936. end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
  1937. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1938. end_payload, 1, NULL);
  1939. tor_free(address);
  1940. return 0;
  1941. }
  1942. } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  1943. or_options_t *options = get_options();
  1944. port = options->DirPort; /* not actually used to open a connection */
  1945. if (!port || circ->purpose != CIRCUIT_PURPOSE_OR) {
  1946. end_payload[0] = END_STREAM_REASON_NOTDIRECTORY;
  1947. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1948. end_payload, 1, NULL);
  1949. return 0;
  1950. }
  1951. if (or_circ && or_circ->p_conn && or_circ->p_conn->_base.address)
  1952. address = tor_strdup(or_circ->p_conn->_base.address);
  1953. else
  1954. address = tor_strdup("127.0.0.1");
  1955. } else {
  1956. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  1957. end_payload[0] = END_STREAM_REASON_INTERNAL;
  1958. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1959. end_payload, 1, NULL);
  1960. return 0;
  1961. }
  1962. log_debug(LD_EXIT,"Creating new exit connection.");
  1963. n_stream = TO_EDGE_CONN(connection_new(CONN_TYPE_EXIT));
  1964. n_stream->_base.purpose = EXIT_PURPOSE_CONNECT;
  1965. n_stream->stream_id = rh.stream_id;
  1966. n_stream->_base.port = port;
  1967. /* leave n_stream->s at -1, because it's not yet valid */
  1968. n_stream->package_window = STREAMWINDOW_START;
  1969. n_stream->deliver_window = STREAMWINDOW_START;
  1970. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  1971. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1972. log_debug(LD_REND,"begin is for rendezvous. configuring stream.");
  1973. n_stream->_base.address = tor_strdup("(rendezvous)");
  1974. n_stream->_base.state = EXIT_CONN_STATE_CONNECTING;
  1975. strlcpy(n_stream->rend_query, origin_circ->rend_query,
  1976. sizeof(n_stream->rend_query));
  1977. tor_assert(connection_edge_is_rendezvous_stream(n_stream));
  1978. assert_circuit_ok(circ);
  1979. if (rend_service_set_connection_addr_port(n_stream, origin_circ) < 0) {
  1980. log_info(LD_REND,"Didn't find rendezvous service (port %d)",
  1981. n_stream->_base.port);
  1982. end_payload[0] = END_STREAM_REASON_EXITPOLICY;
  1983. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  1984. end_payload, 1, NULL);
  1985. connection_free(TO_CONN(n_stream));
  1986. /* knock the whole thing down, somebody screwed up */
  1987. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  1988. tor_free(address);
  1989. return 0;
  1990. }
  1991. assert_circuit_ok(circ);
  1992. log_debug(LD_REND,"Finished assigning addr/port");
  1993. n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
  1994. /* add it into the linked list of n_streams on this circuit */
  1995. n_stream->next_stream = origin_circ->p_streams;
  1996. n_stream->on_circuit = circ;
  1997. origin_circ->p_streams = n_stream;
  1998. assert_circuit_ok(circ);
  1999. connection_exit_connect(n_stream);
  2000. tor_free(address);
  2001. return 0;
  2002. }
  2003. tor_strlower(address);
  2004. n_stream->_base.address = address;
  2005. n_stream->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  2006. /* default to failed, change in dns_resolve if it turns out not to fail */
  2007. if (we_are_hibernating()) {
  2008. end_payload[0] = END_STREAM_REASON_HIBERNATING;
  2009. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  2010. end_payload, 1, NULL);
  2011. connection_free(TO_CONN(n_stream));
  2012. return 0;
  2013. }
  2014. log_debug(LD_EXIT,"about to start the dns_resolve().");
  2015. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  2016. if (or_circ && or_circ->p_conn && or_circ->p_conn->_base.addr)
  2017. n_stream->_base.addr = or_circ->p_conn->_base.addr;
  2018. n_stream->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  2019. n_stream->on_circuit = circ;
  2020. TO_OR_CIRCUIT(circ)->n_streams = n_stream;
  2021. return connection_exit_connect_dir(n_stream);
  2022. }
  2023. /* send it off to the gethostbyname farm */
  2024. switch (dns_resolve(n_stream, NULL)) {
  2025. case 1: /* resolve worked */
  2026. /* add it into the linked list of n_streams on this circuit */
  2027. n_stream->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  2028. n_stream->on_circuit = circ;
  2029. TO_OR_CIRCUIT(circ)->n_streams = n_stream;
  2030. assert_circuit_ok(circ);
  2031. log_debug(LD_EXIT,"about to call connection_exit_connect().");
  2032. connection_exit_connect(n_stream);
  2033. return 0;
  2034. case -1: /* resolve failed */
  2035. end_payload[0] = END_STREAM_REASON_RESOLVEFAILED;
  2036. relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
  2037. end_payload, 1, NULL);
  2038. /* n_stream got freed. don't touch it. */
  2039. break;
  2040. case 0: /* resolve added to pending list */
  2041. /* add it into the linked list of resolving_streams on this circuit */
  2042. n_stream->next_stream = TO_OR_CIRCUIT(circ)->resolving_streams;
  2043. n_stream->on_circuit = circ;
  2044. TO_OR_CIRCUIT(circ)->resolving_streams = n_stream;
  2045. assert_circuit_ok(circ);
  2046. ;
  2047. }
  2048. return 0;
  2049. }
  2050. /**
  2051. * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
  2052. * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
  2053. */
  2054. int
  2055. connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
  2056. {
  2057. edge_connection_t *dummy_conn;
  2058. relay_header_t rh;
  2059. assert_circuit_ok(TO_CIRCUIT(circ));
  2060. relay_header_unpack(&rh, cell->payload);
  2061. /* This 'dummy_conn' only exists to remember the stream ID
  2062. * associated with the resolve request; and to make the
  2063. * implementation of dns.c more uniform. (We really only need to
  2064. * remember the circuit, the stream ID, and the hostname to be
  2065. * resolved; but if we didn't store them in a connection like this,
  2066. * the housekeeping in dns.c would get way more complicated.)
  2067. */
  2068. dummy_conn = TO_EDGE_CONN(connection_new(CONN_TYPE_EXIT));
  2069. dummy_conn->stream_id = rh.stream_id;
  2070. dummy_conn->_base.address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
  2071. rh.length);
  2072. dummy_conn->_base.port = 0;
  2073. dummy_conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  2074. dummy_conn->_base.purpose = EXIT_PURPOSE_RESOLVE;
  2075. /* send it off to the gethostbyname farm */
  2076. switch (dns_resolve(dummy_conn, circ)) {
  2077. case -1: /* Impossible to resolve; a resolved cell was sent. */
  2078. /* Connection freed; don't touch it. */
  2079. return 0;
  2080. case 1: /* The result was cached; a resolved cell was sent. */
  2081. if (!dummy_conn->_base.marked_for_close)
  2082. connection_free(TO_CONN(dummy_conn));
  2083. return 0;
  2084. case 0: /* resolve added to pending list */
  2085. dummy_conn->next_stream = circ->resolving_streams;
  2086. dummy_conn->on_circuit = TO_CIRCUIT(circ);
  2087. circ->resolving_streams = dummy_conn;
  2088. assert_circuit_ok(TO_CIRCUIT(circ));
  2089. break;
  2090. }
  2091. return 0;
  2092. }
  2093. /** Connect to conn's specified addr and port. If it worked, conn
  2094. * has now been added to the connection_array.
  2095. *
  2096. * Send back a connected cell. Include the resolved IP of the destination
  2097. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  2098. * streams must not reveal what IP they connected to.)
  2099. */
  2100. void
  2101. connection_exit_connect(edge_connection_t *edge_conn)
  2102. {
  2103. uint32_t addr;
  2104. uint16_t port;
  2105. connection_t *conn = TO_CONN(edge_conn);
  2106. if (!connection_edge_is_rendezvous_stream(edge_conn) &&
  2107. router_compare_to_my_exit_policy(edge_conn)) {
  2108. log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
  2109. escaped_safe_str(conn->address), conn->port);
  2110. connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY,
  2111. edge_conn->cpath_layer);
  2112. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  2113. connection_free(conn);
  2114. return;
  2115. }
  2116. addr = conn->addr;
  2117. port = conn->port;
  2118. if (redirect_exit_list) {
  2119. SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, r,
  2120. {
  2121. if ((addr&r->mask)==(r->addr&r->mask) &&
  2122. (r->port_min <= port) && (port <= r->port_max)) {
  2123. struct in_addr in;
  2124. if (r->is_redirect) {
  2125. char tmpbuf[INET_NTOA_BUF_LEN];
  2126. addr = r->addr_dest;
  2127. port = r->port_dest;
  2128. in.s_addr = htonl(addr);
  2129. tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
  2130. log_debug(LD_EXIT, "Redirecting connection from %s:%d to %s:%d",
  2131. escaped_safe_str(conn->address), conn->port,
  2132. safe_str(tmpbuf), port);
  2133. }
  2134. break;
  2135. }
  2136. });
  2137. }
  2138. log_debug(LD_EXIT,"about to try connecting");
  2139. switch (connection_connect(conn, conn->address, addr, port)) {
  2140. case -1:
  2141. connection_edge_end_errno(edge_conn, edge_conn->cpath_layer);
  2142. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  2143. connection_free(conn);
  2144. return;
  2145. case 0:
  2146. conn->state = EXIT_CONN_STATE_CONNECTING;
  2147. connection_watch_events(conn, EV_WRITE | EV_READ);
  2148. /* writable indicates finish;
  2149. * readable/error indicates broken link in windowsland. */
  2150. return;
  2151. /* case 1: fall through */
  2152. }
  2153. conn->state = EXIT_CONN_STATE_OPEN;
  2154. if (connection_wants_to_flush(conn)) {
  2155. /* in case there are any queued data cells */
  2156. log_warn(LD_BUG,"Bug: newly connected conn had data waiting!");
  2157. // connection_start_writing(conn);
  2158. }
  2159. connection_watch_events(conn, EV_READ);
  2160. /* also, deliver a 'connected' cell back through the circuit. */
  2161. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  2162. /* rendezvous stream */
  2163. /* don't send an address back! */
  2164. connection_edge_send_command(edge_conn,
  2165. circuit_get_by_edge_conn(edge_conn),
  2166. RELAY_COMMAND_CONNECTED,
  2167. NULL, 0, edge_conn->cpath_layer);
  2168. } else { /* normal stream */
  2169. /* This must be the original address, not the redirected address. */
  2170. char connected_payload[8];
  2171. set_uint32(connected_payload, htonl(conn->addr));
  2172. set_uint32(connected_payload+4,
  2173. htonl(dns_clip_ttl(edge_conn->address_ttl)));
  2174. connection_edge_send_command(edge_conn,
  2175. circuit_get_by_edge_conn(edge_conn),
  2176. RELAY_COMMAND_CONNECTED,
  2177. connected_payload, 8, edge_conn->cpath_layer);
  2178. }
  2179. }
  2180. /** Given an exit conn that should attach to us as a directory server, open a
  2181. * bridge connection with a socketpair, create a new directory conn, and join
  2182. * them together. Return 0 on success (or if there was an error we could send
  2183. * back an end cell for). Return -(some circuit end reason) if the circuit
  2184. * needs to be torn down. Either connects exit_conn, frees it, or marks it,
  2185. * as appropriate.
  2186. */
  2187. static int
  2188. connection_exit_connect_dir(edge_connection_t *exit_conn)
  2189. {
  2190. int fd[2];
  2191. int err;
  2192. dir_connection_t *dir_conn = NULL;
  2193. log_info(LD_EXIT, "Opening dir bridge");
  2194. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) < 0) {
  2195. log_warn(LD_NET,
  2196. "Couldn't construct socketpair (%s). "
  2197. "Network down? Out of sockets?",
  2198. tor_socket_strerror(-err));
  2199. connection_edge_end(exit_conn, END_STREAM_REASON_RESOURCELIMIT,
  2200. exit_conn->cpath_layer);
  2201. connection_free(TO_CONN(exit_conn));
  2202. return 0;
  2203. }
  2204. tor_assert(fd[0] >= 0);
  2205. tor_assert(fd[1] >= 0);
  2206. set_socket_nonblocking(fd[0]);
  2207. set_socket_nonblocking(fd[1]);
  2208. exit_conn->_base.s = fd[0];
  2209. exit_conn->_base.state = EXIT_CONN_STATE_OPEN;
  2210. dir_conn = TO_DIR_CONN(connection_new(CONN_TYPE_DIR));
  2211. dir_conn->_base.s = fd[1];
  2212. dir_conn->_base.addr = 0x7f000001;
  2213. dir_conn->_base.port = 0;
  2214. dir_conn->_base.address = tor_strdup("Tor network");
  2215. dir_conn->_base.type = CONN_TYPE_DIR;
  2216. dir_conn->_base.purpose = DIR_PURPOSE_SERVER;
  2217. dir_conn->_base.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  2218. if (connection_add(TO_CONN(exit_conn))<0) {
  2219. connection_edge_end(exit_conn, END_STREAM_REASON_RESOURCELIMIT,
  2220. exit_conn->cpath_layer);
  2221. connection_free(TO_CONN(exit_conn));
  2222. connection_free(TO_CONN(dir_conn));
  2223. return 0;
  2224. }
  2225. if (connection_add(TO_CONN(dir_conn))<0) {
  2226. connection_edge_end(exit_conn, END_STREAM_REASON_RESOURCELIMIT,
  2227. exit_conn->cpath_layer);
  2228. connection_close_immediate(TO_CONN(exit_conn));
  2229. connection_mark_for_close(TO_CONN(exit_conn));
  2230. connection_free(TO_CONN(dir_conn));
  2231. return 0;
  2232. }
  2233. connection_start_reading(TO_CONN(dir_conn));
  2234. connection_start_reading(TO_CONN(exit_conn));
  2235. if (connection_edge_send_command(exit_conn,
  2236. circuit_get_by_edge_conn(exit_conn),
  2237. RELAY_COMMAND_CONNECTED, NULL, 0,
  2238. exit_conn->cpath_layer) < 0) {
  2239. connection_mark_for_close(TO_CONN(exit_conn));
  2240. connection_mark_for_close(TO_CONN(dir_conn));
  2241. return 0;
  2242. }
  2243. return 0;
  2244. }
  2245. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  2246. * it is a general stream.
  2247. */
  2248. int
  2249. connection_edge_is_rendezvous_stream(edge_connection_t *conn)
  2250. {
  2251. tor_assert(conn);
  2252. if (*conn->rend_query) /* XXX */
  2253. return 1;
  2254. return 0;
  2255. }
  2256. /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
  2257. * to exit from it, or 0 if it probably will not allow it.
  2258. * (We might be uncertain if conn's destination address has not yet been
  2259. * resolved.)
  2260. */
  2261. int
  2262. connection_ap_can_use_exit(edge_connection_t *conn, routerinfo_t *exit)
  2263. {
  2264. tor_assert(conn);
  2265. tor_assert(conn->_base.type == CONN_TYPE_AP);
  2266. tor_assert(conn->socks_request);
  2267. tor_assert(exit);
  2268. /* If a particular exit node has been requested for the new connection,
  2269. * make sure the exit node of the existing circuit matches exactly.
  2270. */
  2271. if (conn->chosen_exit_name) {
  2272. if (router_get_by_nickname(conn->chosen_exit_name, 1) != exit) {
  2273. /* doesn't match */
  2274. // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
  2275. // conn->chosen_exit_name, exit->nickname);
  2276. return 0;
  2277. }
  2278. }
  2279. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  2280. struct in_addr in;
  2281. uint32_t addr = 0;
  2282. addr_policy_result_t r;
  2283. if (tor_inet_aton(conn->socks_request->address, &in))
  2284. addr = ntohl(in.s_addr);
  2285. r = compare_addr_to_addr_policy(addr, conn->socks_request->port,
  2286. exit->exit_policy);
  2287. if (r == ADDR_POLICY_REJECTED || r == ADDR_POLICY_PROBABLY_REJECTED)
  2288. return 0;
  2289. } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
  2290. /* Can't support reverse lookups without eventdns. */
  2291. if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR &&
  2292. exit->has_old_dnsworkers)
  2293. return 0;
  2294. /* Don't send DNS requests to non-exit servers by default. */
  2295. if (!conn->chosen_exit_name && policy_is_reject_star(exit->exit_policy))
  2296. return 0;
  2297. }
  2298. return 1;
  2299. }
  2300. /** Make connection redirection follow the provided list of
  2301. * exit_redirect_t */
  2302. void
  2303. set_exit_redirects(smartlist_t *lst)
  2304. {
  2305. if (redirect_exit_list) {
  2306. SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, p, tor_free(p));
  2307. smartlist_free(redirect_exit_list);
  2308. }
  2309. redirect_exit_list = lst;
  2310. }
  2311. /** If address is of the form "y.onion" with a well-formed handle y:
  2312. * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
  2313. *
  2314. * If address is of the form "y.exit":
  2315. * Put a NUL after y and return EXIT_HOSTNAME.
  2316. *
  2317. * Otherwise:
  2318. * Return NORMAL_HOSTNAME and change nothing.
  2319. */
  2320. hostname_type_t
  2321. parse_extended_hostname(char *address)
  2322. {
  2323. char *s;
  2324. char query[REND_SERVICE_ID_LEN+1];
  2325. s = strrchr(address,'.');
  2326. if (!s)
  2327. return NORMAL_HOSTNAME; /* no dot, thus normal */
  2328. if (!strcmp(s+1,"exit")) {
  2329. *s = 0; /* nul-terminate it */
  2330. return EXIT_HOSTNAME; /* .exit */
  2331. }
  2332. if (strcmp(s+1,"onion"))
  2333. return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
  2334. /* so it is .onion */
  2335. *s = 0; /* nul-terminate it */
  2336. if (strlcpy(query, address, REND_SERVICE_ID_LEN+1) >=
  2337. REND_SERVICE_ID_LEN+1)
  2338. goto failed;
  2339. if (rend_valid_service_id(query)) {
  2340. return ONION_HOSTNAME; /* success */
  2341. }
  2342. failed:
  2343. /* otherwise, return to previous state and return 0 */
  2344. *s = '.';
  2345. return BAD_HOSTNAME;
  2346. }
  2347. /** Check if the address is of the form "y.noconnect"
  2348. */
  2349. static int
  2350. hostname_is_noconnect_address(const char *address)
  2351. {
  2352. return ! strcasecmpend(address, ".noconnect");
  2353. }