connection_edge.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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. static int connection_ap_handshake_process_socks(connection_t *conn);
  8. static int connection_ap_handshake_attach_circuit(connection_t *conn);
  9. static void connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ);
  10. static int connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
  11. int replylen, char success);
  12. static int connection_exit_begin_conn(cell_t *cell, circuit_t *circ);
  13. static void connection_edge_consider_sending_sendme(connection_t *conn);
  14. static uint32_t client_dns_lookup_entry(const char *address);
  15. static void client_dns_set_entry(const char *address, uint32_t val);
  16. int connection_edge_process_inbuf(connection_t *conn) {
  17. assert(conn);
  18. assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
  19. if(conn->inbuf_reached_eof) {
  20. #ifdef HALF_OPEN
  21. /* eof reached; we're done reading, but we might want to write more. */
  22. conn->done_receiving = 1;
  23. shutdown(conn->s, 0); /* XXX check return, refactor NM */
  24. if (conn->done_sending) {
  25. connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
  26. } else {
  27. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_END,
  28. NULL, 0, conn->cpath_layer);
  29. }
  30. return 0;
  31. #else
  32. /* eof reached, kill it. */
  33. log_fn(LOG_INFO,"conn (fd %d) reached eof. Closing.", conn->s);
  34. connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
  35. return -1;
  36. #endif
  37. }
  38. switch(conn->state) {
  39. case AP_CONN_STATE_SOCKS_WAIT:
  40. if(connection_ap_handshake_process_socks(conn) < 0) {
  41. connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
  42. return -1;
  43. }
  44. return 0;
  45. case AP_CONN_STATE_OPEN:
  46. case EXIT_CONN_STATE_OPEN:
  47. if(conn->package_window <= 0) {
  48. log_fn(LOG_WARN,"called with package_window %d. Tell Roger.", conn->package_window);
  49. return 0;
  50. }
  51. if(connection_edge_package_raw_inbuf(conn) < 0) {
  52. connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
  53. return -1;
  54. }
  55. return 0;
  56. case EXIT_CONN_STATE_CONNECTING:
  57. log_fn(LOG_INFO,"text from server while in 'connecting' state at exit. Leaving it on buffer.");
  58. return 0;
  59. }
  60. return 0;
  61. }
  62. char *connection_edge_end_reason(char *payload, unsigned char length) {
  63. if(length < 1) {
  64. log_fn(LOG_WARN,"End cell arrived with length 0. Should be at least 1.");
  65. return "MALFORMED";
  66. }
  67. if(*payload < END_STREAM_REASON_MISC || *payload > END_STREAM_REASON_DONE) {
  68. log_fn(LOG_WARN,"Reason for ending (%d) not recognized.",*payload);
  69. return "MALFORMED";
  70. }
  71. switch(*payload) {
  72. case END_STREAM_REASON_MISC: return "misc error";
  73. case END_STREAM_REASON_RESOLVEFAILED: return "resolve failed";
  74. case END_STREAM_REASON_CONNECTFAILED: return "connect failed";
  75. case END_STREAM_REASON_EXITPOLICY: return "exit policy failed";
  76. case END_STREAM_REASON_DESTROY: return "destroyed";
  77. case END_STREAM_REASON_DONE: return "closed normally";
  78. }
  79. assert(0);
  80. return "";
  81. }
  82. void connection_edge_end(connection_t *conn, char reason, crypt_path_t *cpath_layer) {
  83. char payload[5];
  84. int payload_len=1;
  85. circuit_t *circ;
  86. if(conn->has_sent_end) {
  87. log_fn(LOG_WARN,"It appears I've already sent the end. Are you calling me twice?");
  88. return;
  89. }
  90. payload[0] = reason;
  91. if(reason == END_STREAM_REASON_EXITPOLICY) {
  92. *(uint32_t *)(payload+1) = htonl(conn->addr);
  93. payload_len += 4;
  94. }
  95. circ = circuit_get_by_conn(conn);
  96. if(circ) {
  97. log_fn(LOG_DEBUG,"Marking conn (fd %d) and sending end.",conn->s);
  98. connection_edge_send_command(conn, circ, RELAY_COMMAND_END,
  99. payload, payload_len, cpath_layer);
  100. }
  101. conn->marked_for_close = 1;
  102. conn->has_sent_end = 1;
  103. }
  104. int connection_edge_send_command(connection_t *fromconn, circuit_t *circ, int relay_command,
  105. void *payload, int payload_len, crypt_path_t *cpath_layer) {
  106. cell_t cell;
  107. int cell_direction;
  108. int is_control_cell=0;
  109. if(!circ) {
  110. log_fn(LOG_WARN,"no circ. Closing.");
  111. return 0;
  112. }
  113. if(!fromconn || relay_command == RELAY_COMMAND_BEGIN) /* XXX more */
  114. is_control_cell = 1;
  115. memset(&cell, 0, sizeof(cell_t));
  116. if(fromconn && fromconn->type == CONN_TYPE_AP) {
  117. cell.circ_id = circ->n_circ_id;
  118. cell_direction = CELL_DIRECTION_OUT;
  119. } else {
  120. /* NOTE: if !fromconn, we assume that it's heading towards the OP */
  121. cell.circ_id = circ->p_circ_id;
  122. cell_direction = CELL_DIRECTION_IN;
  123. }
  124. cell.command = CELL_RELAY;
  125. SET_CELL_RELAY_COMMAND(cell, relay_command);
  126. if(is_control_cell)
  127. SET_CELL_STREAM_ID(cell, ZERO_STREAM);
  128. else
  129. SET_CELL_STREAM_ID(cell, fromconn->stream_id);
  130. cell.length = RELAY_HEADER_SIZE + payload_len;
  131. if(payload_len) {
  132. memcpy(cell.payload+RELAY_HEADER_SIZE,payload,payload_len);
  133. }
  134. log_fn(LOG_DEBUG,"delivering %d cell %s.", relay_command,
  135. cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
  136. if(circuit_deliver_relay_cell(&cell, circ, cell_direction, cpath_layer) < 0) {
  137. log_fn(LOG_WARN,"circuit_deliver_relay_cell failed. Closing.");
  138. circuit_close(circ);
  139. return -1;
  140. }
  141. return 0;
  142. }
  143. /* an incoming relay cell has arrived. return -1 if you want to tear down the
  144. * circuit, else 0. */
  145. int connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ, connection_t *conn,
  146. int edge_type, crypt_path_t *layer_hint) {
  147. int relay_command;
  148. static int num_seen=0;
  149. uint32_t addr;
  150. assert(cell && circ);
  151. relay_command = CELL_RELAY_COMMAND(*cell);
  152. // log_fn(LOG_DEBUG,"command %d stream %d", relay_command, stream_id);
  153. num_seen++;
  154. log_fn(LOG_DEBUG,"Now seen %d relay cells here.", num_seen);
  155. /* either conn is NULL, in which case we've got a control cell, or else
  156. * conn points to the recognized stream. */
  157. if(conn && conn->state != AP_CONN_STATE_OPEN && conn->state != EXIT_CONN_STATE_OPEN) {
  158. if(conn->type == CONN_TYPE_EXIT && relay_command == RELAY_COMMAND_END) {
  159. log_fn(LOG_INFO,"Exit got end (%s) before we're connected. Marking for close.",
  160. connection_edge_end_reason(cell->payload+RELAY_HEADER_SIZE, cell->length));
  161. if(conn->state == EXIT_CONN_STATE_RESOLVING) {
  162. log_fn(LOG_INFO,"...and informing resolver we don't want the answer anymore.");
  163. dns_cancel_pending_resolve(conn->address, conn);
  164. }
  165. conn->marked_for_close = 1;
  166. conn->has_sent_end = 1;
  167. return 0;
  168. } else {
  169. log_fn(LOG_WARN,"Got an unexpected relay cell, not in 'open' state. Closing.");
  170. connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
  171. return -1;
  172. }
  173. }
  174. switch(relay_command) {
  175. case RELAY_COMMAND_BEGIN:
  176. if(edge_type == EDGE_AP) {
  177. log_fn(LOG_WARN,"relay begin request unsupported at AP. Dropping.");
  178. return 0;
  179. }
  180. if(conn) {
  181. log_fn(LOG_WARN,"begin cell for known stream. Dropping.");
  182. return 0;
  183. }
  184. connection_exit_begin_conn(cell, circ);
  185. return 0;
  186. case RELAY_COMMAND_DATA:
  187. ++stats_n_data_cells_received;
  188. if((edge_type == EDGE_AP && --layer_hint->deliver_window < 0) ||
  189. (edge_type == EDGE_EXIT && --circ->deliver_window < 0)) {
  190. log_fn(LOG_WARN,"(relay data) circ deliver_window below 0. Killing.");
  191. connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
  192. return -1;
  193. }
  194. log_fn(LOG_DEBUG,"circ deliver_window now %d.", edge_type == EDGE_AP ? layer_hint->deliver_window : circ->deliver_window);
  195. if(circuit_consider_sending_sendme(circ, edge_type, layer_hint) < 0) {
  196. log_fn(LOG_WARN,"circuit_consider_sending_sendme() failed.");
  197. conn->has_sent_end = 1; /* we failed because conn is broken. can't send end. */
  198. return -1;
  199. }
  200. if(!conn) {
  201. log_fn(LOG_INFO,"relay cell dropped, unknown stream %d.",*(int*)conn->stream_id);
  202. return 0;
  203. }
  204. if(--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  205. log_fn(LOG_WARN,"(relay data) conn deliver_window below 0. Killing.");
  206. return -1; /* somebody's breaking protocol. kill the whole circuit. */
  207. }
  208. // printf("New text for buf (%d bytes): '%s'", cell->length - RELAY_HEADER_SIZE, cell->payload + RELAY_HEADER_SIZE);
  209. stats_n_data_bytes_received += (cell->length - RELAY_HEADER_SIZE);
  210. connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
  211. cell->length - RELAY_HEADER_SIZE, conn);
  212. connection_edge_consider_sending_sendme(conn);
  213. return 0;
  214. case RELAY_COMMAND_END:
  215. if(!conn) {
  216. log_fn(LOG_INFO,"end cell (%s) dropped, unknown stream %d.",
  217. connection_edge_end_reason(cell->payload+RELAY_HEADER_SIZE, cell->length),
  218. *(int*)conn->stream_id);
  219. return 0;
  220. }
  221. if(cell->length-RELAY_HEADER_SIZE >= 5 &&
  222. *(cell->payload+RELAY_HEADER_SIZE) == END_STREAM_REASON_EXITPOLICY) {
  223. /* No need to close the connection. We'll hold it open while
  224. * we try a new exit node.
  225. * cell->payload+RELAY_HEADER_SIZE+1 holds the destination addr.
  226. */
  227. addr = ntohl(*(uint32_t*)(cell->payload+RELAY_HEADER_SIZE+1));
  228. client_dns_set_entry(conn->socks_request->address, addr);
  229. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  230. switch(connection_ap_handshake_attach_circuit(conn)) {
  231. case -1: /* it will never work */
  232. break; /* conn will get closed below */
  233. case 0: /* no useful circuits available */
  234. if(!circuit_get_newest(conn, 0)) /* is one already on the way? */
  235. circuit_launch_new();
  236. return 0;
  237. case 1: /* it succeeded, great */
  238. return 0;
  239. }
  240. }
  241. log_fn(LOG_INFO,"end cell (%s) for stream %d. Removing stream.",
  242. connection_edge_end_reason(cell->payload+RELAY_HEADER_SIZE, cell->length),
  243. *(int*)conn->stream_id);
  244. #ifdef HALF_OPEN
  245. conn->done_sending = 1;
  246. shutdown(conn->s, 1); /* XXX check return; refactor NM */
  247. if (conn->done_receiving) {
  248. conn->marked_for_close = 1;
  249. conn->has_sent_end = 1; /* no need to send end, we just got one! */
  250. }
  251. #else
  252. conn->marked_for_close = 1;
  253. conn->has_sent_end = 1; /* no need to send end, we just got one! */
  254. #endif
  255. return 0;
  256. case RELAY_COMMAND_EXTEND:
  257. if(conn) {
  258. log_fn(LOG_WARN,"'extend' for non-zero stream. Dropping.");
  259. return 0;
  260. }
  261. return circuit_extend(cell, circ);
  262. case RELAY_COMMAND_EXTENDED:
  263. if(edge_type == EDGE_EXIT) {
  264. log_fn(LOG_WARN,"'extended' unsupported at exit. Dropping.");
  265. return 0;
  266. }
  267. log_fn(LOG_DEBUG,"Got an extended cell! Yay.");
  268. if(circuit_finish_handshake(circ, cell->payload+RELAY_HEADER_SIZE) < 0) {
  269. log_fn(LOG_WARN,"circuit_finish_handshake failed.");
  270. return -1;
  271. }
  272. if (circuit_send_next_onion_skin(circ)<0) {
  273. log_fn(LOG_WARN,"circuit_send_next_onion_skin() failed.");
  274. return -1;
  275. }
  276. return 0;
  277. case RELAY_COMMAND_TRUNCATE:
  278. if(edge_type == EDGE_AP) {
  279. log_fn(LOG_WARN,"'truncate' unsupported at AP. Dropping.");
  280. return 0;
  281. }
  282. if(circ->n_conn) {
  283. connection_send_destroy(circ->n_circ_id, circ->n_conn);
  284. circ->n_conn = NULL;
  285. }
  286. log_fn(LOG_DEBUG, "Processed 'truncate', replying.");
  287. connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
  288. NULL, 0, NULL);
  289. return 0;
  290. case RELAY_COMMAND_TRUNCATED:
  291. if(edge_type == EDGE_EXIT) {
  292. log_fn(LOG_WARN,"'truncated' unsupported at exit. Dropping.");
  293. return 0;
  294. }
  295. circuit_truncated(circ, layer_hint);
  296. return 0;
  297. case RELAY_COMMAND_CONNECTED:
  298. if(edge_type == EDGE_EXIT) {
  299. log_fn(LOG_WARN,"'connected' unsupported at exit. Dropping.");
  300. return 0;
  301. }
  302. if(!conn) {
  303. log_fn(LOG_INFO,"connected cell dropped, unknown stream %d.",*(int*)conn->stream_id);
  304. return 0;
  305. }
  306. log_fn(LOG_INFO,"Connected! Notifying application.");
  307. if (cell->length-RELAY_HEADER_SIZE == 4) {
  308. addr = ntohl(*(uint32_t*)(cell->payload + RELAY_HEADER_SIZE));
  309. client_dns_set_entry(conn->socks_request->address, addr);
  310. }
  311. if(connection_ap_handshake_socks_reply(conn, NULL, 0, 1) < 0) {
  312. log_fn(LOG_INFO,"Writing to socks-speaking application failed. Closing.");
  313. connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
  314. }
  315. return 0;
  316. case RELAY_COMMAND_SENDME:
  317. if(!conn) {
  318. if(edge_type == EDGE_AP) {
  319. assert(layer_hint);
  320. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  321. log_fn(LOG_DEBUG,"circ-level sendme at AP, packagewindow %d.", layer_hint->package_window);
  322. circuit_resume_edge_reading(circ, EDGE_AP, layer_hint);
  323. } else {
  324. assert(!layer_hint);
  325. circ->package_window += CIRCWINDOW_INCREMENT;
  326. log_fn(LOG_DEBUG,"circ-level sendme at exit, packagewindow %d.", circ->package_window);
  327. circuit_resume_edge_reading(circ, EDGE_EXIT, layer_hint);
  328. }
  329. return 0;
  330. }
  331. conn->package_window += STREAMWINDOW_INCREMENT;
  332. log_fn(LOG_DEBUG,"stream-level sendme, packagewindow now %d.", conn->package_window);
  333. connection_start_reading(conn);
  334. connection_edge_package_raw_inbuf(conn); /* handle whatever might still be on the inbuf */
  335. return 0;
  336. default:
  337. log_fn(LOG_WARN,"unknown relay command %d.",relay_command);
  338. return -1;
  339. }
  340. assert(0);
  341. return -1;
  342. }
  343. int connection_edge_finished_flushing(connection_t *conn) {
  344. unsigned char connected_payload[4];
  345. int e, len=sizeof(e);
  346. assert(conn);
  347. assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
  348. switch(conn->state) {
  349. case EXIT_CONN_STATE_CONNECTING:
  350. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) { /* not yet */
  351. if(!ERRNO_CONN_EINPROGRESS(errno)) {
  352. /* yuck. kill it. */
  353. log_fn(LOG_DEBUG,"in-progress exit connect failed. Removing.");
  354. return -1;
  355. } else {
  356. log_fn(LOG_DEBUG,"in-progress exit connect still waiting.");
  357. return 0; /* no change, see if next time is better */
  358. }
  359. }
  360. /* the connect has finished. */
  361. log_fn(LOG_INFO,"Exit connection to %s:%u established.",
  362. conn->address,conn->port);
  363. conn->state = EXIT_CONN_STATE_OPEN;
  364. connection_watch_events(conn, POLLIN); /* stop writing, continue reading */
  365. if(connection_wants_to_flush(conn)) /* in case there are any queued relay cells */
  366. connection_start_writing(conn);
  367. /* deliver a 'connected' relay cell back through the circuit. */
  368. *(uint32_t*)connected_payload = htonl(conn->addr);
  369. if(connection_edge_send_command(conn, circuit_get_by_conn(conn),
  370. RELAY_COMMAND_CONNECTED, NULL, 0, conn->cpath_layer) < 0)
  371. return 0; /* circuit is closed, don't continue */
  372. return connection_process_inbuf(conn); /* in case the server has written anything */
  373. case AP_CONN_STATE_OPEN:
  374. case EXIT_CONN_STATE_OPEN:
  375. connection_stop_writing(conn);
  376. connection_edge_consider_sending_sendme(conn);
  377. return 0;
  378. case AP_CONN_STATE_SOCKS_WAIT:
  379. connection_stop_writing(conn);
  380. return 0;
  381. default:
  382. log_fn(LOG_WARN,"BUG: called in unexpected state: %d", conn->state);
  383. return -1;
  384. }
  385. return 0;
  386. }
  387. uint64_t stats_n_data_cells_packaged = 0;
  388. uint64_t stats_n_data_bytes_packaged = 0;
  389. uint64_t stats_n_data_cells_received = 0;
  390. uint64_t stats_n_data_bytes_received = 0;
  391. int connection_edge_package_raw_inbuf(connection_t *conn) {
  392. int amount_to_process, length;
  393. char payload[CELL_PAYLOAD_SIZE];
  394. circuit_t *circ;
  395. assert(conn);
  396. assert(!connection_speaks_cells(conn));
  397. repeat_connection_edge_package_raw_inbuf:
  398. circ = circuit_get_by_conn(conn);
  399. if(!circ) {
  400. log_fn(LOG_INFO,"conn has no circuits! Closing.");
  401. return -1;
  402. }
  403. if(circuit_consider_stop_edge_reading(circ, conn->type, conn->cpath_layer))
  404. return 0;
  405. if(conn->package_window <= 0) {
  406. log_fn(LOG_WARN,"called with package_window %d. Tell Roger.", conn->package_window);
  407. connection_stop_reading(conn);
  408. return 0;
  409. }
  410. amount_to_process = buf_datalen(conn->inbuf);
  411. if(!amount_to_process)
  412. return 0;
  413. if(amount_to_process > CELL_PAYLOAD_SIZE - RELAY_HEADER_SIZE) {
  414. length = CELL_PAYLOAD_SIZE - RELAY_HEADER_SIZE;
  415. } else {
  416. length = amount_to_process;
  417. }
  418. stats_n_data_bytes_packaged += length;
  419. stats_n_data_cells_packaged += 1;
  420. connection_fetch_from_buf(payload, length, conn);
  421. log_fn(LOG_DEBUG,"(%d) Packaging %d bytes (%d waiting).",conn->s,length,
  422. (int)buf_datalen(conn->inbuf));
  423. if(connection_edge_send_command(conn, circ, RELAY_COMMAND_DATA,
  424. payload, length, conn->cpath_layer) < 0)
  425. return 0; /* circuit is closed, don't continue */
  426. if(conn->type == CONN_TYPE_EXIT) {
  427. assert(circ->package_window > 0);
  428. circ->package_window--;
  429. } else { /* we're an AP */
  430. assert(conn->type == CONN_TYPE_AP);
  431. assert(conn->cpath_layer->package_window > 0);
  432. conn->cpath_layer->package_window--;
  433. }
  434. if(--conn->package_window <= 0) { /* is it 0 after decrement? */
  435. connection_stop_reading(conn);
  436. log_fn(LOG_DEBUG,"conn->package_window reached 0.");
  437. circuit_consider_stop_edge_reading(circ, conn->type, conn->cpath_layer);
  438. return 0; /* don't process the inbuf any more */
  439. }
  440. log_fn(LOG_DEBUG,"conn->package_window is now %d",conn->package_window);
  441. /* handle more if there's more, or return 0 if there isn't */
  442. goto repeat_connection_edge_package_raw_inbuf;
  443. }
  444. /* Tell any APs that are waiting for a new circuit that one is available */
  445. void connection_ap_attach_pending(void)
  446. {
  447. connection_t **carray;
  448. connection_t *conn;
  449. int n, i;
  450. get_connection_array(&carray, &n);
  451. for (i = 0; i < n; ++i) {
  452. conn = carray[i];
  453. if (conn->type != CONN_TYPE_AP ||
  454. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  455. continue;
  456. switch(connection_ap_handshake_attach_circuit(conn)) {
  457. case -1: /* it will never work */
  458. conn->marked_for_close = 1;
  459. conn->has_sent_end = 1;
  460. break;
  461. case 0: /* we need to build another circuit */
  462. if(!circuit_get_newest(conn, 0)) {
  463. /* if there are no acceptable clean or not-very-dirty circs on the way */
  464. circuit_launch_new();
  465. }
  466. break;
  467. case 1: /* it succeeded, great */
  468. break;
  469. }
  470. }
  471. }
  472. static void connection_edge_consider_sending_sendme(connection_t *conn) {
  473. circuit_t *circ;
  474. if(connection_outbuf_too_full(conn))
  475. return;
  476. circ = circuit_get_by_conn(conn);
  477. if(!circ) {
  478. /* this can legitimately happen if the destroy has already
  479. * arrived and torn down the circuit */
  480. log_fn(LOG_INFO,"No circuit associated with conn. Skipping.");
  481. return;
  482. }
  483. while(conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  484. log_fn(LOG_DEBUG,"Outbuf %d, Queueing stream sendme.", conn->outbuf_flushlen);
  485. conn->deliver_window += STREAMWINDOW_INCREMENT;
  486. if(connection_edge_send_command(conn, circ, RELAY_COMMAND_SENDME,
  487. NULL, 0, conn->cpath_layer) < 0) {
  488. log_fn(LOG_WARN,"connection_edge_send_command failed. Returning.");
  489. return; /* the circuit's closed, don't continue */
  490. }
  491. }
  492. }
  493. static int connection_ap_handshake_process_socks(connection_t *conn) {
  494. socks_request_t *socks;
  495. int sockshere;
  496. assert(conn);
  497. assert(conn->type == CONN_TYPE_AP);
  498. assert(conn->state == AP_CONN_STATE_SOCKS_WAIT);
  499. assert(conn->socks_request);
  500. socks = conn->socks_request;
  501. log_fn(LOG_DEBUG,"entered.");
  502. sockshere = fetch_from_buf_socks(conn->inbuf, socks);
  503. if(sockshere == -1 || sockshere == 0) {
  504. if(socks->replylen) { /* we should send reply back */
  505. log_fn(LOG_DEBUG,"reply is already set for us. Using it.");
  506. connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen, 0);
  507. } else if(sockshere == -1) { /* send normal reject */
  508. log_fn(LOG_WARN,"Fetching socks handshake failed. Closing.");
  509. connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
  510. } else {
  511. log_fn(LOG_DEBUG,"socks handshake not all here yet.");
  512. }
  513. return sockshere;
  514. } /* else socks handshake is done, continue processing */
  515. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  516. switch(connection_ap_handshake_attach_circuit(conn)) {
  517. case -1: /* it will never work */
  518. return -1;
  519. case 0: /* no useful circuits available */
  520. if(!circuit_get_newest(conn, 0)) /* is one already on the way? */
  521. circuit_launch_new();
  522. break;
  523. case 1: /* it succeeded, great */
  524. break;
  525. }
  526. return 0;
  527. }
  528. /* Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  529. * we don't find one: if conn cannot be handled by any known nodes,
  530. * warn and return -1; else tell conn to stop reading and return 0.
  531. * Otherwise, associate conn with a safe live circuit, start
  532. * sending a BEGIN cell down the circuit, and return 1.
  533. */
  534. static int connection_ap_handshake_attach_circuit(connection_t *conn) {
  535. circuit_t *circ;
  536. uint32_t addr;
  537. assert(conn);
  538. assert(conn->type == CONN_TYPE_AP);
  539. assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  540. assert(conn->socks_request);
  541. /* find the circuit that we should use, if there is one. */
  542. circ = circuit_get_newest(conn, 1);
  543. if(!circ) {
  544. log_fn(LOG_INFO,"No safe circuit ready for edge connection; delaying.");
  545. addr = client_dns_lookup_entry(conn->socks_request->address);
  546. if(router_exit_policy_all_routers_reject(addr, conn->socks_request->port)) {
  547. log_fn(LOG_WARN,"No node exists that will handle exit to %s:%d. Rejecting.",
  548. conn->socks_request->address, conn->socks_request->port);
  549. return -1;
  550. }
  551. connection_stop_reading(conn); /* don't read until the connected cell arrives */
  552. return 0;
  553. }
  554. connection_start_reading(conn);
  555. if(!circ->timestamp_dirty)
  556. circ->timestamp_dirty = time(NULL);
  557. /* add it into the linked list of streams on this circuit */
  558. log_fn(LOG_DEBUG,"attaching new conn to circ. n_circ_id %d.", circ->n_circ_id);
  559. conn->next_stream = circ->p_streams;
  560. /* assert_connection_ok(conn, time(NULL)); */
  561. circ->p_streams = conn;
  562. assert(circ->cpath && circ->cpath->prev);
  563. assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  564. conn->cpath_layer = circ->cpath->prev;
  565. connection_ap_handshake_send_begin(conn, circ);
  566. return 1;
  567. }
  568. /* deliver the destaddr:destport in a relay cell */
  569. static void connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ)
  570. {
  571. char payload[CELL_PAYLOAD_SIZE];
  572. int payload_len;
  573. struct in_addr in;
  574. const char *string_addr;
  575. assert(ap_conn->type == CONN_TYPE_AP);
  576. assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  577. assert(ap_conn->socks_request);
  578. crypto_pseudo_rand(STREAM_ID_SIZE, ap_conn->stream_id);
  579. /* FIXME check for collisions */
  580. in.s_addr = htonl(client_dns_lookup_entry(ap_conn->socks_request->address));
  581. string_addr = in.s_addr ? inet_ntoa(in) : NULL;
  582. memcpy(payload, ap_conn->stream_id, STREAM_ID_SIZE);
  583. payload_len = STREAM_ID_SIZE + 1 +
  584. snprintf(payload+STREAM_ID_SIZE,CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE-STREAM_ID_SIZE,
  585. "%s:%d",
  586. string_addr ? string_addr : ap_conn->socks_request->address,
  587. ap_conn->socks_request->port);
  588. log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",*(int *)ap_conn->stream_id);
  589. if(connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_BEGIN,
  590. payload, payload_len, ap_conn->cpath_layer) < 0)
  591. return; /* circuit is closed, don't continue */
  592. ap_conn->package_window = STREAMWINDOW_START;
  593. ap_conn->deliver_window = STREAMWINDOW_START;
  594. ap_conn->state = AP_CONN_STATE_OPEN;
  595. /* XXX Right now, we rely on the socks client not to send us any data
  596. * XXX until we've sent back a socks reply. (If it does, we could wind
  597. * XXX up packaging that data and sending it to the exit, then later having
  598. * XXX the exit refuse us.)
  599. * XXX Perhaps we should grow an AP_CONN_STATE_CONNECTING state.
  600. */
  601. log_fn(LOG_INFO,"Address/port sent, ap socket %d, n_circ_id %d",ap_conn->s,circ->n_circ_id);
  602. return;
  603. }
  604. static int connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
  605. int replylen, char success) {
  606. char buf[256];
  607. if(replylen) { /* we already have a reply in mind */
  608. connection_write_to_buf(reply, replylen, conn);
  609. return flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen); /* try to flush it */
  610. }
  611. assert(conn->socks_request);
  612. if(conn->socks_request->socks_version == 4) {
  613. memset(buf,0,SOCKS4_NETWORK_LEN);
  614. #define SOCKS4_GRANTED 90
  615. #define SOCKS4_REJECT 91
  616. buf[1] = (success ? SOCKS4_GRANTED : SOCKS4_REJECT);
  617. /* leave version, destport, destip zero */
  618. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, conn);
  619. return flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen); /* try to flush it */
  620. }
  621. if(conn->socks_request->socks_version == 5) {
  622. buf[0] = 5; /* version 5 */
  623. #define SOCKS5_SUCCESS 0
  624. #define SOCKS5_GENERIC_ERROR 1
  625. buf[1] = success ? SOCKS5_SUCCESS : SOCKS5_GENERIC_ERROR;
  626. buf[2] = 0;
  627. buf[3] = 1; /* ipv4 addr */
  628. memset(buf+4,0,6); /* Set external addr/port to 0.
  629. The spec doesn't seem to say what to do here. -RD */
  630. connection_write_to_buf(buf,10,conn);
  631. return flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen); /* try to flush it */
  632. }
  633. return 0; /* if socks_version isn't 4 or 5, don't send anything */
  634. }
  635. static int connection_exit_begin_conn(cell_t *cell, circuit_t *circ) {
  636. connection_t *n_stream;
  637. char *colon;
  638. /* XXX currently we don't send an end cell back if we drop the
  639. * begin because it's malformed.
  640. */
  641. if(!memchr(cell->payload+RELAY_HEADER_SIZE+STREAM_ID_SIZE,0,
  642. cell->length-RELAY_HEADER_SIZE-STREAM_ID_SIZE)) {
  643. log_fn(LOG_WARN,"relay begin cell has no \\0. Dropping.");
  644. return 0;
  645. }
  646. colon = strchr(cell->payload+RELAY_HEADER_SIZE+STREAM_ID_SIZE, ':');
  647. if(!colon) {
  648. log_fn(LOG_WARN,"relay begin cell has no colon. Dropping.");
  649. return 0;
  650. }
  651. *colon = 0;
  652. if(!atoi(colon+1)) { /* bad port */
  653. log_fn(LOG_WARN,"relay begin cell has invalid port. Dropping.");
  654. return 0;
  655. }
  656. log_fn(LOG_DEBUG,"Creating new exit connection.");
  657. n_stream = connection_new(CONN_TYPE_EXIT);
  658. memcpy(n_stream->stream_id, cell->payload + RELAY_HEADER_SIZE, STREAM_ID_SIZE);
  659. n_stream->address = tor_strdup(cell->payload + RELAY_HEADER_SIZE + STREAM_ID_SIZE);
  660. n_stream->port = atoi(colon+1);
  661. n_stream->state = EXIT_CONN_STATE_RESOLVING;
  662. /* leave n_stream->s at -1, because it's not yet valid */
  663. n_stream->package_window = STREAMWINDOW_START;
  664. n_stream->deliver_window = STREAMWINDOW_START;
  665. if(connection_add(n_stream) < 0) { /* no space, forget it */
  666. log_fn(LOG_WARN,"connection_add failed. Dropping.");
  667. connection_free(n_stream);
  668. return 0;
  669. }
  670. /* add it into the linked list of streams on this circuit */
  671. n_stream->next_stream = circ->n_streams;
  672. circ->n_streams = n_stream;
  673. /* send it off to the gethostbyname farm */
  674. switch(dns_resolve(n_stream)) {
  675. case 1: /* resolve worked */
  676. connection_exit_connect(n_stream);
  677. return 0;
  678. case -1: /* resolve failed */
  679. log_fn(LOG_INFO,"Resolve failed (%s).", n_stream->address);
  680. connection_edge_end(n_stream, END_STREAM_REASON_RESOLVEFAILED, NULL);
  681. /* case 0, resolve added to pending list */
  682. }
  683. return 0;
  684. }
  685. void connection_exit_connect(connection_t *conn) {
  686. unsigned char connected_payload[4];
  687. if(router_compare_to_my_exit_policy(conn) < 0) {
  688. log_fn(LOG_INFO,"%s:%d failed exit policy. Closing.", conn->address, conn->port);
  689. connection_edge_end(conn, END_STREAM_REASON_EXITPOLICY, NULL);
  690. return;
  691. }
  692. switch(connection_connect(conn, conn->address, conn->addr, conn->port)) {
  693. case -1:
  694. connection_edge_end(conn, END_STREAM_REASON_CONNECTFAILED, NULL);
  695. return;
  696. case 0:
  697. connection_set_poll_socket(conn);
  698. conn->state = EXIT_CONN_STATE_CONNECTING;
  699. connection_watch_events(conn, POLLOUT | POLLIN | POLLERR);
  700. /* writable indicates finish, readable indicates broken link,
  701. error indicates broken link in windowsland. */
  702. return;
  703. /* case 1: fall through */
  704. }
  705. connection_set_poll_socket(conn);
  706. conn->state = EXIT_CONN_STATE_OPEN;
  707. if(connection_wants_to_flush(conn)) { /* in case there are any queued data cells */
  708. log_fn(LOG_WARN,"tell roger: newly connected conn had data waiting!");
  709. // connection_start_writing(conn);
  710. }
  711. // connection_process_inbuf(conn);
  712. connection_watch_events(conn, POLLIN);
  713. /* also, deliver a 'connected' cell back through the circuit. */
  714. *((uint32_t*) connected_payload) = htonl(conn->addr);
  715. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
  716. connected_payload, 4, conn->cpath_layer);
  717. }
  718. int connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit)
  719. {
  720. uint32_t addr;
  721. assert(conn);
  722. assert(conn->type == CONN_TYPE_AP);
  723. assert(conn->socks_request);
  724. log_fn(LOG_DEBUG,"considering nickname %s, for address %s / port %d:",
  725. exit->nickname, conn->socks_request->address,
  726. conn->socks_request->port);
  727. addr = client_dns_lookup_entry(conn->socks_request->address);
  728. return router_supports_exit_address(addr, conn->socks_request->port, exit);
  729. }
  730. /* ***** Client DNS code ***** */
  731. #define MAX_DNS_ENTRY_AGE 30*60
  732. /* XXX Perhaps this should get merged with the dns.c code somehow. */
  733. struct client_dns_entry {
  734. SPLAY_ENTRY(client_dns_entry) node;
  735. char *address;
  736. uint32_t addr;
  737. time_t expires;
  738. };
  739. static int client_dns_size = 0;
  740. static SPLAY_HEAD(client_dns_tree, client_dns_entry) client_dns_root;
  741. static int compare_client_dns_entries(struct client_dns_entry *a,
  742. struct client_dns_entry *b)
  743. {
  744. return strcasecmp(a->address, b->address);
  745. }
  746. static void client_dns_entry_free(struct client_dns_entry *ent)
  747. {
  748. tor_free(ent->address);
  749. tor_free(ent);
  750. }
  751. SPLAY_PROTOTYPE(client_dns_tree, client_dns_entry, node, compare_client_dns_entries);
  752. SPLAY_GENERATE(client_dns_tree, client_dns_entry, node, compare_client_dns_entries);
  753. void client_dns_init(void) {
  754. SPLAY_INIT(&client_dns_root);
  755. client_dns_size = 0;
  756. }
  757. static uint32_t client_dns_lookup_entry(const char *address)
  758. {
  759. struct client_dns_entry *ent;
  760. struct client_dns_entry search;
  761. struct in_addr in;
  762. time_t now;
  763. assert(address);
  764. if (inet_aton(address, &in)) {
  765. log_fn(LOG_DEBUG, "Using static address %s (%08X)", address,
  766. ntohl(in.s_addr));
  767. return ntohl(in.s_addr);
  768. }
  769. search.address = (char*)address;
  770. ent = SPLAY_FIND(client_dns_tree, &client_dns_root, &search);
  771. if (!ent) {
  772. log_fn(LOG_DEBUG, "No entry found for address %s", address);
  773. return 0;
  774. } else {
  775. now = time(NULL);
  776. if (ent->expires < now) {
  777. log_fn(LOG_DEBUG, "Expired entry found for address %s", address);
  778. SPLAY_REMOVE(client_dns_tree, &client_dns_root, ent);
  779. client_dns_entry_free(ent);
  780. --client_dns_size;
  781. return 0;
  782. }
  783. in.s_addr = htonl(ent->addr);
  784. log_fn(LOG_DEBUG, "Found cached entry for address %s: %s", address,
  785. inet_ntoa(in));
  786. return ent->addr;
  787. }
  788. }
  789. static void client_dns_set_entry(const char *address, uint32_t val)
  790. {
  791. struct client_dns_entry *ent;
  792. struct client_dns_entry search;
  793. struct in_addr in;
  794. time_t now;
  795. assert(address);
  796. assert(val);
  797. if (inet_aton(address, &in)) {
  798. if (ntohl(in.s_addr) == val)
  799. return;
  800. in.s_addr = htonl(val);
  801. log_fn(LOG_WARN,
  802. "Trying to store incompatible cached value %s for static address %s",
  803. inet_ntoa(in), address);
  804. return;
  805. }
  806. search.address = (char*) address;
  807. now = time(NULL);
  808. ent = SPLAY_FIND(client_dns_tree, &client_dns_root, &search);
  809. if (ent) {
  810. in.s_addr = htonl(val);
  811. log_fn(LOG_DEBUG, "Updating entry for address %s: %s", address,
  812. inet_ntoa(in));
  813. ent->addr = val;
  814. ent->expires = now+MAX_DNS_ENTRY_AGE;
  815. } else {
  816. in.s_addr = htonl(val);
  817. log_fn(LOG_DEBUG, "Caching result for address %s: %s", address,
  818. inet_ntoa(in));
  819. ent = tor_malloc(sizeof(struct client_dns_entry));
  820. ent->address = tor_strdup(address);
  821. ent->addr = val;
  822. ent->expires = now+MAX_DNS_ENTRY_AGE;
  823. SPLAY_INSERT(client_dns_tree, &client_dns_root, ent);
  824. ++client_dns_size;
  825. }
  826. }
  827. void client_dns_clean(void)
  828. {
  829. struct client_dns_entry **expired_entries;
  830. int n_expired_entries = 0;
  831. struct client_dns_entry *ent;
  832. time_t now;
  833. int i;
  834. if(!client_dns_size)
  835. return;
  836. expired_entries = tor_malloc(client_dns_size *
  837. sizeof(struct client_dns_entry *));
  838. now = time(NULL);
  839. SPLAY_FOREACH(ent, client_dns_tree, &client_dns_root) {
  840. if (ent->expires < now) {
  841. expired_entries[n_expired_entries++] = ent;
  842. }
  843. }
  844. for (i = 0; i < n_expired_entries; ++i) {
  845. SPLAY_REMOVE(client_dns_tree, &client_dns_root, expired_entries[i]);
  846. client_dns_entry_free(expired_entries[i]);
  847. }
  848. tor_free(expired_entries);
  849. }
  850. /*
  851. Local Variables:
  852. mode:c
  853. indent-tabs-mode:nil
  854. c-basic-offset:2
  855. End:
  856. */