connection_edge.c 105 KB

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