connection_edge.c 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634
  1. /* Copyright 2001 Matej Pfajfar, 2001-2004 Roger Dingledine. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * \file connection_edge.c
  6. * \brief Handle edge streams and relay cells.
  7. **/
  8. #include "or.h"
  9. #include "tree.h"
  10. extern or_options_t options; /* command-line and config-file options */
  11. extern char *conn_state_to_string[][_CONN_TYPE_MAX+1]; /* from connection.c */
  12. static int connection_ap_handshake_process_socks(connection_t *conn);
  13. static int connection_exit_begin_conn(cell_t *cell, circuit_t *circ);
  14. static void connection_edge_consider_sending_sendme(connection_t *conn);
  15. static uint32_t client_dns_lookup_entry(const char *address);
  16. static void client_dns_set_entry(const char *address, uint32_t val);
  17. static int client_dns_incr_failures(const char *address);
  18. /** Pack the relay_header_t host-order structure <b>src</b> into
  19. * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
  20. * about the wire format.
  21. */
  22. void relay_header_pack(char *dest, const relay_header_t *src) {
  23. *(uint8_t*)(dest) = src->command;
  24. set_uint16(dest+1, htons(src->recognized));
  25. set_uint16(dest+3, htons(src->stream_id));
  26. memcpy(dest+5, src->integrity, 4);
  27. set_uint16(dest+9, htons(src->length));
  28. }
  29. /** Unpack the network-order buffer <b>src</b> into a host-order
  30. * relay_header_t structure <b>dest</b>.
  31. */
  32. void relay_header_unpack(relay_header_t *dest, const char *src) {
  33. dest->command = *(uint8_t*)(src);
  34. dest->recognized = ntohs(get_uint16(src+1));
  35. dest->stream_id = ntohs(get_uint16(src+3));
  36. memcpy(dest->integrity, src+5, 4);
  37. dest->length = ntohs(get_uint16(src+9));
  38. }
  39. /** Handle new bytes on conn->inbuf, or notification of eof.
  40. *
  41. * If there was an EOF, then send an end and mark the connection
  42. * for close.
  43. *
  44. * Otherwise handle it based on state:
  45. * - If it's waiting for socks info, try to read another step of the
  46. * socks handshake out of conn->inbuf.
  47. * - If it's open, then package more relay cells from the stream.
  48. * - Else, leave the bytes on inbuf alone for now.
  49. *
  50. * Mark and return -1 if there was an unexpected error with the conn,
  51. * else return 0.
  52. */
  53. int connection_edge_process_inbuf(connection_t *conn) {
  54. tor_assert(conn);
  55. tor_assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
  56. if(conn->inbuf_reached_eof) {
  57. #ifdef HALF_OPEN
  58. /* eof reached; we're done reading, but we might want to write more. */
  59. conn->done_receiving = 1;
  60. shutdown(conn->s, 0); /* XXX check return, refactor NM */
  61. if (conn->done_sending) {
  62. connection_mark_for_close(conn, END_STREAM_REASON_DONE);
  63. } else {
  64. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_END,
  65. NULL, 0, conn->cpath_layer);
  66. }
  67. return 0;
  68. #else
  69. /* eof reached, kill it. */
  70. log_fn(LOG_INFO,"conn (fd %d) reached eof. Closing.", conn->s);
  71. connection_mark_for_close(conn, END_STREAM_REASON_DONE);
  72. conn->hold_open_until_flushed = 1; /* just because we shouldn't read
  73. doesn't mean we shouldn't write */
  74. return 0;
  75. #endif
  76. }
  77. switch(conn->state) {
  78. case AP_CONN_STATE_SOCKS_WAIT:
  79. if(connection_ap_handshake_process_socks(conn) < 0) {
  80. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  81. conn->hold_open_until_flushed = 1;
  82. return -1;
  83. }
  84. return 0;
  85. case AP_CONN_STATE_OPEN:
  86. case EXIT_CONN_STATE_OPEN:
  87. if(conn->package_window <= 0) {
  88. /* XXX this is still getting called rarely :( */
  89. log_fn(LOG_WARN,"called with package_window %d. Tell Roger.", conn->package_window);
  90. return 0;
  91. }
  92. if(connection_edge_package_raw_inbuf(conn) < 0) {
  93. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  94. return -1;
  95. }
  96. return 0;
  97. case EXIT_CONN_STATE_CONNECTING:
  98. case AP_CONN_STATE_RENDDESC_WAIT:
  99. case AP_CONN_STATE_CIRCUIT_WAIT:
  100. case AP_CONN_STATE_CONNECT_WAIT:
  101. log_fn(LOG_INFO,"data from edge while in '%s' state. Leaving it on buffer.",
  102. conn_state_to_string[conn->type][conn->state]);
  103. return 0;
  104. }
  105. log_fn(LOG_WARN,"Got unexpected state %d. Closing.",conn->state);
  106. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  107. return -1;
  108. }
  109. /** This edge needs to be closed, because its circuit has closed.
  110. * Mark it for close and return 0.
  111. */
  112. int connection_edge_destroy(uint16_t circ_id, connection_t *conn) {
  113. tor_assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
  114. if(conn->marked_for_close)
  115. return 0; /* already marked; probably got an 'end' */
  116. log_fn(LOG_INFO,"CircID %d: At an edge. Marking connection for close.",
  117. circ_id);
  118. conn->has_sent_end = 1; /* we're closing the circuit, nothing to send to */
  119. connection_mark_for_close(conn, END_STREAM_REASON_DESTROY);
  120. conn->hold_open_until_flushed = 1;
  121. return 0;
  122. }
  123. /** Translate the <b>payload</b> of length <b>length</b>, which
  124. * came from a relay 'end' cell, into a static const string describing
  125. * why the stream is closing.
  126. */
  127. static const char *
  128. connection_edge_end_reason(char *payload, uint16_t length) {
  129. if(length < 1) {
  130. log_fn(LOG_WARN,"End cell arrived with length 0. Should be at least 1.");
  131. return "MALFORMED";
  132. }
  133. if(*payload < _MIN_END_STREAM_REASON || *payload > _MAX_END_STREAM_REASON) {
  134. log_fn(LOG_WARN,"Reason for ending (%d) not recognized.",*payload);
  135. return "MALFORMED";
  136. }
  137. switch(*payload) {
  138. case END_STREAM_REASON_MISC: return "misc error";
  139. case END_STREAM_REASON_RESOLVEFAILED: return "resolve failed";
  140. case END_STREAM_REASON_CONNECTFAILED: return "connect failed";
  141. case END_STREAM_REASON_EXITPOLICY: return "exit policy failed";
  142. case END_STREAM_REASON_DESTROY: return "destroyed";
  143. case END_STREAM_REASON_DONE: return "closed normally";
  144. case END_STREAM_REASON_TIMEOUT: return "gave up (timeout)";
  145. }
  146. tor_assert(0);
  147. return "";
  148. }
  149. /** Send a relay end cell from stream <b>conn</b> to conn's circuit,
  150. * with a destination of cpath_layer. (If cpath_layer is NULL, the
  151. * destination is the circuit's origin.) Mark the relay end cell as
  152. * closing because of <b>reason</b>.
  153. *
  154. * Return -1 if this function has already been called on this conn,
  155. * else return 0.
  156. */
  157. int connection_edge_end(connection_t *conn, char reason, crypt_path_t *cpath_layer) {
  158. char payload[5];
  159. int payload_len=1;
  160. circuit_t *circ;
  161. if(conn->has_sent_end) {
  162. log_fn(LOG_WARN,"It appears I've already sent the end. Are you calling me twice?");
  163. return -1;
  164. }
  165. payload[0] = reason;
  166. if(reason == END_STREAM_REASON_EXITPOLICY) {
  167. /* this is safe even for rend circs, because they never fail
  168. * because of exitpolicy */
  169. set_uint32(payload+1, htonl(conn->addr));
  170. payload_len += 4;
  171. }
  172. circ = circuit_get_by_conn(conn);
  173. if(circ && !circ->marked_for_close) {
  174. log_fn(LOG_DEBUG,"Marking conn (fd %d) and sending end.",conn->s);
  175. connection_edge_send_command(conn, circ, RELAY_COMMAND_END,
  176. payload, payload_len, cpath_layer);
  177. } else {
  178. log_fn(LOG_DEBUG,"Marking conn (fd %d); no circ to send end.",conn->s);
  179. }
  180. conn->has_sent_end = 1;
  181. return 0;
  182. }
  183. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
  184. * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
  185. * that's sending the relay cell, or NULL if it's a control cell.
  186. * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
  187. * for OP->OR cells.
  188. *
  189. * If you can't send the cell, mark the circuit for close and
  190. * return -1. Else return 0.
  191. */
  192. int connection_edge_send_command(connection_t *fromconn, circuit_t *circ,
  193. int relay_command, const char *payload,
  194. int payload_len, crypt_path_t *cpath_layer) {
  195. cell_t cell;
  196. relay_header_t rh;
  197. int cell_direction;
  198. if(!circ) {
  199. log_fn(LOG_WARN,"no circ. Closing conn.");
  200. tor_assert(fromconn);
  201. connection_mark_for_close(fromconn, 0);
  202. return -1;
  203. }
  204. memset(&cell, 0, sizeof(cell_t));
  205. cell.command = CELL_RELAY;
  206. if(cpath_layer) {
  207. cell.circ_id = circ->n_circ_id;
  208. cell_direction = CELL_DIRECTION_OUT;
  209. } else {
  210. cell.circ_id = circ->p_circ_id;
  211. cell_direction = CELL_DIRECTION_IN;
  212. }
  213. memset(&rh, 0, sizeof(rh));
  214. rh.command = relay_command;
  215. if(fromconn)
  216. rh.stream_id = fromconn->stream_id; /* else it's 0 */
  217. rh.length = payload_len;
  218. relay_header_pack(cell.payload, &rh);
  219. if(payload_len)
  220. memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
  221. log_fn(LOG_DEBUG,"delivering %d cell %s.", relay_command,
  222. cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
  223. if(circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer) < 0) {
  224. log_fn(LOG_WARN,"circuit_package_relay_cell failed. Closing.");
  225. circuit_mark_for_close(circ);
  226. return -1;
  227. }
  228. return 0;
  229. }
  230. /** How many times will I retry a stream that fails due to DNS
  231. * resolve failure?
  232. */
  233. #define MAX_RESOLVE_FAILURES 3
  234. /** An incoming relay cell has arrived from circuit <b>circ</b> to
  235. * stream <b>conn</b>.
  236. *
  237. * The arguments here are the same as in
  238. * connection_edge_process_relay_cell() below; this function is called
  239. * from there when <b>conn</b> is defined and not in an open state.
  240. */
  241. static int
  242. connection_edge_process_relay_cell_not_open(
  243. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  244. connection_t *conn, crypt_path_t *layer_hint) {
  245. uint32_t addr;
  246. int reason;
  247. if(rh->command == RELAY_COMMAND_END) {
  248. reason = *(cell->payload+RELAY_HEADER_SIZE);
  249. /* We have to check this here, since we aren't connected yet. */
  250. if (rh->length >= 5 && reason == END_STREAM_REASON_EXITPOLICY) {
  251. log_fn(LOG_INFO,"Address %s refused due to exit policy. Retrying.",
  252. conn->socks_request->address);
  253. addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  254. client_dns_set_entry(conn->socks_request->address, addr);
  255. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  256. circuit_detach_stream(circ,conn);
  257. if(connection_ap_handshake_attach_circuit(conn) >= 0)
  258. return 0;
  259. log_fn(LOG_INFO,"Giving up on retrying (from exitpolicy); conn can't be handled.");
  260. /* else, conn will get closed below */
  261. } else if (rh->length && reason == END_STREAM_REASON_RESOLVEFAILED) {
  262. if (client_dns_incr_failures(conn->socks_request->address)
  263. < MAX_RESOLVE_FAILURES) {
  264. /* We haven't retried too many times; reattach the connection. */
  265. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  266. circuit_detach_stream(circ,conn);
  267. if(connection_ap_handshake_attach_circuit(conn) >= 0)
  268. return 0;
  269. /* else, conn will get closed below */
  270. log_fn(LOG_INFO,"Giving up on retrying (from resolvefailed); conn can't be handled.");
  271. } else {
  272. log_fn(LOG_WARN,"Have tried resolving address %s at %d different places. Giving up.",
  273. conn->socks_request->address, MAX_RESOLVE_FAILURES);
  274. }
  275. }
  276. log_fn(LOG_INFO,"Edge got end (%s) before we're connected. Marking for close.",
  277. connection_edge_end_reason(cell->payload+RELAY_HEADER_SIZE, rh->length));
  278. if(CIRCUIT_IS_ORIGIN(circ))
  279. circuit_log_path(LOG_INFO,circ);
  280. conn->has_sent_end = 1; /* we just got an 'end', don't need to send one */
  281. connection_mark_for_close(conn, 0);
  282. return 0;
  283. }
  284. if(conn->type == CONN_TYPE_AP && rh->command == RELAY_COMMAND_CONNECTED) {
  285. if(conn->state != AP_CONN_STATE_CONNECT_WAIT) {
  286. log_fn(LOG_WARN,"Got 'connected' while not in state connect_wait. Dropping.");
  287. return 0;
  288. }
  289. // log_fn(LOG_INFO,"Connected! Notifying application.");
  290. conn->state = AP_CONN_STATE_OPEN;
  291. if (rh->length >= 4) {
  292. addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  293. client_dns_set_entry(conn->socks_request->address, addr);
  294. }
  295. log_fn(LOG_INFO,"'connected' received after %d seconds.",
  296. (int)(time(NULL) - conn->timestamp_lastread));
  297. circuit_log_path(LOG_INFO,circ);
  298. connection_ap_handshake_socks_reply(conn, NULL, 0, 1);
  299. conn->socks_request->has_finished = 1;
  300. /* handle anything that might have queued */
  301. if (connection_edge_package_raw_inbuf(conn) < 0) {
  302. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  303. return 0;
  304. }
  305. return 0;
  306. }
  307. log_fn(LOG_WARN,"Got an unexpected relay command %d, in state %d (%s). Closing.",
  308. rh->command, conn->state, conn_state_to_string[conn->type][conn->state]);
  309. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  310. return -1;
  311. }
  312. /** An incoming relay cell has arrived on circuit <b>circ</b>. If
  313. * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
  314. * destined for <b>conn</b>.
  315. *
  316. * If <b>layer_hint</b> is defined, then we're the origin of the
  317. * circuit, and it specifies the hop that packaged <b>cell</b>.
  318. *
  319. * Return -1 if you want to tear down the circuit, else 0.
  320. */
  321. int connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  322. connection_t *conn,
  323. crypt_path_t *layer_hint) {
  324. static int num_seen=0;
  325. relay_header_t rh;
  326. tor_assert(cell && circ);
  327. relay_header_unpack(&rh, cell->payload);
  328. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  329. num_seen++;
  330. log_fn(LOG_DEBUG,"Now seen %d relay cells here.", num_seen);
  331. /* either conn is NULL, in which case we've got a control cell, or else
  332. * conn points to the recognized stream. */
  333. if(conn &&
  334. conn->state != AP_CONN_STATE_OPEN &&
  335. conn->state != EXIT_CONN_STATE_OPEN) {
  336. return connection_edge_process_relay_cell_not_open(
  337. &rh, cell, circ, conn, layer_hint);
  338. }
  339. switch(rh.command) {
  340. case RELAY_COMMAND_DROP:
  341. log_fn(LOG_INFO,"Got a relay-level padding cell. Dropping.");
  342. return 0;
  343. case RELAY_COMMAND_BEGIN:
  344. if (layer_hint &&
  345. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  346. log_fn(LOG_WARN,"relay begin request unsupported at AP. Dropping.");
  347. return 0;
  348. }
  349. if(conn) {
  350. log_fn(LOG_WARN,"begin cell for known stream. Dropping.");
  351. return 0;
  352. }
  353. connection_exit_begin_conn(cell, circ);
  354. return 0;
  355. case RELAY_COMMAND_DATA:
  356. ++stats_n_data_cells_received;
  357. if((layer_hint && --layer_hint->deliver_window < 0) ||
  358. (!layer_hint && --circ->deliver_window < 0)) {
  359. log_fn(LOG_WARN,"(relay data) circ deliver_window below 0. Killing.");
  360. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  361. return -1;
  362. }
  363. log_fn(LOG_DEBUG,"circ deliver_window now %d.", layer_hint ?
  364. layer_hint->deliver_window : circ->deliver_window);
  365. circuit_consider_sending_sendme(circ, layer_hint);
  366. if(!conn) {
  367. log_fn(LOG_INFO,"data cell dropped, unknown stream.");
  368. return 0;
  369. }
  370. if(--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  371. log_fn(LOG_WARN,"(relay data) conn deliver_window below 0. Killing.");
  372. return -1; /* somebody's breaking protocol. kill the whole circuit. */
  373. }
  374. stats_n_data_bytes_received += rh.length;
  375. connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
  376. rh.length, conn);
  377. connection_edge_consider_sending_sendme(conn);
  378. return 0;
  379. case RELAY_COMMAND_END:
  380. if(!conn) {
  381. log_fn(LOG_INFO,"end cell (%s) dropped, unknown stream.",
  382. connection_edge_end_reason(cell->payload+RELAY_HEADER_SIZE, rh.length));
  383. return 0;
  384. }
  385. /* XXX add to this log_fn the exit node's nickname? */
  386. log_fn(LOG_INFO,"end cell (%s) for stream %d. Removing stream.",
  387. connection_edge_end_reason(cell->payload+RELAY_HEADER_SIZE, rh.length),
  388. conn->stream_id);
  389. #ifdef HALF_OPEN
  390. conn->done_sending = 1;
  391. shutdown(conn->s, 1); /* XXX check return; refactor NM */
  392. if (conn->done_receiving) {
  393. /* We just *got* an end; no reason to send one. */
  394. conn->has_sent_end = 1;
  395. connection_mark_for_close(conn, 0);
  396. conn->hold_open_until_flushed = 1;
  397. }
  398. #else
  399. /* We just *got* an end; no reason to send one. */
  400. conn->has_sent_end = 1;
  401. connection_mark_for_close(conn, 0);
  402. conn->hold_open_until_flushed = 1;
  403. #endif
  404. return 0;
  405. case RELAY_COMMAND_EXTEND:
  406. if(conn) {
  407. log_fn(LOG_WARN,"'extend' for non-zero stream. Dropping.");
  408. return 0;
  409. }
  410. return circuit_extend(cell, circ);
  411. case RELAY_COMMAND_EXTENDED:
  412. if(!layer_hint) {
  413. log_fn(LOG_WARN,"'extended' unsupported at non-origin. Dropping.");
  414. return 0;
  415. }
  416. log_fn(LOG_DEBUG,"Got an extended cell! Yay.");
  417. if(circuit_finish_handshake(circ, cell->payload+RELAY_HEADER_SIZE) < 0) {
  418. log_fn(LOG_WARN,"circuit_finish_handshake failed.");
  419. return -1;
  420. }
  421. if (circuit_send_next_onion_skin(circ)<0) {
  422. log_fn(LOG_INFO,"circuit_send_next_onion_skin() failed.");
  423. return -1;
  424. }
  425. return 0;
  426. case RELAY_COMMAND_TRUNCATE:
  427. if(layer_hint) {
  428. log_fn(LOG_WARN,"'truncate' unsupported at origin. Dropping.");
  429. return 0;
  430. }
  431. if(circ->n_conn) {
  432. connection_send_destroy(circ->n_circ_id, circ->n_conn);
  433. circ->n_conn = NULL;
  434. }
  435. log_fn(LOG_DEBUG, "Processed 'truncate', replying.");
  436. connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
  437. NULL, 0, NULL);
  438. return 0;
  439. case RELAY_COMMAND_TRUNCATED:
  440. if(!layer_hint) {
  441. log_fn(LOG_WARN,"'truncated' unsupported at non-origin. Dropping.");
  442. return 0;
  443. }
  444. circuit_truncated(circ, layer_hint);
  445. return 0;
  446. case RELAY_COMMAND_CONNECTED:
  447. if(conn) {
  448. log_fn(LOG_WARN,"'connected' unsupported while open. Closing circ.");
  449. return -1;
  450. }
  451. log_fn(LOG_INFO,"'connected' received, no conn attached anymore. Ignoring.");
  452. return 0;
  453. case RELAY_COMMAND_SENDME:
  454. if(!conn) {
  455. if(layer_hint) {
  456. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  457. log_fn(LOG_DEBUG,"circ-level sendme at origin, packagewindow %d.",
  458. layer_hint->package_window);
  459. circuit_resume_edge_reading(circ, layer_hint);
  460. } else {
  461. circ->package_window += CIRCWINDOW_INCREMENT;
  462. log_fn(LOG_DEBUG,"circ-level sendme at non-origin, packagewindow %d.",
  463. circ->package_window);
  464. circuit_resume_edge_reading(circ, layer_hint);
  465. }
  466. return 0;
  467. }
  468. conn->package_window += STREAMWINDOW_INCREMENT;
  469. log_fn(LOG_DEBUG,"stream-level sendme, packagewindow now %d.", conn->package_window);
  470. connection_start_reading(conn);
  471. connection_edge_package_raw_inbuf(conn); /* handle whatever might still be on the inbuf */
  472. return 0;
  473. case RELAY_COMMAND_ESTABLISH_INTRO:
  474. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  475. case RELAY_COMMAND_INTRODUCE1:
  476. case RELAY_COMMAND_INTRODUCE2:
  477. case RELAY_COMMAND_INTRODUCE_ACK:
  478. case RELAY_COMMAND_RENDEZVOUS1:
  479. case RELAY_COMMAND_RENDEZVOUS2:
  480. case RELAY_COMMAND_INTRO_ESTABLISHED:
  481. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  482. rend_process_relay_cell(circ, rh.command, rh.length,
  483. cell->payload+RELAY_HEADER_SIZE);
  484. return 0;
  485. }
  486. log_fn(LOG_WARN,"unknown relay command %d.",rh.command);
  487. return -1;
  488. }
  489. /** Connection <b>conn</b> has finished writing and has no bytes left on
  490. * its outbuf.
  491. *
  492. * If it's in state 'connecting', then take a look at the socket, and
  493. * take appropriate actions (such as sending back a relay 'connected'
  494. * cell) if the connect succeeded.
  495. *
  496. * If it's in state 'open', stop writing, consider responding with a
  497. * sendme, and return.
  498. * Otherwise, stop writing and return.
  499. *
  500. * If <b>conn</b> is broken, mark it for close and return -1, else
  501. * return 0.
  502. */
  503. int connection_edge_finished_flushing(connection_t *conn) {
  504. unsigned char connected_payload[4];
  505. int e, len=sizeof(e);
  506. tor_assert(conn);
  507. tor_assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
  508. switch(conn->state) {
  509. case EXIT_CONN_STATE_CONNECTING:
  510. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) { /* not yet */
  511. if(!ERRNO_IS_CONN_EINPROGRESS(tor_socket_errno(conn->s))) {
  512. /* yuck. kill it. */
  513. log_fn(LOG_DEBUG,"in-progress exit connect failed. Removing.");
  514. connection_mark_for_close(conn, END_STREAM_REASON_CONNECTFAILED);
  515. return -1;
  516. } else {
  517. log_fn(LOG_DEBUG,"in-progress exit connect still waiting.");
  518. return 0; /* no change, see if next time is better */
  519. }
  520. }
  521. /* the connect has finished. */
  522. log_fn(LOG_INFO,"Exit connection to %s:%u established.",
  523. conn->address,conn->port);
  524. conn->state = EXIT_CONN_STATE_OPEN;
  525. connection_watch_events(conn, POLLIN); /* stop writing, continue reading */
  526. if(connection_wants_to_flush(conn)) /* in case there are any queued relay cells */
  527. connection_start_writing(conn);
  528. /* deliver a 'connected' relay cell back through the circuit. */
  529. if(connection_edge_is_rendezvous_stream(conn)) {
  530. if(connection_edge_send_command(conn, circuit_get_by_conn(conn),
  531. RELAY_COMMAND_CONNECTED, NULL, 0, conn->cpath_layer) < 0)
  532. return 0; /* circuit is closed, don't continue */
  533. } else {
  534. *(uint32_t*)connected_payload = htonl(conn->addr);
  535. if(connection_edge_send_command(conn, circuit_get_by_conn(conn),
  536. RELAY_COMMAND_CONNECTED, connected_payload, 4, conn->cpath_layer) < 0)
  537. return 0; /* circuit is closed, don't continue */
  538. }
  539. tor_assert(conn->package_window > 0);
  540. return connection_edge_process_inbuf(conn); /* in case the server has written anything */
  541. case AP_CONN_STATE_OPEN:
  542. case EXIT_CONN_STATE_OPEN:
  543. connection_stop_writing(conn);
  544. connection_edge_consider_sending_sendme(conn);
  545. return 0;
  546. case AP_CONN_STATE_SOCKS_WAIT:
  547. case AP_CONN_STATE_RENDDESC_WAIT:
  548. case AP_CONN_STATE_CIRCUIT_WAIT:
  549. case AP_CONN_STATE_CONNECT_WAIT:
  550. connection_stop_writing(conn);
  551. return 0;
  552. default:
  553. log_fn(LOG_WARN,"BUG: called in unexpected state %d.", conn->state);
  554. return -1;
  555. }
  556. return 0;
  557. }
  558. uint64_t stats_n_data_cells_packaged = 0;
  559. uint64_t stats_n_data_bytes_packaged = 0;
  560. uint64_t stats_n_data_cells_received = 0;
  561. uint64_t stats_n_data_bytes_received = 0;
  562. /** While conn->inbuf has an entire relay payload of bytes on it,
  563. * and the appropriate package windows aren't empty, grab a cell
  564. * and send it down the circuit.
  565. *
  566. * Return -1 if conn should be marked for close, else return 0.
  567. */
  568. int connection_edge_package_raw_inbuf(connection_t *conn) {
  569. int amount_to_process, length;
  570. char payload[CELL_PAYLOAD_SIZE];
  571. circuit_t *circ;
  572. tor_assert(conn);
  573. tor_assert(!connection_speaks_cells(conn));
  574. repeat_connection_edge_package_raw_inbuf:
  575. circ = circuit_get_by_conn(conn);
  576. if(!circ) {
  577. log_fn(LOG_INFO,"conn has no circuits! Closing.");
  578. return -1;
  579. }
  580. if(circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
  581. return 0;
  582. if(conn->package_window <= 0) {
  583. log_fn(LOG_WARN,"called with package_window %d. Tell Roger.", conn->package_window);
  584. connection_stop_reading(conn);
  585. return 0;
  586. }
  587. amount_to_process = buf_datalen(conn->inbuf);
  588. if(!amount_to_process)
  589. return 0;
  590. if(amount_to_process > RELAY_PAYLOAD_SIZE) {
  591. length = RELAY_PAYLOAD_SIZE;
  592. } else {
  593. length = amount_to_process;
  594. }
  595. stats_n_data_bytes_packaged += length;
  596. stats_n_data_cells_packaged += 1;
  597. connection_fetch_from_buf(payload, length, conn);
  598. log_fn(LOG_DEBUG,"(%d) Packaging %d bytes (%d waiting).", conn->s, length,
  599. (int)buf_datalen(conn->inbuf));
  600. if(connection_edge_send_command(conn, circ, RELAY_COMMAND_DATA,
  601. payload, length, conn->cpath_layer) < 0)
  602. return 0; /* circuit is closed, don't continue */
  603. if(!conn->cpath_layer) { /* non-rendezvous exit */
  604. tor_assert(circ->package_window > 0);
  605. circ->package_window--;
  606. } else { /* we're an AP, or an exit on a rendezvous circ */
  607. tor_assert(conn->cpath_layer->package_window > 0);
  608. conn->cpath_layer->package_window--;
  609. }
  610. if(--conn->package_window <= 0) { /* is it 0 after decrement? */
  611. connection_stop_reading(conn);
  612. log_fn(LOG_DEBUG,"conn->package_window reached 0.");
  613. circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
  614. return 0; /* don't process the inbuf any more */
  615. }
  616. log_fn(LOG_DEBUG,"conn->package_window is now %d",conn->package_window);
  617. /* handle more if there's more, or return 0 if there isn't */
  618. goto repeat_connection_edge_package_raw_inbuf;
  619. }
  620. /** How many times do we retry a general-purpose stream (detach it from
  621. * one circuit and try another, after we wait a while with no 'connected'
  622. * cell) before giving up?
  623. */
  624. #define MAX_STREAM_RETRIES 4
  625. /** Find all general-purpose AP streams in state connect_wait that sent
  626. * their begin cell >=15 seconds ago. Detach from their current circuit,
  627. * and mark their current circuit as unsuitable for new streams. Then call
  628. * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
  629. * available) or launch a new one.
  630. *
  631. * For rendezvous streams, simply give up after 45 seconds (with no
  632. * retry attempt).
  633. */
  634. void connection_ap_expire_beginning(void) {
  635. connection_t **carray;
  636. connection_t *conn;
  637. circuit_t *circ;
  638. int n, i;
  639. time_t now = time(NULL);
  640. get_connection_array(&carray, &n);
  641. for (i = 0; i < n; ++i) {
  642. conn = carray[i];
  643. if (conn->type != CONN_TYPE_AP ||
  644. conn->state != AP_CONN_STATE_CONNECT_WAIT)
  645. continue;
  646. if (now - conn->timestamp_lastread < 15)
  647. continue;
  648. conn->num_retries++;
  649. circ = circuit_get_by_conn(conn);
  650. if(!circ) { /* it's vanished? */
  651. log_fn(LOG_INFO,"Conn is in connect-wait, but lost its circ.");
  652. connection_mark_for_close(conn,0);
  653. continue;
  654. }
  655. if(circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  656. if (now - conn->timestamp_lastread > 45) {
  657. log_fn(LOG_WARN,"Rend stream is %d seconds late. Giving up.",
  658. (int)(now - conn->timestamp_lastread));
  659. connection_mark_for_close(conn,END_STREAM_REASON_TIMEOUT);
  660. }
  661. continue;
  662. }
  663. tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
  664. if(conn->num_retries >= MAX_STREAM_RETRIES) {
  665. log_fn(LOG_WARN,"Stream is %d seconds late. Giving up.",
  666. 15*conn->num_retries);
  667. circuit_log_path(LOG_WARN, circ);
  668. connection_mark_for_close(conn,END_STREAM_REASON_TIMEOUT);
  669. } else {
  670. log_fn(LOG_WARN,"Stream is %d seconds late. Retrying.",
  671. (int)(now - conn->timestamp_lastread));
  672. circuit_log_path(LOG_WARN, circ);
  673. /* send an end down the circuit */
  674. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
  675. /* un-mark it as ending, since we're going to reuse it */
  676. conn->has_sent_end = 0;
  677. /* move it back into 'pending' state. */
  678. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  679. circuit_detach_stream(circ, conn);
  680. /* kludge to make us not try this circuit again, yet to allow
  681. * current streams on it to survive if they can: make it
  682. * unattractive to use for new streams */
  683. tor_assert(circ->timestamp_dirty);
  684. circ->timestamp_dirty -= options.NewCircuitPeriod;
  685. /* give our stream another 15 seconds to try */
  686. conn->timestamp_lastread += 15;
  687. /* attaching to a dirty circuit is fine */
  688. if(connection_ap_handshake_attach_circuit(conn)<0) {
  689. /* it will never work */
  690. /* Don't need to send end -- we're not connected */
  691. connection_mark_for_close(conn, 0);
  692. }
  693. } /* end if max_retries */
  694. } /* end for */
  695. }
  696. /** Tell any AP streamss that are waiting for a new circuit that one is
  697. * available.
  698. */
  699. void connection_ap_attach_pending(void)
  700. {
  701. connection_t **carray;
  702. connection_t *conn;
  703. int n, i;
  704. get_connection_array(&carray, &n);
  705. for (i = 0; i < n; ++i) {
  706. conn = carray[i];
  707. if (conn->type != CONN_TYPE_AP ||
  708. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  709. continue;
  710. if(connection_ap_handshake_attach_circuit(conn) < 0) {
  711. /* -1 means it will never work */
  712. /* Don't send end; there is no 'other side' yet */
  713. connection_mark_for_close(conn,0);
  714. }
  715. }
  716. }
  717. /** Called when we've just received a relay data cell, or when
  718. * we've just finished flushing all bytes to stream <b>conn</b>.
  719. *
  720. * If conn->outbuf is not too full, and our deliver window is
  721. * low, send back a suitable number of stream-level sendme cells.
  722. */
  723. static void connection_edge_consider_sending_sendme(connection_t *conn) {
  724. circuit_t *circ;
  725. if(connection_outbuf_too_full(conn))
  726. return;
  727. circ = circuit_get_by_conn(conn);
  728. if(!circ) {
  729. /* this can legitimately happen if the destroy has already
  730. * arrived and torn down the circuit */
  731. log_fn(LOG_INFO,"No circuit associated with conn. Skipping.");
  732. return;
  733. }
  734. while(conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  735. log_fn(LOG_DEBUG,"Outbuf %d, Queueing stream sendme.", conn->outbuf_flushlen);
  736. conn->deliver_window += STREAMWINDOW_INCREMENT;
  737. if(connection_edge_send_command(conn, circ, RELAY_COMMAND_SENDME,
  738. NULL, 0, conn->cpath_layer) < 0) {
  739. log_fn(LOG_WARN,"connection_edge_send_command failed. Returning.");
  740. return; /* the circuit's closed, don't continue */
  741. }
  742. }
  743. }
  744. /** connection_edge_process_inbuf() found a conn in state
  745. * socks_wait. See if conn->inbuf has the right bytes to proceed with
  746. * the socks handshake.
  747. *
  748. * If the handshake is complete, and it's for a general circuit, then
  749. * try to attach it to a circuit (or launch one as needed). If it's for
  750. * a rendezvous circuit, then fetch a rendezvous descriptor first (or
  751. * attach/launch a circuit if the rendezvous descriptor is already here
  752. * and fresh enough).
  753. *
  754. * Return -1 if an unexpected error with conn (and it should be marked
  755. * for close), else return 0.
  756. */
  757. static int connection_ap_handshake_process_socks(connection_t *conn) {
  758. socks_request_t *socks;
  759. int sockshere;
  760. tor_assert(conn);
  761. tor_assert(conn->type == CONN_TYPE_AP);
  762. tor_assert(conn->state == AP_CONN_STATE_SOCKS_WAIT);
  763. tor_assert(conn->socks_request);
  764. socks = conn->socks_request;
  765. log_fn(LOG_DEBUG,"entered.");
  766. sockshere = fetch_from_buf_socks(conn->inbuf, socks);
  767. if(sockshere == -1 || sockshere == 0) {
  768. if(socks->replylen) { /* we should send reply back */
  769. log_fn(LOG_DEBUG,"reply is already set for us. Using it.");
  770. connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen, 0);
  771. } else if(sockshere == -1) { /* send normal reject */
  772. log_fn(LOG_WARN,"Fetching socks handshake failed. Closing.");
  773. connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
  774. } else {
  775. log_fn(LOG_DEBUG,"socks handshake not all here yet.");
  776. }
  777. if (sockshere == -1)
  778. conn->socks_request->has_finished = 1;
  779. return sockshere;
  780. } /* else socks handshake is done, continue processing */
  781. /* this call _modifies_ socks->address iff it's a hidden-service request */
  782. if (rend_parse_rendezvous_address(socks->address) < 0) {
  783. /* normal request */
  784. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  785. return connection_ap_handshake_attach_circuit(conn);
  786. } else {
  787. /* it's a hidden-service request */
  788. rend_cache_entry_t *entry;
  789. int r;
  790. strcpy(conn->rend_query, socks->address); /* this strcpy is safe -RD */
  791. log_fn(LOG_INFO,"Got a hidden service request for ID '%s'", conn->rend_query);
  792. /* see if we already have it cached */
  793. r = rend_cache_lookup_entry(conn->rend_query, &entry);
  794. if(r<0) {
  795. log_fn(LOG_WARN,"Invalid service descriptor %s", conn->rend_query);
  796. return -1;
  797. }
  798. if(r==0) {
  799. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  800. log_fn(LOG_INFO, "Unknown descriptor %s. Fetching.", conn->rend_query);
  801. rend_client_refetch_renddesc(conn->rend_query);
  802. return 0;
  803. }
  804. if(r>0) {
  805. #define NUM_SECONDS_BEFORE_REFETCH (60*15)
  806. if(time(NULL) - entry->received < NUM_SECONDS_BEFORE_REFETCH) {
  807. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  808. log_fn(LOG_INFO, "Descriptor is here and fresh enough. Great.");
  809. return connection_ap_handshake_attach_circuit(conn);
  810. } else {
  811. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  812. log_fn(LOG_INFO, "Stale descriptor %s. Refetching.", conn->rend_query);
  813. rend_client_refetch_renddesc(conn->rend_query);
  814. return 0;
  815. }
  816. }
  817. }
  818. return 0;
  819. }
  820. /** Find an open circ that we're happy with: return 1. If there isn't
  821. * one, and there isn't one on the way, launch one and return 0. If it
  822. * will never work, return -1.
  823. *
  824. * Write the found or in-progress or launched circ into *circp.
  825. */
  826. static int
  827. circuit_get_open_circ_or_launch(connection_t *conn,
  828. uint8_t desired_circuit_purpose,
  829. circuit_t **circp) {
  830. circuit_t *circ;
  831. uint32_t addr;
  832. tor_assert(conn);
  833. tor_assert(circp);
  834. tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  835. circ = circuit_get_best(conn, 1, desired_circuit_purpose);
  836. if(circ) {
  837. *circp = circ;
  838. return 1; /* we're happy */
  839. }
  840. if(!connection_edge_is_rendezvous_stream(conn)) { /* general purpose circ */
  841. addr = client_dns_lookup_entry(conn->socks_request->address);
  842. if(router_exit_policy_all_routers_reject(addr, conn->socks_request->port)) {
  843. log_fn(LOG_WARN,"No Tor server exists that allows exit to %s:%d. Rejecting.",
  844. conn->socks_request->address, conn->socks_request->port);
  845. return -1;
  846. }
  847. }
  848. /* is one already on the way? */
  849. circ = circuit_get_best(conn, 0, desired_circuit_purpose);
  850. if(!circ) {
  851. char *exitname=NULL;
  852. uint8_t new_circ_purpose;
  853. if(desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  854. /* need to pick an intro point */
  855. exitname = rend_client_get_random_intro(conn->rend_query);
  856. if(!exitname) {
  857. log_fn(LOG_WARN,"Couldn't get an intro point for '%s'. Closing conn.",
  858. conn->rend_query);
  859. return -1;
  860. }
  861. if(!router_get_by_nickname(exitname)) {
  862. log_fn(LOG_WARN,"Advertised intro point '%s' is not known. Closing.", exitname);
  863. return -1;
  864. }
  865. /* XXX if we failed, then refetch the descriptor */
  866. log_fn(LOG_INFO,"Chose %s as intro point for %s.", exitname, conn->rend_query);
  867. }
  868. if(desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
  869. new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
  870. else if(desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
  871. new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  872. else
  873. new_circ_purpose = desired_circuit_purpose;
  874. circ = circuit_launch_new(new_circ_purpose, exitname);
  875. tor_free(exitname);
  876. if(circ &&
  877. (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL)) {
  878. /* then write the service_id into circ */
  879. strcpy(circ->rend_query, conn->rend_query);
  880. }
  881. }
  882. if(!circ)
  883. log_fn(LOG_INFO,"No safe circuit (purpose %d) ready for edge connection; delaying.",
  884. desired_circuit_purpose);
  885. *circp = circ;
  886. return 0;
  887. }
  888. /** Attach the AP stream <b>apconn</b> to circ's linked list of
  889. * p_streams. Also set apconn's cpath_layer to the last hop in
  890. * circ's cpath.
  891. */
  892. void link_apconn_to_circ(connection_t *apconn, circuit_t *circ) {
  893. /* add it into the linked list of streams on this circuit */
  894. log_fn(LOG_DEBUG,"attaching new conn to circ. n_circ_id %d.", circ->n_circ_id);
  895. apconn->next_stream = circ->p_streams;
  896. /* assert_connection_ok(conn, time(NULL)); */
  897. circ->p_streams = apconn;
  898. tor_assert(CIRCUIT_IS_ORIGIN(circ) && circ->cpath && circ->cpath->prev);
  899. tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  900. apconn->cpath_layer = circ->cpath->prev;
  901. }
  902. /** Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  903. * we don't find one: if conn cannot be handled by any known nodes,
  904. * warn and return -1 (conn needs to die);
  905. * else launch new circuit (if necessary) and return 0.
  906. * Otherwise, associate conn with a safe live circuit, do the
  907. * right next step, and return 1.
  908. */
  909. int connection_ap_handshake_attach_circuit(connection_t *conn) {
  910. int retval;
  911. int conn_age;
  912. tor_assert(conn);
  913. tor_assert(conn->type == CONN_TYPE_AP);
  914. tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  915. tor_assert(conn->socks_request);
  916. conn_age = time(NULL) - conn->timestamp_created;
  917. if(conn_age > 60) {
  918. /* XXX make this cleaner than '60' */
  919. log_fn(LOG_WARN,"Giving up on unattached conn (%d sec old).", conn_age);
  920. return -1;
  921. }
  922. if(!connection_edge_is_rendezvous_stream(conn)) { /* we're a general conn */
  923. circuit_t *circ=NULL;
  924. /* find the circuit that we should use, if there is one. */
  925. retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_GENERAL, &circ);
  926. if(retval < 1)
  927. return retval;
  928. /* We have found a suitable circuit for our conn. Hurray. */
  929. log_fn(LOG_DEBUG,"Attaching apconn to general circ %d (stream %d sec old).",
  930. circ->n_circ_id, conn_age);
  931. /* here, print the circ's path. so people can figure out which circs are sucking. */
  932. circuit_log_path(LOG_INFO,circ);
  933. if(!circ->timestamp_dirty)
  934. circ->timestamp_dirty = time(NULL);
  935. link_apconn_to_circ(conn, circ);
  936. connection_ap_handshake_send_begin(conn, circ);
  937. return 1;
  938. } else { /* we're a rendezvous conn */
  939. circuit_t *rendcirc=NULL, *introcirc=NULL;
  940. tor_assert(!conn->cpath_layer);
  941. /* start by finding a rendezvous circuit for us */
  942. retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
  943. if(retval < 0) return -1; /* failed */
  944. tor_assert(rendcirc);
  945. if(retval > 0) {
  946. /* one is already established, attach */
  947. log_fn(LOG_INFO,"rend joined circ %d already here. attaching. (stream %d sec old)",
  948. rendcirc->n_circ_id, conn_age);
  949. link_apconn_to_circ(conn, rendcirc);
  950. if(connection_ap_handshake_send_begin(conn, rendcirc) < 0)
  951. return 0; /* already marked, let them fade away */
  952. return 1;
  953. }
  954. if(rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
  955. log_fn(LOG_INFO,"pending-join circ %d already here, with intro ack. Stalling. (stream %d sec old)", rendcirc->n_circ_id, conn_age);
  956. return 0;
  957. }
  958. /* it's on its way. find an intro circ. */
  959. retval = circuit_get_open_circ_or_launch(conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
  960. if(retval < 0) return -1; /* failed */
  961. tor_assert(introcirc);
  962. if(retval > 0) {
  963. /* one has already sent the intro. keep waiting. */
  964. log_fn(LOG_INFO,"Intro circ %d present and awaiting ack (rend %d). Stalling. (stream %d sec old)",
  965. introcirc->n_circ_id, rendcirc->n_circ_id, conn_age);
  966. return 0;
  967. }
  968. /* now both rendcirc and introcirc are defined, and neither is finished */
  969. if(rendcirc->purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  970. log_fn(LOG_INFO,"ready rend circ %d already here (no intro-ack yet on intro %d). (stream %d sec old)",
  971. rendcirc->n_circ_id, introcirc->n_circ_id, conn_age);
  972. /* look around for any new intro circs that should introduce */
  973. tor_assert(introcirc->purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  974. if(introcirc->state == CIRCUIT_STATE_OPEN) {
  975. log_fn(LOG_INFO,"found open intro circ %d (rend %d); sending introduction. (stream %d sec old)",
  976. introcirc->n_circ_id, rendcirc->n_circ_id, conn_age);
  977. /* XXX here we should cannibalize the rend circ if it's a zero service id */
  978. if(rend_client_send_introduction(introcirc, rendcirc) < 0) {
  979. return -1;
  980. }
  981. rendcirc->timestamp_dirty = time(NULL);
  982. introcirc->timestamp_dirty = time(NULL);
  983. assert_circuit_ok(rendcirc);
  984. assert_circuit_ok(introcirc);
  985. return 0;
  986. }
  987. }
  988. log_fn(LOG_INFO,"Intro (%d) and rend (%d) circs are not both ready. Stalling conn. (%d sec old)", introcirc->n_circ_id, rendcirc->n_circ_id, conn_age);
  989. return 0;
  990. }
  991. }
  992. /** Iterate over the two bytes of stream_id until we get one that is not
  993. * already in use; return it. Return 0 if can't get a unique stream_id.
  994. */
  995. static uint16_t get_unique_stream_id_by_circ(circuit_t *circ) {
  996. connection_t *tmpconn;
  997. uint16_t test_stream_id;
  998. uint32_t attempts=0;
  999. again:
  1000. test_stream_id = circ->next_stream_id++;
  1001. if(++attempts > 1<<16) {
  1002. /* Make sure we don't loop forever if all stream_id's are used. */
  1003. log_fn(LOG_WARN,"No unused stream IDs. Failing.");
  1004. return 0;
  1005. }
  1006. if (test_stream_id == 0)
  1007. goto again;
  1008. for(tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  1009. if(tmpconn->stream_id == test_stream_id)
  1010. goto again;
  1011. return test_stream_id;
  1012. }
  1013. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  1014. * socks_request field, and send it down circ.
  1015. *
  1016. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  1017. */
  1018. int connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ)
  1019. {
  1020. char payload[CELL_PAYLOAD_SIZE];
  1021. int payload_len;
  1022. struct in_addr in;
  1023. const char *string_addr;
  1024. tor_assert(ap_conn->type == CONN_TYPE_AP);
  1025. tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1026. tor_assert(ap_conn->socks_request);
  1027. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  1028. if (ap_conn->stream_id==0) {
  1029. /* Don't send end: there is no 'other side' yet */
  1030. connection_mark_for_close(ap_conn, 0);
  1031. circuit_mark_for_close(circ);
  1032. return -1;
  1033. }
  1034. if(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  1035. in.s_addr = htonl(client_dns_lookup_entry(ap_conn->socks_request->address));
  1036. string_addr = in.s_addr ? inet_ntoa(in) : NULL;
  1037. snprintf(payload,RELAY_PAYLOAD_SIZE,
  1038. "%s:%d",
  1039. string_addr ? string_addr : ap_conn->socks_request->address,
  1040. ap_conn->socks_request->port);
  1041. } else {
  1042. snprintf(payload,RELAY_PAYLOAD_SIZE,
  1043. ":%d", ap_conn->socks_request->port);
  1044. }
  1045. payload_len = strlen(payload)+1;
  1046. log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
  1047. if(connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_BEGIN,
  1048. payload, payload_len, ap_conn->cpath_layer) < 0)
  1049. return -1; /* circuit is closed, don't continue */
  1050. ap_conn->package_window = STREAMWINDOW_START;
  1051. ap_conn->deliver_window = STREAMWINDOW_START;
  1052. ap_conn->state = AP_CONN_STATE_CONNECT_WAIT;
  1053. log_fn(LOG_INFO,"Address/port sent, ap socket %d, n_circ_id %d",ap_conn->s,circ->n_circ_id);
  1054. return 0;
  1055. }
  1056. /** Make an AP connection_t, do a socketpair and attach one side
  1057. * to the conn, connection_add it, initialize it to circuit_wait,
  1058. * and call connection_ap_handshake_attach_circuit(conn) on it.
  1059. *
  1060. * Return the other end of the socketpair, or -1 if error.
  1061. */
  1062. int connection_ap_make_bridge(char *address, uint16_t port) {
  1063. int fd[2];
  1064. connection_t *conn;
  1065. log_fn(LOG_INFO,"Making AP bridge to %s:%d ...",address,port);
  1066. if(tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
  1067. log(LOG_WARN,"Couldn't construct socketpair (%s). Network down? Delaying.",
  1068. tor_socket_strerror(tor_socket_errno(-1)));
  1069. return -1;
  1070. }
  1071. set_socket_nonblocking(fd[0]);
  1072. set_socket_nonblocking(fd[1]);
  1073. conn = connection_new(CONN_TYPE_AP);
  1074. conn->s = fd[0];
  1075. /* populate conn->socks_request */
  1076. /* leave version at zero, so the socks_reply is empty */
  1077. conn->socks_request->socks_version = 0;
  1078. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  1079. strcpy(conn->socks_request->address, address);
  1080. conn->socks_request->port = port;
  1081. conn->address = tor_strdup("(local bridge)");
  1082. conn->addr = ntohs(0);
  1083. conn->port = 0;
  1084. if(connection_add(conn) < 0) { /* no space, forget it */
  1085. connection_free(conn); /* this closes fd[0] */
  1086. tor_close_socket(fd[1]);
  1087. return -1;
  1088. }
  1089. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1090. connection_start_reading(conn);
  1091. /* attaching to a dirty circuit is fine */
  1092. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  1093. connection_mark_for_close(conn, 0);
  1094. tor_close_socket(fd[1]);
  1095. return -1;
  1096. }
  1097. log_fn(LOG_INFO,"... AP bridge created and connected.");
  1098. return fd[1];
  1099. }
  1100. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  1101. * socks version, etc.
  1102. *
  1103. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it
  1104. * to conn and return.
  1105. *
  1106. * Otherwise, send back a reply based on whether <b>success</b> is 1 or 0.
  1107. */
  1108. void connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
  1109. int replylen, char success) {
  1110. char buf[256];
  1111. if(replylen) { /* we already have a reply in mind */
  1112. connection_write_to_buf(reply, replylen, conn);
  1113. return;
  1114. }
  1115. tor_assert(conn->socks_request);
  1116. if(conn->socks_request->socks_version == 4) {
  1117. memset(buf,0,SOCKS4_NETWORK_LEN);
  1118. #define SOCKS4_GRANTED 90
  1119. #define SOCKS4_REJECT 91
  1120. buf[1] = (success ? SOCKS4_GRANTED : SOCKS4_REJECT);
  1121. /* leave version, destport, destip zero */
  1122. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, conn);
  1123. }
  1124. if(conn->socks_request->socks_version == 5) {
  1125. buf[0] = 5; /* version 5 */
  1126. #define SOCKS5_SUCCESS 0
  1127. #define SOCKS5_GENERIC_ERROR 1
  1128. buf[1] = success ? SOCKS5_SUCCESS : SOCKS5_GENERIC_ERROR;
  1129. buf[2] = 0;
  1130. buf[3] = 1; /* ipv4 addr */
  1131. memset(buf+4,0,6); /* Set external addr/port to 0.
  1132. The spec doesn't seem to say what to do here. -RD */
  1133. connection_write_to_buf(buf,10,conn);
  1134. }
  1135. /* If socks_version isn't 4 or 5, don't send anything.
  1136. * This can happen in the case of AP bridges. */
  1137. return;
  1138. }
  1139. /** A relay 'begin' cell has arrived, and either we are an exit hop
  1140. * for the circuit, or we are the origin and it is a rendezvous begin.
  1141. *
  1142. * Launch a new exit connection and initialize things appropriately.
  1143. *
  1144. * If it's a rendezvous stream, call connection_exit_connect() on
  1145. * it.
  1146. *
  1147. * For general streams, call dns_resolve() on it first, and only call
  1148. * connection_exit_connect() if the dns answer is already known.
  1149. *
  1150. * Note that we don't call connection_add() on the new stream! We wait
  1151. * for connection_exit_connect() to do that.
  1152. *
  1153. * Return -1 if we want to tear down <b>circ</b>. Else return 0.
  1154. */
  1155. static int connection_exit_begin_conn(cell_t *cell, circuit_t *circ) {
  1156. connection_t *n_stream;
  1157. relay_header_t rh;
  1158. char *colon;
  1159. assert_circuit_ok(circ);
  1160. relay_header_unpack(&rh, cell->payload);
  1161. /* XXX currently we don't send an end cell back if we drop the
  1162. * begin because it's malformed.
  1163. */
  1164. if(!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
  1165. log_fn(LOG_WARN,"relay begin cell has no \\0. Dropping.");
  1166. return 0;
  1167. }
  1168. colon = strchr(cell->payload+RELAY_HEADER_SIZE, ':');
  1169. if(!colon) {
  1170. log_fn(LOG_WARN,"relay begin cell has no colon. Dropping.");
  1171. return 0;
  1172. }
  1173. *colon = 0;
  1174. if(!atoi(colon+1)) { /* bad port */
  1175. log_fn(LOG_WARN,"relay begin cell has invalid port. Dropping.");
  1176. return 0;
  1177. }
  1178. log_fn(LOG_DEBUG,"Creating new exit connection.");
  1179. n_stream = connection_new(CONN_TYPE_EXIT);
  1180. n_stream->stream_id = rh.stream_id;
  1181. n_stream->port = atoi(colon+1);
  1182. /* leave n_stream->s at -1, because it's not yet valid */
  1183. n_stream->package_window = STREAMWINDOW_START;
  1184. n_stream->deliver_window = STREAMWINDOW_START;
  1185. if(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  1186. log_fn(LOG_DEBUG,"begin is for rendezvous. configuring stream.");
  1187. n_stream->address = tor_strdup("(rendezvous)");
  1188. n_stream->state = EXIT_CONN_STATE_CONNECTING;
  1189. strcpy(n_stream->rend_query, circ->rend_query);
  1190. tor_assert(n_stream->rend_query[0]);
  1191. assert_circuit_ok(circ);
  1192. if(rend_service_set_connection_addr_port(n_stream, circ) < 0) {
  1193. log_fn(LOG_INFO,"Didn't find rendezvous service (port %d)",n_stream->port);
  1194. connection_mark_for_close(n_stream, END_STREAM_REASON_EXITPOLICY);
  1195. connection_free(n_stream);
  1196. circuit_mark_for_close(circ); /* knock the whole thing down, somebody screwed up */
  1197. return 0;
  1198. }
  1199. assert_circuit_ok(circ);
  1200. log_fn(LOG_DEBUG,"Finished assigning addr/port");
  1201. n_stream->cpath_layer = circ->cpath->prev; /* link it */
  1202. /* add it into the linked list of n_streams on this circuit */
  1203. n_stream->next_stream = circ->n_streams;
  1204. circ->n_streams = n_stream;
  1205. assert_circuit_ok(circ);
  1206. connection_exit_connect(n_stream);
  1207. return 0;
  1208. }
  1209. n_stream->address = tor_strdup(cell->payload + RELAY_HEADER_SIZE);
  1210. n_stream->state = EXIT_CONN_STATE_RESOLVEFAILED;
  1211. /* default to failed, change in dns_resolve if it turns out not to fail */
  1212. /* send it off to the gethostbyname farm */
  1213. switch(dns_resolve(n_stream)) {
  1214. case 1: /* resolve worked */
  1215. /* add it into the linked list of n_streams on this circuit */
  1216. n_stream->next_stream = circ->n_streams;
  1217. circ->n_streams = n_stream;
  1218. assert_circuit_ok(circ);
  1219. connection_exit_connect(n_stream);
  1220. return 0;
  1221. case -1: /* resolve failed */
  1222. log_fn(LOG_INFO,"Resolve failed (%s).", n_stream->address);
  1223. connection_mark_for_close(n_stream, END_STREAM_REASON_RESOLVEFAILED);
  1224. connection_free(n_stream);
  1225. break;
  1226. case 0: /* resolve added to pending list */
  1227. /* add it into the linked list of resolving_streams on this circuit */
  1228. n_stream->next_stream = circ->resolving_streams;
  1229. circ->resolving_streams = n_stream;
  1230. assert_circuit_ok(circ);
  1231. ;
  1232. }
  1233. return 0;
  1234. }
  1235. /** Connect to conn's specified addr and port. If it worked, conn
  1236. * has now been added to the connection_array.
  1237. *
  1238. * Send back a connected cell. Include the resolved IP of the destination
  1239. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  1240. * streams must not reveal what IP they connected to.)
  1241. */
  1242. void connection_exit_connect(connection_t *conn) {
  1243. unsigned char connected_payload[4];
  1244. if (!connection_edge_is_rendezvous_stream(conn) &&
  1245. router_compare_to_my_exit_policy(conn) == ADDR_POLICY_REJECTED) {
  1246. log_fn(LOG_INFO,"%s:%d failed exit policy. Closing.", conn->address, conn->port);
  1247. connection_mark_for_close(conn, END_STREAM_REASON_EXITPOLICY);
  1248. circuit_detach_stream(circuit_get_by_conn(conn), conn);
  1249. connection_free(conn);
  1250. return;
  1251. }
  1252. log_fn(LOG_DEBUG,"about to try connecting");
  1253. switch(connection_connect(conn, conn->address, conn->addr, conn->port)) {
  1254. case -1:
  1255. connection_mark_for_close(conn, END_STREAM_REASON_CONNECTFAILED);
  1256. circuit_detach_stream(circuit_get_by_conn(conn), conn);
  1257. connection_free(conn);
  1258. return;
  1259. case 0:
  1260. conn->state = EXIT_CONN_STATE_CONNECTING;
  1261. connection_watch_events(conn, POLLOUT | POLLIN | POLLERR);
  1262. /* writable indicates finish, readable indicates broken link,
  1263. error indicates broken link in windowsland. */
  1264. return;
  1265. /* case 1: fall through */
  1266. }
  1267. conn->state = EXIT_CONN_STATE_OPEN;
  1268. if(connection_wants_to_flush(conn)) { /* in case there are any queued data cells */
  1269. log_fn(LOG_WARN,"tell roger: newly connected conn had data waiting!");
  1270. // connection_start_writing(conn);
  1271. }
  1272. // connection_process_inbuf(conn);
  1273. connection_watch_events(conn, POLLIN);
  1274. /* also, deliver a 'connected' cell back through the circuit. */
  1275. if(connection_edge_is_rendezvous_stream(conn)) { /* rendezvous stream */
  1276. /* don't send an address back! */
  1277. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
  1278. NULL, 0, conn->cpath_layer);
  1279. } else { /* normal stream */
  1280. *(uint32_t*)connected_payload = htonl(conn->addr);
  1281. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
  1282. connected_payload, 4, conn->cpath_layer);
  1283. }
  1284. }
  1285. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  1286. * it is a general stream.
  1287. */
  1288. int connection_edge_is_rendezvous_stream(connection_t *conn) {
  1289. tor_assert(conn);
  1290. if(*conn->rend_query) /* XXX */
  1291. return 1;
  1292. return 0;
  1293. }
  1294. /** Return 1 if router <b>exit</b> might allow stream <b>conn</b>
  1295. * to exit from it, or 0 if it definitely will not allow it.
  1296. * (We might be uncertain if conn's destination address has not yet been
  1297. * resolved.)
  1298. */
  1299. int connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit)
  1300. {
  1301. uint32_t addr;
  1302. tor_assert(conn);
  1303. tor_assert(conn->type == CONN_TYPE_AP);
  1304. tor_assert(conn->socks_request);
  1305. log_fn(LOG_DEBUG,"considering nickname %s, for address %s / port %d:",
  1306. exit->nickname, conn->socks_request->address,
  1307. conn->socks_request->port);
  1308. addr = client_dns_lookup_entry(conn->socks_request->address);
  1309. return router_compare_addr_to_exit_policy(addr,
  1310. conn->socks_request->port, exit->exit_policy);
  1311. }
  1312. /* ***** Client DNS code ***** */
  1313. /* XXX Perhaps this should get merged with the dns.c code somehow. */
  1314. /* XXX But we can't just merge them, because then nodes that act as
  1315. * both OR and OP could be attacked: people could rig the dns cache
  1316. * by answering funny things to stream begin requests, and later
  1317. * other clients would reuse those funny addr's. Hm.
  1318. */
  1319. /** A client-side struct to remember the resolved IP (addr) for
  1320. * a given address. These structs make up a tree, with client_dns_map
  1321. * below as its root.
  1322. */
  1323. struct client_dns_entry {
  1324. uint32_t addr; /**< The resolved IP of this entry */
  1325. time_t expires; /**< At what second does addr expire? */
  1326. int n_failures; /**< How many times has this entry failed to resolve so far? */
  1327. };
  1328. /** How many elements are in the client dns cache currently? */
  1329. static int client_dns_size = 0;
  1330. /** The tree of client-side cached DNS resolves. */
  1331. static strmap_t *client_dns_map = NULL;
  1332. /** Initialize client_dns_map and client_dns_size. */
  1333. void client_dns_init(void) {
  1334. client_dns_map = strmap_new();
  1335. client_dns_size = 0;
  1336. }
  1337. /** Return the client_dns_entry that corresponds to <b>address</b>.
  1338. * If it's not there, allocate and return a new entry for <b>address</b>.
  1339. */
  1340. static struct client_dns_entry *
  1341. _get_or_create_ent(const char *address)
  1342. {
  1343. struct client_dns_entry *ent;
  1344. ent = strmap_get_lc(client_dns_map,address);
  1345. if (!ent) {
  1346. ent = tor_malloc_zero(sizeof(struct client_dns_entry));
  1347. ent->expires = time(NULL)+MAX_DNS_ENTRY_AGE;
  1348. strmap_set_lc(client_dns_map,address,ent);
  1349. ++client_dns_size;
  1350. }
  1351. return ent;
  1352. }
  1353. /** Return the IP associated with <b>address</b>, if we know it
  1354. * and it's still fresh enough. Otherwise return 0.
  1355. */
  1356. static uint32_t client_dns_lookup_entry(const char *address)
  1357. {
  1358. struct client_dns_entry *ent;
  1359. struct in_addr in;
  1360. time_t now;
  1361. tor_assert(address);
  1362. if (tor_inet_aton(address, &in)) {
  1363. log_fn(LOG_DEBUG, "Using static address %s (%08lX)", address,
  1364. (unsigned long)ntohl(in.s_addr));
  1365. return ntohl(in.s_addr);
  1366. }
  1367. ent = strmap_get_lc(client_dns_map,address);
  1368. if (!ent || !ent->addr) {
  1369. log_fn(LOG_DEBUG, "No entry found for address %s", address);
  1370. return 0;
  1371. } else {
  1372. now = time(NULL);
  1373. if (ent->expires < now) {
  1374. log_fn(LOG_DEBUG, "Expired entry found for address %s", address);
  1375. strmap_remove_lc(client_dns_map,address);
  1376. tor_free(ent);
  1377. --client_dns_size;
  1378. return 0;
  1379. }
  1380. in.s_addr = htonl(ent->addr);
  1381. log_fn(LOG_DEBUG, "Found cached entry for address %s: %s", address,
  1382. inet_ntoa(in));
  1383. return ent->addr;
  1384. }
  1385. }
  1386. /** An attempt to resolve <b>address</b> failed at some OR.
  1387. * Increment the number of resolve failures we have on record
  1388. * for it, and then return that number.
  1389. */
  1390. static int client_dns_incr_failures(const char *address)
  1391. {
  1392. struct client_dns_entry *ent;
  1393. ent = _get_or_create_ent(address);
  1394. ++ent->n_failures;
  1395. log_fn(LOG_DEBUG,"Address %s now has %d resolve failures.",
  1396. address, ent->n_failures);
  1397. return ent->n_failures;
  1398. }
  1399. /** Record the fact that <b>address</b> resolved to <b>val</b>.
  1400. * We can now use this in subsequent streams in client_dns_lookup_entry(),
  1401. * so we can more correctly choose a router that will allow <b>address</b>
  1402. * to exit from him.
  1403. */
  1404. static void client_dns_set_entry(const char *address, uint32_t val)
  1405. {
  1406. struct client_dns_entry *ent;
  1407. struct in_addr in;
  1408. time_t now;
  1409. tor_assert(address);
  1410. tor_assert(val);
  1411. if (tor_inet_aton(address, &in))
  1412. return;
  1413. now = time(NULL);
  1414. ent = _get_or_create_ent(address);
  1415. in.s_addr = htonl(val);
  1416. log_fn(LOG_DEBUG, "Updating entry for address %s: %s", address,
  1417. inet_ntoa(in));
  1418. ent->addr = val;
  1419. ent->expires = now+MAX_DNS_ENTRY_AGE;
  1420. ent->n_failures = 0;
  1421. }
  1422. /** A helper function for client_dns_clean() below. If ent is too old,
  1423. * then remove it from the tree and return NULL, else return ent.
  1424. */
  1425. static void* _remove_if_expired(const char *addr,
  1426. struct client_dns_entry *ent,
  1427. time_t *nowp)
  1428. {
  1429. if (ent->expires < *nowp) {
  1430. --client_dns_size;
  1431. tor_free(ent);
  1432. return NULL;
  1433. } else {
  1434. return ent;
  1435. }
  1436. }
  1437. /** Clean out entries from the client-side DNS cache that were
  1438. * resolved long enough ago that they are no longer valid.
  1439. */
  1440. void client_dns_clean(void)
  1441. {
  1442. time_t now;
  1443. if(!client_dns_size)
  1444. return;
  1445. now = time(NULL);
  1446. strmap_foreach(client_dns_map, (strmap_foreach_fn)_remove_if_expired, &now);
  1447. }
  1448. /*
  1449. Local Variables:
  1450. mode:c
  1451. indent-tabs-mode:nil
  1452. c-basic-offset:2
  1453. End:
  1454. */