connection_edge.c 105 KB

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