connection_edge.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "or.h"
  5. #include "tree.h"
  6. extern or_options_t options; /* command-line and config-file options */
  7. extern char *conn_state_to_string[][_CONN_TYPE_MAX+1];
  8. static int connection_ap_handshake_process_socks(connection_t *conn);
  9. static int connection_ap_handshake_attach_circuit(connection_t *conn,
  10. int must_be_clean);
  11. static int connection_ap_handshake_attach_circuit_helper(connection_t *conn,
  12. int must_be_clean);
  13. static void connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ);
  14. static int connection_exit_begin_conn(cell_t *cell, circuit_t *circ);
  15. static void connection_edge_consider_sending_sendme(connection_t *conn);
  16. static uint32_t client_dns_lookup_entry(const char *address);
  17. static void client_dns_set_entry(const char *address, uint32_t val);
  18. void relay_header_pack(char *dest, const relay_header_t *src) {
  19. uint16_t tmp;
  20. /* we have to do slow memcpy's here, because we screwed up
  21. * and made our cell payload not word-aligned. we should fix
  22. * this someday.
  23. */
  24. *(uint8_t*)(dest) = src->command;
  25. tmp = htons(src->recognized);
  26. memcpy(dest+1, &tmp, 2);
  27. tmp = htons(src->stream_id);
  28. memcpy(dest+3, &tmp, 2);
  29. memcpy(dest+5, src->integrity, 4);
  30. tmp = htons(src->length);
  31. memcpy(dest+9, &tmp, 2);
  32. #if 0
  33. *(uint8_t*)(dest) = src->command;
  34. *(uint16_t*)(dest+1) = htons(src->recognized);
  35. *(uint16_t*)(dest+3) = htons(src->stream_id);
  36. memcpy(dest+5, src->integrity, 4);
  37. *(uint16_t*)(dest+9) = htons(src->length);
  38. #endif
  39. }
  40. void relay_header_unpack(relay_header_t *dest, const char *src) {
  41. dest->command = *(uint8_t*)(src);
  42. memcpy(&dest->recognized, src+1, 2);
  43. dest->recognized = ntohs(dest->recognized);
  44. memcpy(&dest->stream_id, src+3, 2);
  45. dest->stream_id = ntohs(dest->stream_id);
  46. memcpy(dest->integrity, src+5, 4);
  47. memcpy(&dest->length, src+9, 2);
  48. dest->length = ntohs(dest->length);
  49. #if 0
  50. dest->command = *(uint8_t*)(src);
  51. dest->recognized = ntohs(*(uint16_t*)(src+1));
  52. dest->stream_id = ntohs(*(uint16_t*)(src+3));
  53. memcpy(dest->integrity, src+5, 4);
  54. dest->length = ntohs(*(uint16_t*)(src+9));
  55. #endif
  56. }
  57. /* mark and return -1 if there was an unexpected error with the conn,
  58. * else return 0.
  59. */
  60. int connection_edge_process_inbuf(connection_t *conn) {
  61. assert(conn);
  62. assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
  63. if(conn->inbuf_reached_eof) {
  64. #ifdef HALF_OPEN
  65. /* eof reached; we're done reading, but we might want to write more. */
  66. conn->done_receiving = 1;
  67. shutdown(conn->s, 0); /* XXX check return, refactor NM */
  68. if (conn->done_sending) {
  69. connection_mark_for_close(conn, END_STREAM_REASON_DONE);
  70. } else {
  71. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_END,
  72. NULL, 0, conn->cpath_layer);
  73. }
  74. return 0;
  75. #else
  76. /* eof reached, kill it. */
  77. log_fn(LOG_INFO,"conn (fd %d) reached eof. Closing.", conn->s);
  78. connection_mark_for_close(conn, END_STREAM_REASON_DONE);
  79. conn->hold_open_until_flushed = 1; /* just because we shouldn't read
  80. doesn't mean we shouldn't write */
  81. return 0;
  82. #endif
  83. }
  84. switch(conn->state) {
  85. case AP_CONN_STATE_SOCKS_WAIT:
  86. if(connection_ap_handshake_process_socks(conn) < 0) {
  87. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  88. conn->hold_open_until_flushed = 1;
  89. return -1;
  90. }
  91. return 0;
  92. case AP_CONN_STATE_OPEN:
  93. case EXIT_CONN_STATE_OPEN:
  94. if(conn->package_window <= 0) {
  95. log_fn(LOG_WARN,"called with package_window %d. Tell Roger.", conn->package_window);
  96. return 0;
  97. }
  98. if(connection_edge_package_raw_inbuf(conn) < 0) {
  99. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  100. return -1;
  101. }
  102. return 0;
  103. case EXIT_CONN_STATE_CONNECTING:
  104. case AP_CONN_STATE_CIRCUIT_WAIT:
  105. case AP_CONN_STATE_CONNECT_WAIT:
  106. log_fn(LOG_INFO,"data from edge while in '%s' state. Leaving it on buffer.",
  107. conn_state_to_string[conn->type][conn->state]);
  108. return 0;
  109. }
  110. log_fn(LOG_WARN,"Got unexpected state %d. Closing.",conn->state);
  111. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  112. return -1;
  113. }
  114. int connection_edge_destroy(uint16_t circ_id, connection_t *conn) {
  115. assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
  116. if(conn->marked_for_close)
  117. return 0; /* already marked; probably got an 'end' */
  118. log_fn(LOG_INFO,"CircID %d: At an edge. Marking connection for close.",
  119. circ_id);
  120. conn->has_sent_end = 1; /* we're closing the circuit, nothing to send to */
  121. connection_mark_for_close(conn, END_STREAM_REASON_DESTROY);
  122. conn->hold_open_until_flushed = 1;
  123. return 0;
  124. }
  125. static char *connection_edge_end_reason(char *payload, uint16_t length) {
  126. if(length < 1) {
  127. log_fn(LOG_WARN,"End cell arrived with length 0. Should be at least 1.");
  128. return "MALFORMED";
  129. }
  130. if(*payload < _MIN_END_STREAM_REASON || *payload > _MAX_END_STREAM_REASON) {
  131. log_fn(LOG_WARN,"Reason for ending (%d) not recognized.",*payload);
  132. return "MALFORMED";
  133. }
  134. switch(*payload) {
  135. case END_STREAM_REASON_MISC: return "misc error";
  136. case END_STREAM_REASON_RESOLVEFAILED: return "resolve failed";
  137. case END_STREAM_REASON_CONNECTFAILED: return "connect failed";
  138. case END_STREAM_REASON_EXITPOLICY: return "exit policy failed";
  139. case END_STREAM_REASON_DESTROY: return "destroyed";
  140. case END_STREAM_REASON_DONE: return "closed normally";
  141. case END_STREAM_REASON_TIMEOUT: return "gave up (timeout)";
  142. }
  143. assert(0);
  144. return "";
  145. }
  146. int connection_edge_end(connection_t *conn, char reason, crypt_path_t *cpath_layer) {
  147. char payload[5];
  148. int payload_len=1;
  149. circuit_t *circ;
  150. if(conn->has_sent_end) {
  151. log_fn(LOG_WARN,"It appears I've already sent the end. Are you calling me twice?");
  152. return -1;
  153. }
  154. payload[0] = reason;
  155. if(reason == END_STREAM_REASON_EXITPOLICY) {
  156. uint32_t tmp = htonl(conn->addr);
  157. memcpy(payload+1, &tmp, 4);
  158. // *(uint32_t *)(payload+1) = htonl(conn->addr);
  159. payload_len += 4;
  160. }
  161. circ = circuit_get_by_conn(conn);
  162. if(circ && !circ->marked_for_close) {
  163. log_fn(LOG_DEBUG,"Marking conn (fd %d) and sending end.",conn->s);
  164. connection_edge_send_command(conn, circ, RELAY_COMMAND_END,
  165. payload, payload_len, cpath_layer);
  166. } else {
  167. log_fn(LOG_DEBUG,"Marking conn (fd %d); no circ to send end.",conn->s);
  168. }
  169. conn->has_sent_end = 1;
  170. return 0;
  171. }
  172. int connection_edge_send_command(connection_t *fromconn, circuit_t *circ,
  173. int relay_command, void *payload,
  174. int payload_len, crypt_path_t *cpath_layer) {
  175. cell_t cell;
  176. relay_header_t rh;
  177. int cell_direction;
  178. if(!circ) {
  179. log_fn(LOG_WARN,"no circ. Closing conn.");
  180. assert(fromconn);
  181. connection_mark_for_close(fromconn, 0);
  182. return -1;
  183. }
  184. memset(&cell, 0, sizeof(cell_t));
  185. cell.command = CELL_RELAY;
  186. if(cpath_layer) {
  187. cell.circ_id = circ->n_circ_id;
  188. cell_direction = CELL_DIRECTION_OUT;
  189. } else {
  190. cell.circ_id = circ->p_circ_id;
  191. cell_direction = CELL_DIRECTION_IN;
  192. }
  193. memset(&rh, 0, sizeof(rh));
  194. rh.command = relay_command;
  195. if(fromconn)
  196. rh.stream_id = fromconn->stream_id; /* else it's 0 */
  197. rh.length = payload_len;
  198. relay_header_pack(cell.payload, &rh);
  199. if(payload_len)
  200. memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
  201. log_fn(LOG_DEBUG,"delivering %d cell %s.", relay_command,
  202. cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
  203. if(circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer) < 0) {
  204. log_fn(LOG_WARN,"circuit_package_relay_cell failed. Closing.");
  205. circuit_mark_for_close(circ);
  206. return -1;
  207. }
  208. return 0;
  209. }
  210. /* an incoming relay cell has arrived. return -1 if you want to tear down the
  211. * circuit, else 0. */
  212. int connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  213. connection_t *conn, int edge_type,
  214. crypt_path_t *layer_hint) {
  215. static int num_seen=0;
  216. uint32_t addr;
  217. relay_header_t rh;
  218. assert(cell && circ);
  219. relay_header_unpack(&rh, cell->payload);
  220. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  221. num_seen++;
  222. log_fn(LOG_DEBUG,"Now seen %d relay cells here.", num_seen);
  223. /* either conn is NULL, in which case we've got a control cell, or else
  224. * conn points to the recognized stream. */
  225. if(conn && conn->state != AP_CONN_STATE_OPEN && conn->state != EXIT_CONN_STATE_OPEN) {
  226. if(rh.command == RELAY_COMMAND_END) {
  227. log_fn(LOG_INFO,"Edge got end (%s) before we're connected. Marking for close.",
  228. connection_edge_end_reason(cell->payload+RELAY_HEADER_SIZE, rh.length));
  229. conn->has_sent_end = 1; /* we just got an 'end', don't need to send one */
  230. connection_mark_for_close(conn, 0);
  231. /* XXX This is where we should check if reason is EXITPOLICY, and reattach */
  232. /* XXX here we should send a socks reject back if necessary, and hold
  233. * open til flushed */
  234. return 0;
  235. }
  236. if(conn->type == CONN_TYPE_AP && rh.command == RELAY_COMMAND_CONNECTED) {
  237. if(conn->state != AP_CONN_STATE_CONNECT_WAIT) {
  238. log_fn(LOG_WARN,"Got 'connected' while not in state connect_wait. Dropping.");
  239. return 0;
  240. }
  241. // log_fn(LOG_INFO,"Connected! Notifying application.");
  242. conn->state = AP_CONN_STATE_OPEN;
  243. if (rh.length >= 4) {
  244. memcpy(&addr, cell->payload + RELAY_HEADER_SIZE, 4);
  245. addr = ntohl(addr);
  246. client_dns_set_entry(conn->socks_request->address, addr);
  247. }
  248. log_fn(LOG_INFO,"'connected' received after %d seconds.",
  249. (int)(time(NULL) - conn->timestamp_lastread));
  250. circuit_log_path(LOG_INFO,circ);
  251. connection_ap_handshake_socks_reply(conn, NULL, 0, 1);
  252. conn->socks_request->has_finished = 1;
  253. /* handle anything that might have queued */
  254. if (connection_edge_package_raw_inbuf(conn) < 0) {
  255. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  256. return 0;
  257. }
  258. return 0;
  259. } else {
  260. log_fn(LOG_WARN,"Got an unexpected relay command %d, in state %d (%s). Closing.",
  261. rh.command, conn->state, conn_state_to_string[conn->type][conn->state]);
  262. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  263. return -1;
  264. }
  265. }
  266. switch(rh.command) {
  267. case RELAY_COMMAND_DROP:
  268. log_fn(LOG_INFO,"Got a relay-level padding cell. Dropping.");
  269. return 0;
  270. case RELAY_COMMAND_BEGIN:
  271. if(edge_type == EDGE_AP) {
  272. log_fn(LOG_WARN,"relay begin request unsupported at AP. Dropping.");
  273. return 0;
  274. }
  275. if(conn) {
  276. log_fn(LOG_WARN,"begin cell for known stream. Dropping.");
  277. return 0;
  278. }
  279. connection_exit_begin_conn(cell, circ);
  280. return 0;
  281. case RELAY_COMMAND_DATA:
  282. ++stats_n_data_cells_received;
  283. if((edge_type == EDGE_AP && --layer_hint->deliver_window < 0) ||
  284. (edge_type == EDGE_EXIT && --circ->deliver_window < 0)) {
  285. log_fn(LOG_WARN,"(relay data) circ deliver_window below 0. Killing.");
  286. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  287. return -1;
  288. }
  289. log_fn(LOG_DEBUG,"circ deliver_window now %d.", edge_type == EDGE_AP ?
  290. layer_hint->deliver_window : circ->deliver_window);
  291. circuit_consider_sending_sendme(circ, edge_type, layer_hint);
  292. if(!conn) {
  293. log_fn(LOG_INFO,"data cell dropped, unknown stream.");
  294. return 0;
  295. }
  296. if(--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  297. log_fn(LOG_WARN,"(relay data) conn deliver_window below 0. Killing.");
  298. return -1; /* somebody's breaking protocol. kill the whole circuit. */
  299. }
  300. stats_n_data_bytes_received += rh.length;
  301. connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
  302. rh.length, conn);
  303. connection_edge_consider_sending_sendme(conn);
  304. return 0;
  305. case RELAY_COMMAND_END:
  306. if(!conn) {
  307. log_fn(LOG_INFO,"end cell (%s) dropped, unknown stream.",
  308. connection_edge_end_reason(cell->payload+RELAY_HEADER_SIZE, rh.length));
  309. return 0;
  310. }
  311. if(rh.length >= 5 &&
  312. *(cell->payload+RELAY_HEADER_SIZE) == END_STREAM_REASON_EXITPOLICY) {
  313. /* XXX this will never be reached, since we're in 'connect_wait' state
  314. * but this is only reached when we're in 'open' state. Put it higher. */
  315. /* No need to close the connection. We'll hold it open while
  316. * we try a new exit node.
  317. * cell->payload+RELAY_HEADER_SIZE+1 holds the destination addr.
  318. */
  319. memcpy(&addr, cell->payload+RELAY_HEADER_SIZE+1, 4);
  320. addr = ntohl(addr);
  321. client_dns_set_entry(conn->socks_request->address, addr);
  322. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  323. /* attaching to a dirty circuit is fine */
  324. if(connection_ap_handshake_attach_circuit(conn, 0) >= 0)
  325. return 0;
  326. /* else, conn will get closed below */
  327. }
  328. /* XXX add to this log_fn the exit node's nickname? */
  329. log_fn(LOG_INFO,"end cell (%s) for stream %d. Removing stream.",
  330. connection_edge_end_reason(cell->payload+RELAY_HEADER_SIZE, rh.length),
  331. conn->stream_id);
  332. #ifdef HALF_OPEN
  333. conn->done_sending = 1;
  334. shutdown(conn->s, 1); /* XXX check return; refactor NM */
  335. if (conn->done_receiving) {
  336. /* We just *got* an end; no reason to send one. */
  337. conn->has_sent_end = 1;
  338. connection_mark_for_close(conn, 0);
  339. conn->hold_open_until_flushed = 1;
  340. }
  341. #else
  342. /* We just *got* an end; no reason to send one. */
  343. conn->has_sent_end = 1;
  344. connection_mark_for_close(conn, 0);
  345. conn->hold_open_until_flushed = 1;
  346. #endif
  347. return 0;
  348. case RELAY_COMMAND_EXTEND:
  349. if(conn) {
  350. log_fn(LOG_WARN,"'extend' for non-zero stream. Dropping.");
  351. return 0;
  352. }
  353. return circuit_extend(cell, circ);
  354. case RELAY_COMMAND_EXTENDED:
  355. if(edge_type == EDGE_EXIT) {
  356. log_fn(LOG_WARN,"'extended' unsupported at exit. Dropping.");
  357. return 0;
  358. }
  359. log_fn(LOG_DEBUG,"Got an extended cell! Yay.");
  360. if(circuit_finish_handshake(circ, cell->payload+RELAY_HEADER_SIZE) < 0) {
  361. log_fn(LOG_WARN,"circuit_finish_handshake failed.");
  362. return -1;
  363. }
  364. if (circuit_send_next_onion_skin(circ)<0) {
  365. log_fn(LOG_INFO,"circuit_send_next_onion_skin() failed.");
  366. return -1;
  367. }
  368. return 0;
  369. case RELAY_COMMAND_TRUNCATE:
  370. if(edge_type == EDGE_AP) {
  371. log_fn(LOG_WARN,"'truncate' unsupported at AP. Dropping.");
  372. return 0;
  373. }
  374. if(circ->n_conn) {
  375. connection_send_destroy(circ->n_circ_id, circ->n_conn);
  376. circ->n_conn = NULL;
  377. }
  378. log_fn(LOG_DEBUG, "Processed 'truncate', replying.");
  379. connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
  380. NULL, 0, NULL);
  381. return 0;
  382. case RELAY_COMMAND_TRUNCATED:
  383. if(edge_type == EDGE_EXIT) {
  384. log_fn(LOG_WARN,"'truncated' unsupported at exit. Dropping.");
  385. return 0;
  386. }
  387. circuit_truncated(circ, layer_hint);
  388. return 0;
  389. case RELAY_COMMAND_CONNECTED:
  390. if(conn) {
  391. log_fn(LOG_WARN,"'connected' unsupported while open. Closing conn.");
  392. return -1;
  393. }
  394. log_fn(LOG_INFO,"'connected' received, no conn attached anymore. Ignoring.");
  395. return 0;
  396. case RELAY_COMMAND_SENDME:
  397. if(!conn) {
  398. if(edge_type == EDGE_AP) {
  399. assert(layer_hint);
  400. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  401. log_fn(LOG_DEBUG,"circ-level sendme at AP, packagewindow %d.",
  402. layer_hint->package_window);
  403. circuit_resume_edge_reading(circ, EDGE_AP, layer_hint);
  404. } else {
  405. assert(!layer_hint);
  406. circ->package_window += CIRCWINDOW_INCREMENT;
  407. log_fn(LOG_DEBUG,"circ-level sendme at exit, packagewindow %d.",
  408. circ->package_window);
  409. circuit_resume_edge_reading(circ, EDGE_EXIT, layer_hint);
  410. }
  411. return 0;
  412. }
  413. conn->package_window += STREAMWINDOW_INCREMENT;
  414. log_fn(LOG_DEBUG,"stream-level sendme, packagewindow now %d.", conn->package_window);
  415. connection_start_reading(conn);
  416. connection_edge_package_raw_inbuf(conn); /* handle whatever might still be on the inbuf */
  417. return 0;
  418. }
  419. log_fn(LOG_WARN,"unknown relay command %d.",rh.command);
  420. return -1;
  421. }
  422. int connection_edge_finished_flushing(connection_t *conn) {
  423. unsigned char connected_payload[4];
  424. int e, len=sizeof(e);
  425. assert(conn);
  426. assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
  427. switch(conn->state) {
  428. case EXIT_CONN_STATE_CONNECTING:
  429. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) { /* not yet */
  430. if(!ERRNO_CONN_EINPROGRESS(errno)) {
  431. /* yuck. kill it. */
  432. log_fn(LOG_DEBUG,"in-progress exit connect failed. Removing.");
  433. connection_mark_for_close(conn, END_STREAM_REASON_CONNECTFAILED);
  434. return -1;
  435. } else {
  436. log_fn(LOG_DEBUG,"in-progress exit connect still waiting.");
  437. return 0; /* no change, see if next time is better */
  438. }
  439. }
  440. /* the connect has finished. */
  441. log_fn(LOG_INFO,"Exit connection to %s:%u established.",
  442. conn->address,conn->port);
  443. conn->state = EXIT_CONN_STATE_OPEN;
  444. connection_watch_events(conn, POLLIN); /* stop writing, continue reading */
  445. if(connection_wants_to_flush(conn)) /* in case there are any queued relay cells */
  446. connection_start_writing(conn);
  447. /* deliver a 'connected' relay cell back through the circuit. */
  448. *(uint32_t*)connected_payload = htonl(conn->addr);
  449. if(connection_edge_send_command(conn, circuit_get_by_conn(conn),
  450. RELAY_COMMAND_CONNECTED, connected_payload, 4, NULL) < 0)
  451. return 0; /* circuit is closed, don't continue */
  452. assert(conn->package_window > 0);
  453. return connection_edge_process_inbuf(conn); /* in case the server has written anything */
  454. case AP_CONN_STATE_OPEN:
  455. case EXIT_CONN_STATE_OPEN:
  456. connection_stop_writing(conn);
  457. connection_edge_consider_sending_sendme(conn);
  458. return 0;
  459. case AP_CONN_STATE_SOCKS_WAIT:
  460. case AP_CONN_STATE_CIRCUIT_WAIT:
  461. case AP_CONN_STATE_CONNECT_WAIT:
  462. connection_stop_writing(conn);
  463. return 0;
  464. default:
  465. log_fn(LOG_WARN,"BUG: called in unexpected state %d.", conn->state);
  466. return -1;
  467. }
  468. return 0;
  469. }
  470. uint64_t stats_n_data_cells_packaged = 0;
  471. uint64_t stats_n_data_bytes_packaged = 0;
  472. uint64_t stats_n_data_cells_received = 0;
  473. uint64_t stats_n_data_bytes_received = 0;
  474. int connection_edge_package_raw_inbuf(connection_t *conn) {
  475. int amount_to_process, length;
  476. char payload[CELL_PAYLOAD_SIZE];
  477. circuit_t *circ;
  478. assert(conn);
  479. assert(!connection_speaks_cells(conn));
  480. repeat_connection_edge_package_raw_inbuf:
  481. circ = circuit_get_by_conn(conn);
  482. if(!circ) {
  483. log_fn(LOG_INFO,"conn has no circuits! Closing.");
  484. return -1;
  485. }
  486. if(circuit_consider_stop_edge_reading(circ, conn->type, conn->cpath_layer))
  487. return 0;
  488. if(conn->package_window <= 0) {
  489. log_fn(LOG_WARN,"called with package_window %d. Tell Roger.", conn->package_window);
  490. connection_stop_reading(conn);
  491. return 0;
  492. }
  493. amount_to_process = buf_datalen(conn->inbuf);
  494. if(!amount_to_process)
  495. return 0;
  496. if(amount_to_process > RELAY_PAYLOAD_SIZE) {
  497. length = RELAY_PAYLOAD_SIZE;
  498. } else {
  499. length = amount_to_process;
  500. }
  501. stats_n_data_bytes_packaged += length;
  502. stats_n_data_cells_packaged += 1;
  503. connection_fetch_from_buf(payload, length, conn);
  504. log_fn(LOG_DEBUG,"(%d) Packaging %d bytes (%d waiting).", conn->s, length,
  505. (int)buf_datalen(conn->inbuf));
  506. if(connection_edge_send_command(conn, circ, RELAY_COMMAND_DATA,
  507. payload, length, conn->cpath_layer) < 0)
  508. return 0; /* circuit is closed, don't continue */
  509. if(conn->type == CONN_TYPE_EXIT) {
  510. assert(circ->package_window > 0);
  511. circ->package_window--;
  512. } else { /* we're an AP */
  513. assert(conn->type == CONN_TYPE_AP);
  514. assert(conn->cpath_layer->package_window > 0);
  515. conn->cpath_layer->package_window--;
  516. }
  517. if(--conn->package_window <= 0) { /* is it 0 after decrement? */
  518. connection_stop_reading(conn);
  519. log_fn(LOG_DEBUG,"conn->package_window reached 0.");
  520. circuit_consider_stop_edge_reading(circ, conn->type, conn->cpath_layer);
  521. return 0; /* don't process the inbuf any more */
  522. }
  523. log_fn(LOG_DEBUG,"conn->package_window is now %d",conn->package_window);
  524. /* handle more if there's more, or return 0 if there isn't */
  525. goto repeat_connection_edge_package_raw_inbuf;
  526. }
  527. #define MAX_STREAM_RETRIES 4
  528. void connection_ap_expire_beginning(void) {
  529. connection_t **carray;
  530. connection_t *conn;
  531. circuit_t *circ;
  532. int n, i;
  533. time_t now = time(NULL);
  534. get_connection_array(&carray, &n);
  535. for (i = 0; i < n; ++i) {
  536. conn = carray[i];
  537. if (conn->type != CONN_TYPE_AP ||
  538. conn->state != AP_CONN_STATE_CONNECT_WAIT)
  539. continue;
  540. if (now - conn->timestamp_lastread < 15)
  541. continue;
  542. conn->num_retries++;
  543. circ = circuit_get_by_conn(conn);
  544. if(conn->num_retries >= MAX_STREAM_RETRIES) {
  545. log_fn(LOG_WARN,"Stream is %d seconds late. Giving up.",
  546. 15*conn->num_retries);
  547. circuit_log_path(LOG_WARN, circ);
  548. connection_mark_for_close(conn,END_STREAM_REASON_TIMEOUT);
  549. } else {
  550. log_fn(LOG_WARN,"Stream is %d seconds late. Retrying.",
  551. (int)(now - conn->timestamp_lastread));
  552. circuit_log_path(LOG_WARN, circ);
  553. /* send an end down the circuit */
  554. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
  555. /* un-mark it as ending, since we're going to reuse it */
  556. conn->has_sent_end = 0;
  557. /* move it back into 'pending' state. */
  558. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  559. circuit_detach_stream(circ, conn);
  560. /* kludge to make us not try this circuit again, yet to allow
  561. * current streams on it to survive if they can: make it
  562. * unattractive to use for new streams */
  563. assert(circ->timestamp_dirty);
  564. circ->timestamp_dirty -= options.NewCircuitPeriod;
  565. /* give our stream another 15 seconds to try */
  566. conn->timestamp_lastread += 15;
  567. /* attaching to a dirty circuit is fine */
  568. if(connection_ap_handshake_attach_circuit(conn,0)<0) {
  569. /* it will never work */
  570. /* Don't need to send end -- we're not connected */
  571. connection_mark_for_close(conn, 0);
  572. }
  573. } /* end if max_retries */
  574. } /* end for */
  575. }
  576. /* Tell any APs that are waiting for a new circuit that one is available */
  577. void connection_ap_attach_pending(void)
  578. {
  579. connection_t **carray;
  580. connection_t *conn;
  581. int n, i;
  582. get_connection_array(&carray, &n);
  583. for (i = 0; i < n; ++i) {
  584. conn = carray[i];
  585. if (conn->type != CONN_TYPE_AP ||
  586. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  587. continue;
  588. /* attaching to a dirty circuit is fine */
  589. if(connection_ap_handshake_attach_circuit(conn,0) < 0) {
  590. /* -1 means it will never work */
  591. /* Don't send end; there is no 'other side' yet */
  592. connection_mark_for_close(conn,0);
  593. }
  594. }
  595. }
  596. static void connection_edge_consider_sending_sendme(connection_t *conn) {
  597. circuit_t *circ;
  598. if(connection_outbuf_too_full(conn))
  599. return;
  600. circ = circuit_get_by_conn(conn);
  601. if(!circ) {
  602. /* this can legitimately happen if the destroy has already
  603. * arrived and torn down the circuit */
  604. log_fn(LOG_INFO,"No circuit associated with conn. Skipping.");
  605. return;
  606. }
  607. while(conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  608. log_fn(LOG_DEBUG,"Outbuf %d, Queueing stream sendme.", conn->outbuf_flushlen);
  609. conn->deliver_window += STREAMWINDOW_INCREMENT;
  610. if(connection_edge_send_command(conn, circ, RELAY_COMMAND_SENDME,
  611. NULL, 0, conn->cpath_layer) < 0) {
  612. log_fn(LOG_WARN,"connection_edge_send_command failed. Returning.");
  613. return; /* the circuit's closed, don't continue */
  614. }
  615. }
  616. }
  617. /* return -1 if an unexpected error with conn, else 0. */
  618. static int connection_ap_handshake_process_socks(connection_t *conn) {
  619. socks_request_t *socks;
  620. int sockshere;
  621. assert(conn);
  622. assert(conn->type == CONN_TYPE_AP);
  623. assert(conn->state == AP_CONN_STATE_SOCKS_WAIT);
  624. assert(conn->socks_request);
  625. socks = conn->socks_request;
  626. log_fn(LOG_DEBUG,"entered.");
  627. sockshere = fetch_from_buf_socks(conn->inbuf, socks);
  628. if(sockshere == -1 || sockshere == 0) {
  629. if(socks->replylen) { /* we should send reply back */
  630. log_fn(LOG_DEBUG,"reply is already set for us. Using it.");
  631. connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen, 0);
  632. } else if(sockshere == -1) { /* send normal reject */
  633. log_fn(LOG_WARN,"Fetching socks handshake failed. Closing.");
  634. connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
  635. } else {
  636. log_fn(LOG_DEBUG,"socks handshake not all here yet.");
  637. }
  638. if (sockshere == -1)
  639. conn->socks_request->has_finished = 1;
  640. return sockshere;
  641. } /* else socks handshake is done, continue processing */
  642. /* this call _modifies_ socks->address iff it's a hidden-service request */
  643. if (rend_parse_rendezvous_address(socks->address) < 0) {
  644. /* normal request */
  645. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  646. /* attaching to a dirty circuit is fine */
  647. return connection_ap_handshake_attach_circuit(conn,0);
  648. } else {
  649. /* it's a hidden-service request */
  650. const char *descp;
  651. int desc_len;
  652. /* see if we already have it cached */
  653. if (rend_cache_lookup(socks->address, &descp, &desc_len) == 1) {
  654. /* then pick and launch a rendezvous circuit */
  655. /* go into some other state */
  656. } else {
  657. /* initiate a dir hidserv desc lookup */
  658. /* go into a state where you'll be notified of the answer */
  659. }
  660. }
  661. return 0;
  662. }
  663. static int connection_ap_handshake_attach_circuit(connection_t *conn,
  664. int must_be_clean) {
  665. /* try attaching. launch new circuit if needed.
  666. * return -1 if conn needs to die, else 0. */
  667. switch(connection_ap_handshake_attach_circuit_helper(conn, must_be_clean)) {
  668. case -1: /* it will never work */
  669. return -1;
  670. case 0: /* no useful circuits available */
  671. if(!circuit_get_newest(conn, 0, must_be_clean)) {
  672. /* is one already on the way? */
  673. circuit_launch_new(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  674. }
  675. return 0;
  676. default: /* case 1, it succeeded, great */
  677. return 0;
  678. }
  679. }
  680. /* Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  681. * we don't find one: if conn cannot be handled by any known nodes,
  682. * warn and return -1; else tell conn to stop reading and return 0.
  683. * Otherwise, associate conn with a safe live circuit, start
  684. * sending a BEGIN cell down the circuit, and return 1.
  685. */
  686. static int connection_ap_handshake_attach_circuit_helper(connection_t *conn,
  687. int must_be_clean) {
  688. circuit_t *circ;
  689. uint32_t addr;
  690. assert(conn);
  691. assert(conn->type == CONN_TYPE_AP);
  692. assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  693. assert(conn->socks_request);
  694. /* find the circuit that we should use, if there is one. */
  695. circ = circuit_get_newest(conn, 1, must_be_clean);
  696. if(!circ) {
  697. log_fn(LOG_INFO,"No safe circuit ready for edge connection; delaying.");
  698. addr = client_dns_lookup_entry(conn->socks_request->address);
  699. if(router_exit_policy_all_routers_reject(addr, conn->socks_request->port)) {
  700. log_fn(LOG_WARN,"No Tor server exists that allows exit to %s:%d. Rejecting.",
  701. conn->socks_request->address, conn->socks_request->port);
  702. return -1;
  703. }
  704. connection_stop_reading(conn); /* don't read until the connected cell arrives */
  705. return 0;
  706. }
  707. connection_start_reading(conn);
  708. /* here, print the circ's path. so people can figure out which circs are sucking. */
  709. circuit_log_path(LOG_INFO,circ);
  710. if(!circ->timestamp_dirty)
  711. circ->timestamp_dirty = time(NULL);
  712. /* add it into the linked list of streams on this circuit */
  713. log_fn(LOG_DEBUG,"attaching new conn to circ. n_circ_id %d.", circ->n_circ_id);
  714. conn->next_stream = circ->p_streams;
  715. /* assert_connection_ok(conn, time(NULL)); */
  716. circ->p_streams = conn;
  717. assert(circ->cpath && circ->cpath->prev);
  718. assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  719. conn->cpath_layer = circ->cpath->prev;
  720. connection_ap_handshake_send_begin(conn, circ);
  721. return 1;
  722. }
  723. /* Iterate over the two bytes of stream_id until we get one that is not
  724. * already in use. Return 0 if can't get a unique stream_id.
  725. */
  726. static uint16_t get_unique_stream_id_by_circ(circuit_t *circ) {
  727. connection_t *tmpconn;
  728. uint16_t test_stream_id;
  729. uint32_t attempts=0;
  730. again:
  731. test_stream_id = circ->next_stream_id++;
  732. if(++attempts > 1<<16) {
  733. /* Make sure we don't loop forever if all stream_id's are used. */
  734. log_fn(LOG_WARN,"No unused stream IDs. Failing.");
  735. return 0;
  736. }
  737. if (test_stream_id == 0)
  738. goto again;
  739. for(tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  740. if(tmpconn->stream_id == test_stream_id)
  741. goto again;
  742. return test_stream_id;
  743. }
  744. /* deliver the destaddr:destport in a relay cell */
  745. static void connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ)
  746. {
  747. char payload[CELL_PAYLOAD_SIZE];
  748. int payload_len;
  749. struct in_addr in;
  750. const char *string_addr;
  751. assert(ap_conn->type == CONN_TYPE_AP);
  752. assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  753. assert(ap_conn->socks_request);
  754. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  755. if (ap_conn->stream_id==0) {
  756. /* Don't send end: there is no 'other side' yet */
  757. connection_mark_for_close(ap_conn, 0);
  758. return;
  759. }
  760. in.s_addr = htonl(client_dns_lookup_entry(ap_conn->socks_request->address));
  761. string_addr = in.s_addr ? inet_ntoa(in) : NULL;
  762. snprintf(payload,RELAY_PAYLOAD_SIZE,
  763. "%s:%d",
  764. string_addr ? string_addr : ap_conn->socks_request->address,
  765. ap_conn->socks_request->port);
  766. payload_len = strlen(payload)+1;
  767. log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
  768. if(connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_BEGIN,
  769. payload, payload_len, ap_conn->cpath_layer) < 0)
  770. return; /* circuit is closed, don't continue */
  771. ap_conn->package_window = STREAMWINDOW_START;
  772. ap_conn->deliver_window = STREAMWINDOW_START;
  773. ap_conn->state = AP_CONN_STATE_CONNECT_WAIT;
  774. /* XXX Right now, we rely on the socks client not to send us any data
  775. * XXX until we've sent back a socks reply. (If it does, we could wind
  776. * XXX up packaging that data and sending it to the exit, then later having
  777. * XXX the exit refuse us.)
  778. */
  779. log_fn(LOG_INFO,"Address/port sent, ap socket %d, n_circ_id %d",ap_conn->s,circ->n_circ_id);
  780. return;
  781. }
  782. /* make an ap connection_t, do a socketpair and attach one side
  783. * to the conn, connection_add it, initialize it to circuit_wait,
  784. * and call connection_ap_handshake_attach_circuit(conn) on it.
  785. * Return the other end of the socketpair, or -1 if error.
  786. */
  787. int connection_ap_make_bridge(char *address, uint16_t port) {
  788. int fd[2];
  789. connection_t *conn;
  790. log_fn(LOG_INFO,"Making AP bridge to %s:%d ...",address,port);
  791. if(tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
  792. log(LOG_ERR, "Couldn't construct socketpair: %s", strerror(errno));
  793. exit(1);
  794. }
  795. set_socket_nonblocking(fd[0]);
  796. set_socket_nonblocking(fd[1]);
  797. conn = connection_new(CONN_TYPE_AP);
  798. conn->s = fd[0];
  799. /* populate conn->socks_request */
  800. /* leave version at zero, so the socks_reply is empty */
  801. conn->socks_request->socks_version = 0;
  802. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  803. strcpy(conn->socks_request->address, address);
  804. conn->socks_request->port = port;
  805. conn->address = tor_strdup("(local bridge)");
  806. conn->addr = ntohs(0);
  807. conn->port = 0;
  808. if(connection_add(conn) < 0) { /* no space, forget it */
  809. connection_free(conn); /* this closes fd[0] */
  810. close(fd[1]);
  811. return -1;
  812. }
  813. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  814. connection_start_reading(conn);
  815. /* attaching to a dirty circuit is fine */
  816. if (connection_ap_handshake_attach_circuit(conn, 0) < 0) {
  817. connection_mark_for_close(conn, 0);
  818. close(fd[1]);
  819. return -1;
  820. }
  821. log_fn(LOG_INFO,"... AP bridge created and connected.");
  822. return fd[1];
  823. }
  824. void connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
  825. int replylen, char success) {
  826. char buf[256];
  827. if(replylen) { /* we already have a reply in mind */
  828. connection_write_to_buf(reply, replylen, conn);
  829. return;
  830. }
  831. assert(conn->socks_request);
  832. if(conn->socks_request->socks_version == 4) {
  833. memset(buf,0,SOCKS4_NETWORK_LEN);
  834. #define SOCKS4_GRANTED 90
  835. #define SOCKS4_REJECT 91
  836. buf[1] = (success ? SOCKS4_GRANTED : SOCKS4_REJECT);
  837. /* leave version, destport, destip zero */
  838. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, conn);
  839. }
  840. if(conn->socks_request->socks_version == 5) {
  841. buf[0] = 5; /* version 5 */
  842. #define SOCKS5_SUCCESS 0
  843. #define SOCKS5_GENERIC_ERROR 1
  844. buf[1] = success ? SOCKS5_SUCCESS : SOCKS5_GENERIC_ERROR;
  845. buf[2] = 0;
  846. buf[3] = 1; /* ipv4 addr */
  847. memset(buf+4,0,6); /* Set external addr/port to 0.
  848. The spec doesn't seem to say what to do here. -RD */
  849. connection_write_to_buf(buf,10,conn);
  850. }
  851. /* If socks_version isn't 4 or 5, don't send anything.
  852. * This can happen in the case of AP bridges. */
  853. return;
  854. }
  855. static int connection_exit_begin_conn(cell_t *cell, circuit_t *circ) {
  856. connection_t *n_stream;
  857. relay_header_t rh;
  858. char *colon;
  859. relay_header_unpack(&rh, cell->payload);
  860. /* XXX currently we don't send an end cell back if we drop the
  861. * begin because it's malformed.
  862. */
  863. if(!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
  864. log_fn(LOG_WARN,"relay begin cell has no \\0. Dropping.");
  865. return 0;
  866. }
  867. colon = strchr(cell->payload+RELAY_HEADER_SIZE, ':');
  868. if(!colon) {
  869. log_fn(LOG_WARN,"relay begin cell has no colon. Dropping.");
  870. return 0;
  871. }
  872. *colon = 0;
  873. if(!atoi(colon+1)) { /* bad port */
  874. log_fn(LOG_WARN,"relay begin cell has invalid port. Dropping.");
  875. return 0;
  876. }
  877. log_fn(LOG_DEBUG,"Creating new exit connection.");
  878. n_stream = connection_new(CONN_TYPE_EXIT);
  879. n_stream->stream_id = rh.stream_id;
  880. n_stream->address = tor_strdup(cell->payload + RELAY_HEADER_SIZE);
  881. n_stream->port = atoi(colon+1);
  882. n_stream->state = EXIT_CONN_STATE_RESOLVING;
  883. /* leave n_stream->s at -1, because it's not yet valid */
  884. n_stream->package_window = STREAMWINDOW_START;
  885. n_stream->deliver_window = STREAMWINDOW_START;
  886. if(connection_add(n_stream) < 0) { /* no space, forget it */
  887. log_fn(LOG_WARN,"connection_add failed. Dropping.");
  888. connection_free(n_stream);
  889. return 0;
  890. }
  891. /* add it into the linked list of streams on this circuit */
  892. n_stream->next_stream = circ->n_streams;
  893. circ->n_streams = n_stream;
  894. /* send it off to the gethostbyname farm */
  895. switch(dns_resolve(n_stream)) {
  896. case 1: /* resolve worked */
  897. connection_exit_connect(n_stream);
  898. return 0;
  899. case -1: /* resolve failed */
  900. log_fn(LOG_INFO,"Resolve failed (%s).", n_stream->address);
  901. /* Set the state so that we don't try to remove n_stream from a DNS
  902. * pending list. */
  903. n_stream->state = EXIT_CONN_STATE_RESOLVEFAILED;
  904. connection_mark_for_close(n_stream, END_STREAM_REASON_RESOLVEFAILED);
  905. break;
  906. case 0: /* resolve added to pending list */
  907. ;
  908. }
  909. return 0;
  910. }
  911. void connection_exit_connect(connection_t *conn) {
  912. unsigned char connected_payload[4];
  913. if(router_compare_to_my_exit_policy(conn) == ADDR_POLICY_REJECTED) {
  914. log_fn(LOG_INFO,"%s:%d failed exit policy. Closing.", conn->address, conn->port);
  915. connection_mark_for_close(conn, END_STREAM_REASON_EXITPOLICY);
  916. return;
  917. }
  918. switch(connection_connect(conn, conn->address, conn->addr, conn->port)) {
  919. case -1:
  920. connection_mark_for_close(conn, END_STREAM_REASON_CONNECTFAILED);
  921. return;
  922. case 0:
  923. connection_set_poll_socket(conn);
  924. conn->state = EXIT_CONN_STATE_CONNECTING;
  925. connection_watch_events(conn, POLLOUT | POLLIN | POLLERR);
  926. /* writable indicates finish, readable indicates broken link,
  927. error indicates broken link in windowsland. */
  928. return;
  929. /* case 1: fall through */
  930. }
  931. connection_set_poll_socket(conn);
  932. conn->state = EXIT_CONN_STATE_OPEN;
  933. if(connection_wants_to_flush(conn)) { /* in case there are any queued data cells */
  934. log_fn(LOG_WARN,"tell roger: newly connected conn had data waiting!");
  935. // connection_start_writing(conn);
  936. }
  937. // connection_process_inbuf(conn);
  938. connection_watch_events(conn, POLLIN);
  939. /* also, deliver a 'connected' cell back through the circuit. */
  940. *(uint32_t*)connected_payload = htonl(conn->addr);
  941. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
  942. connected_payload, 4, NULL);
  943. }
  944. int connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit)
  945. {
  946. uint32_t addr;
  947. assert(conn);
  948. assert(conn->type == CONN_TYPE_AP);
  949. assert(conn->socks_request);
  950. log_fn(LOG_DEBUG,"considering nickname %s, for address %s / port %d:",
  951. exit->nickname, conn->socks_request->address,
  952. conn->socks_request->port);
  953. addr = client_dns_lookup_entry(conn->socks_request->address);
  954. return router_compare_addr_to_exit_policy(addr,
  955. conn->socks_request->port, exit->exit_policy);
  956. }
  957. /* ***** Client DNS code ***** */
  958. /* XXX Perhaps this should get merged with the dns.c code somehow. */
  959. /* XXX But we can't just merge them, because then nodes that act as
  960. * both OR and OP could be attacked: people could rig the dns cache
  961. * by answering funny things to stream begin requests, and later
  962. * other clients would reuse those funny addr's. Hm.
  963. */
  964. struct client_dns_entry {
  965. uint32_t addr;
  966. time_t expires;
  967. };
  968. static int client_dns_size = 0;
  969. static strmap_t *client_dns_map = NULL;
  970. void client_dns_init(void) {
  971. client_dns_map = strmap_new();
  972. client_dns_size = 0;
  973. }
  974. static uint32_t client_dns_lookup_entry(const char *address)
  975. {
  976. struct client_dns_entry *ent;
  977. struct in_addr in;
  978. time_t now;
  979. assert(address);
  980. if (tor_inet_aton(address, &in)) {
  981. log_fn(LOG_DEBUG, "Using static address %s (%08lX)", address,
  982. (unsigned long)ntohl(in.s_addr));
  983. return ntohl(in.s_addr);
  984. }
  985. ent = strmap_get_lc(client_dns_map,address);
  986. if (!ent) {
  987. log_fn(LOG_DEBUG, "No entry found for address %s", address);
  988. return 0;
  989. } else {
  990. now = time(NULL);
  991. if (ent->expires < now) {
  992. log_fn(LOG_DEBUG, "Expired entry found for address %s", address);
  993. strmap_remove_lc(client_dns_map,address);
  994. tor_free(ent);
  995. --client_dns_size;
  996. return 0;
  997. }
  998. in.s_addr = htonl(ent->addr);
  999. log_fn(LOG_DEBUG, "Found cached entry for address %s: %s", address,
  1000. inet_ntoa(in));
  1001. return ent->addr;
  1002. }
  1003. }
  1004. static void client_dns_set_entry(const char *address, uint32_t val)
  1005. {
  1006. struct client_dns_entry *ent;
  1007. struct in_addr in;
  1008. time_t now;
  1009. assert(address);
  1010. assert(val);
  1011. if (tor_inet_aton(address, &in))
  1012. return;
  1013. now = time(NULL);
  1014. ent = strmap_get_lc(client_dns_map, address);
  1015. if (ent) {
  1016. in.s_addr = htonl(val);
  1017. log_fn(LOG_DEBUG, "Updating entry for address %s: %s", address,
  1018. inet_ntoa(in));
  1019. ent->addr = val;
  1020. ent->expires = now+MAX_DNS_ENTRY_AGE;
  1021. } else {
  1022. in.s_addr = htonl(val);
  1023. log_fn(LOG_DEBUG, "Caching result for address %s: %s", address,
  1024. inet_ntoa(in));
  1025. ent = tor_malloc(sizeof(struct client_dns_entry));
  1026. ent->addr = val;
  1027. ent->expires = now+MAX_DNS_ENTRY_AGE;
  1028. strmap_set_lc(client_dns_map, address, ent);
  1029. ++client_dns_size;
  1030. }
  1031. }
  1032. static void* _remove_if_expired(const char *addr,
  1033. struct client_dns_entry *ent,
  1034. time_t *nowp)
  1035. {
  1036. if (ent->expires < *nowp) {
  1037. --client_dns_size;
  1038. tor_free(ent);
  1039. return NULL;
  1040. } else {
  1041. return ent;
  1042. }
  1043. }
  1044. void client_dns_clean(void)
  1045. {
  1046. time_t now;
  1047. if(!client_dns_size)
  1048. return;
  1049. now = time(NULL);
  1050. strmap_foreach(client_dns_map, (strmap_foreach_fn)_remove_if_expired, &now);
  1051. }
  1052. /*
  1053. Local Variables:
  1054. mode:c
  1055. indent-tabs-mode:nil
  1056. c-basic-offset:2
  1057. End:
  1058. */