connection_edge.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  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. assert(conn->package_window > 0);
  373. return connection_edge_process_inbuf(conn); /* in case the server has written anything */
  374. case AP_CONN_STATE_OPEN:
  375. case EXIT_CONN_STATE_OPEN:
  376. connection_stop_writing(conn);
  377. connection_edge_consider_sending_sendme(conn);
  378. return 0;
  379. case AP_CONN_STATE_SOCKS_WAIT:
  380. connection_stop_writing(conn);
  381. return 0;
  382. default:
  383. log_fn(LOG_WARN,"BUG: called in unexpected state: %d", conn->state);
  384. return -1;
  385. }
  386. return 0;
  387. }
  388. uint64_t stats_n_data_cells_packaged = 0;
  389. uint64_t stats_n_data_bytes_packaged = 0;
  390. uint64_t stats_n_data_cells_received = 0;
  391. uint64_t stats_n_data_bytes_received = 0;
  392. int connection_edge_package_raw_inbuf(connection_t *conn) {
  393. int amount_to_process, length;
  394. char payload[CELL_PAYLOAD_SIZE];
  395. circuit_t *circ;
  396. assert(conn);
  397. assert(!connection_speaks_cells(conn));
  398. repeat_connection_edge_package_raw_inbuf:
  399. circ = circuit_get_by_conn(conn);
  400. if(!circ) {
  401. log_fn(LOG_INFO,"conn has no circuits! Closing.");
  402. return -1;
  403. }
  404. if(circuit_consider_stop_edge_reading(circ, conn->type, conn->cpath_layer))
  405. return 0;
  406. if(conn->package_window <= 0) {
  407. log_fn(LOG_WARN,"called with package_window %d. Tell Roger.", conn->package_window);
  408. connection_stop_reading(conn);
  409. return 0;
  410. }
  411. amount_to_process = buf_datalen(conn->inbuf);
  412. if(!amount_to_process)
  413. return 0;
  414. if(amount_to_process > CELL_PAYLOAD_SIZE - RELAY_HEADER_SIZE) {
  415. length = CELL_PAYLOAD_SIZE - RELAY_HEADER_SIZE;
  416. } else {
  417. length = amount_to_process;
  418. }
  419. stats_n_data_bytes_packaged += length;
  420. stats_n_data_cells_packaged += 1;
  421. connection_fetch_from_buf(payload, length, conn);
  422. log_fn(LOG_DEBUG,"(%d) Packaging %d bytes (%d waiting).",conn->s,length,
  423. (int)buf_datalen(conn->inbuf));
  424. if(connection_edge_send_command(conn, circ, RELAY_COMMAND_DATA,
  425. payload, length, conn->cpath_layer) < 0)
  426. return 0; /* circuit is closed, don't continue */
  427. if(conn->type == CONN_TYPE_EXIT) {
  428. assert(circ->package_window > 0);
  429. circ->package_window--;
  430. } else { /* we're an AP */
  431. assert(conn->type == CONN_TYPE_AP);
  432. assert(conn->cpath_layer->package_window > 0);
  433. conn->cpath_layer->package_window--;
  434. }
  435. if(--conn->package_window <= 0) { /* is it 0 after decrement? */
  436. connection_stop_reading(conn);
  437. log_fn(LOG_DEBUG,"conn->package_window reached 0.");
  438. circuit_consider_stop_edge_reading(circ, conn->type, conn->cpath_layer);
  439. return 0; /* don't process the inbuf any more */
  440. }
  441. log_fn(LOG_DEBUG,"conn->package_window is now %d",conn->package_window);
  442. /* handle more if there's more, or return 0 if there isn't */
  443. goto repeat_connection_edge_package_raw_inbuf;
  444. }
  445. /* Tell any APs that are waiting for a new circuit that one is available */
  446. void connection_ap_attach_pending(void)
  447. {
  448. connection_t **carray;
  449. connection_t *conn;
  450. int n, i;
  451. get_connection_array(&carray, &n);
  452. for (i = 0; i < n; ++i) {
  453. conn = carray[i];
  454. if (conn->type != CONN_TYPE_AP ||
  455. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  456. continue;
  457. switch(connection_ap_handshake_attach_circuit(conn)) {
  458. case -1: /* it will never work */
  459. conn->marked_for_close = 1;
  460. conn->has_sent_end = 1;
  461. break;
  462. case 0: /* we need to build another circuit */
  463. if(!circuit_get_newest(conn, 0)) {
  464. /* if there are no acceptable clean or not-very-dirty circs on the way */
  465. circuit_launch_new();
  466. }
  467. break;
  468. case 1: /* it succeeded, great */
  469. break;
  470. }
  471. }
  472. }
  473. static void connection_edge_consider_sending_sendme(connection_t *conn) {
  474. circuit_t *circ;
  475. if(connection_outbuf_too_full(conn))
  476. return;
  477. circ = circuit_get_by_conn(conn);
  478. if(!circ) {
  479. /* this can legitimately happen if the destroy has already
  480. * arrived and torn down the circuit */
  481. log_fn(LOG_INFO,"No circuit associated with conn. Skipping.");
  482. return;
  483. }
  484. while(conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  485. log_fn(LOG_DEBUG,"Outbuf %d, Queueing stream sendme.", conn->outbuf_flushlen);
  486. conn->deliver_window += STREAMWINDOW_INCREMENT;
  487. if(connection_edge_send_command(conn, circ, RELAY_COMMAND_SENDME,
  488. NULL, 0, conn->cpath_layer) < 0) {
  489. log_fn(LOG_WARN,"connection_edge_send_command failed. Returning.");
  490. return; /* the circuit's closed, don't continue */
  491. }
  492. }
  493. }
  494. static int connection_ap_handshake_process_socks(connection_t *conn) {
  495. socks_request_t *socks;
  496. int sockshere;
  497. assert(conn);
  498. assert(conn->type == CONN_TYPE_AP);
  499. assert(conn->state == AP_CONN_STATE_SOCKS_WAIT);
  500. assert(conn->socks_request);
  501. socks = conn->socks_request;
  502. log_fn(LOG_DEBUG,"entered.");
  503. sockshere = fetch_from_buf_socks(conn->inbuf, socks);
  504. if(sockshere == -1 || sockshere == 0) {
  505. if(socks->replylen) { /* we should send reply back */
  506. log_fn(LOG_DEBUG,"reply is already set for us. Using it.");
  507. connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen, 0);
  508. } else if(sockshere == -1) { /* send normal reject */
  509. log_fn(LOG_WARN,"Fetching socks handshake failed. Closing.");
  510. connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
  511. } else {
  512. log_fn(LOG_DEBUG,"socks handshake not all here yet.");
  513. }
  514. return sockshere;
  515. } /* else socks handshake is done, continue processing */
  516. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  517. switch(connection_ap_handshake_attach_circuit(conn)) {
  518. case -1: /* it will never work */
  519. return -1;
  520. case 0: /* no useful circuits available */
  521. if(!circuit_get_newest(conn, 0)) /* is one already on the way? */
  522. circuit_launch_new();
  523. break;
  524. case 1: /* it succeeded, great */
  525. break;
  526. }
  527. return 0;
  528. }
  529. /* Try to find a safe live circuit for CONN_TYPE_AP connection conn. If
  530. * we don't find one: if conn cannot be handled by any known nodes,
  531. * warn and return -1; else tell conn to stop reading and return 0.
  532. * Otherwise, associate conn with a safe live circuit, start
  533. * sending a BEGIN cell down the circuit, and return 1.
  534. */
  535. static int connection_ap_handshake_attach_circuit(connection_t *conn) {
  536. circuit_t *circ;
  537. uint32_t addr;
  538. assert(conn);
  539. assert(conn->type == CONN_TYPE_AP);
  540. assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  541. assert(conn->socks_request);
  542. /* find the circuit that we should use, if there is one. */
  543. circ = circuit_get_newest(conn, 1);
  544. if(!circ) {
  545. log_fn(LOG_INFO,"No safe circuit ready for edge connection; delaying.");
  546. addr = client_dns_lookup_entry(conn->socks_request->address);
  547. if(router_exit_policy_all_routers_reject(addr, conn->socks_request->port)) {
  548. log_fn(LOG_WARN,"No node exists that will handle exit to %s:%d. Rejecting.",
  549. conn->socks_request->address, conn->socks_request->port);
  550. return -1;
  551. }
  552. connection_stop_reading(conn); /* don't read until the connected cell arrives */
  553. return 0;
  554. }
  555. connection_start_reading(conn);
  556. if(!circ->timestamp_dirty)
  557. circ->timestamp_dirty = time(NULL);
  558. /* add it into the linked list of streams on this circuit */
  559. log_fn(LOG_DEBUG,"attaching new conn to circ. n_circ_id %d.", circ->n_circ_id);
  560. conn->next_stream = circ->p_streams;
  561. /* assert_connection_ok(conn, time(NULL)); */
  562. circ->p_streams = conn;
  563. assert(circ->cpath && circ->cpath->prev);
  564. assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
  565. conn->cpath_layer = circ->cpath->prev;
  566. connection_ap_handshake_send_begin(conn, circ);
  567. return 1;
  568. }
  569. /* deliver the destaddr:destport in a relay cell */
  570. static void connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ)
  571. {
  572. char payload[CELL_PAYLOAD_SIZE];
  573. int payload_len;
  574. struct in_addr in;
  575. const char *string_addr;
  576. assert(ap_conn->type == CONN_TYPE_AP);
  577. assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  578. assert(ap_conn->socks_request);
  579. crypto_pseudo_rand(STREAM_ID_SIZE, ap_conn->stream_id);
  580. /* FIXME check for collisions */
  581. in.s_addr = htonl(client_dns_lookup_entry(ap_conn->socks_request->address));
  582. string_addr = in.s_addr ? inet_ntoa(in) : NULL;
  583. memcpy(payload, ap_conn->stream_id, STREAM_ID_SIZE);
  584. payload_len = STREAM_ID_SIZE + 1 +
  585. snprintf(payload+STREAM_ID_SIZE,CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE-STREAM_ID_SIZE,
  586. "%s:%d",
  587. string_addr ? string_addr : ap_conn->socks_request->address,
  588. ap_conn->socks_request->port);
  589. log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",*(int *)ap_conn->stream_id);
  590. if(connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_BEGIN,
  591. payload, payload_len, ap_conn->cpath_layer) < 0)
  592. return; /* circuit is closed, don't continue */
  593. ap_conn->package_window = STREAMWINDOW_START;
  594. ap_conn->deliver_window = STREAMWINDOW_START;
  595. ap_conn->state = AP_CONN_STATE_OPEN;
  596. /* XXX Right now, we rely on the socks client not to send us any data
  597. * XXX until we've sent back a socks reply. (If it does, we could wind
  598. * XXX up packaging that data and sending it to the exit, then later having
  599. * XXX the exit refuse us.)
  600. * XXX Perhaps we should grow an AP_CONN_STATE_CONNECTING state.
  601. */
  602. log_fn(LOG_INFO,"Address/port sent, ap socket %d, n_circ_id %d",ap_conn->s,circ->n_circ_id);
  603. return;
  604. }
  605. static int connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
  606. int replylen, char success) {
  607. char buf[256];
  608. if(replylen) { /* we already have a reply in mind */
  609. connection_write_to_buf(reply, replylen, conn);
  610. return flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen); /* try to flush it */
  611. }
  612. assert(conn->socks_request);
  613. if(conn->socks_request->socks_version == 4) {
  614. memset(buf,0,SOCKS4_NETWORK_LEN);
  615. #define SOCKS4_GRANTED 90
  616. #define SOCKS4_REJECT 91
  617. buf[1] = (success ? SOCKS4_GRANTED : SOCKS4_REJECT);
  618. /* leave version, destport, destip zero */
  619. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, conn);
  620. return flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen); /* try to flush it */
  621. }
  622. if(conn->socks_request->socks_version == 5) {
  623. buf[0] = 5; /* version 5 */
  624. #define SOCKS5_SUCCESS 0
  625. #define SOCKS5_GENERIC_ERROR 1
  626. buf[1] = success ? SOCKS5_SUCCESS : SOCKS5_GENERIC_ERROR;
  627. buf[2] = 0;
  628. buf[3] = 1; /* ipv4 addr */
  629. memset(buf+4,0,6); /* Set external addr/port to 0.
  630. The spec doesn't seem to say what to do here. -RD */
  631. connection_write_to_buf(buf,10,conn);
  632. return flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen); /* try to flush it */
  633. }
  634. return 0; /* if socks_version isn't 4 or 5, don't send anything */
  635. }
  636. static int connection_exit_begin_conn(cell_t *cell, circuit_t *circ) {
  637. connection_t *n_stream;
  638. char *colon;
  639. /* XXX currently we don't send an end cell back if we drop the
  640. * begin because it's malformed.
  641. */
  642. if(!memchr(cell->payload+RELAY_HEADER_SIZE+STREAM_ID_SIZE,0,
  643. cell->length-RELAY_HEADER_SIZE-STREAM_ID_SIZE)) {
  644. log_fn(LOG_WARN,"relay begin cell has no \\0. Dropping.");
  645. return 0;
  646. }
  647. colon = strchr(cell->payload+RELAY_HEADER_SIZE+STREAM_ID_SIZE, ':');
  648. if(!colon) {
  649. log_fn(LOG_WARN,"relay begin cell has no colon. Dropping.");
  650. return 0;
  651. }
  652. *colon = 0;
  653. if(!atoi(colon+1)) { /* bad port */
  654. log_fn(LOG_WARN,"relay begin cell has invalid port. Dropping.");
  655. return 0;
  656. }
  657. log_fn(LOG_DEBUG,"Creating new exit connection.");
  658. n_stream = connection_new(CONN_TYPE_EXIT);
  659. memcpy(n_stream->stream_id, cell->payload + RELAY_HEADER_SIZE, STREAM_ID_SIZE);
  660. n_stream->address = tor_strdup(cell->payload + RELAY_HEADER_SIZE + STREAM_ID_SIZE);
  661. n_stream->port = atoi(colon+1);
  662. n_stream->state = EXIT_CONN_STATE_RESOLVING;
  663. /* leave n_stream->s at -1, because it's not yet valid */
  664. n_stream->package_window = STREAMWINDOW_START;
  665. n_stream->deliver_window = STREAMWINDOW_START;
  666. if(connection_add(n_stream) < 0) { /* no space, forget it */
  667. log_fn(LOG_WARN,"connection_add failed. Dropping.");
  668. connection_free(n_stream);
  669. return 0;
  670. }
  671. /* add it into the linked list of streams on this circuit */
  672. n_stream->next_stream = circ->n_streams;
  673. circ->n_streams = n_stream;
  674. /* send it off to the gethostbyname farm */
  675. switch(dns_resolve(n_stream)) {
  676. case 1: /* resolve worked */
  677. connection_exit_connect(n_stream);
  678. return 0;
  679. case -1: /* resolve failed */
  680. log_fn(LOG_INFO,"Resolve failed (%s).", n_stream->address);
  681. connection_edge_end(n_stream, END_STREAM_REASON_RESOLVEFAILED, NULL);
  682. /* case 0, resolve added to pending list */
  683. }
  684. return 0;
  685. }
  686. void connection_exit_connect(connection_t *conn) {
  687. unsigned char connected_payload[4];
  688. if(router_compare_to_my_exit_policy(conn) < 0) {
  689. log_fn(LOG_INFO,"%s:%d failed exit policy. Closing.", conn->address, conn->port);
  690. connection_edge_end(conn, END_STREAM_REASON_EXITPOLICY, NULL);
  691. return;
  692. }
  693. switch(connection_connect(conn, conn->address, conn->addr, conn->port)) {
  694. case -1:
  695. connection_edge_end(conn, END_STREAM_REASON_CONNECTFAILED, NULL);
  696. return;
  697. case 0:
  698. connection_set_poll_socket(conn);
  699. conn->state = EXIT_CONN_STATE_CONNECTING;
  700. connection_watch_events(conn, POLLOUT | POLLIN | POLLERR);
  701. /* writable indicates finish, readable indicates broken link,
  702. error indicates broken link in windowsland. */
  703. return;
  704. /* case 1: fall through */
  705. }
  706. connection_set_poll_socket(conn);
  707. conn->state = EXIT_CONN_STATE_OPEN;
  708. if(connection_wants_to_flush(conn)) { /* in case there are any queued data cells */
  709. log_fn(LOG_WARN,"tell roger: newly connected conn had data waiting!");
  710. // connection_start_writing(conn);
  711. }
  712. // connection_process_inbuf(conn);
  713. connection_watch_events(conn, POLLIN);
  714. /* also, deliver a 'connected' cell back through the circuit. */
  715. *((uint32_t*) connected_payload) = htonl(conn->addr);
  716. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
  717. connected_payload, 4, conn->cpath_layer);
  718. }
  719. int connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit)
  720. {
  721. uint32_t addr;
  722. assert(conn);
  723. assert(conn->type == CONN_TYPE_AP);
  724. assert(conn->socks_request);
  725. log_fn(LOG_DEBUG,"considering nickname %s, for address %s / port %d:",
  726. exit->nickname, conn->socks_request->address,
  727. conn->socks_request->port);
  728. addr = client_dns_lookup_entry(conn->socks_request->address);
  729. return router_supports_exit_address(addr, conn->socks_request->port, exit);
  730. }
  731. /* ***** Client DNS code ***** */
  732. #define MAX_DNS_ENTRY_AGE 30*60
  733. /* XXX Perhaps this should get merged with the dns.c code somehow. */
  734. struct client_dns_entry {
  735. SPLAY_ENTRY(client_dns_entry) node;
  736. char *address;
  737. uint32_t addr;
  738. time_t expires;
  739. };
  740. static int client_dns_size = 0;
  741. static SPLAY_HEAD(client_dns_tree, client_dns_entry) client_dns_root;
  742. static int compare_client_dns_entries(struct client_dns_entry *a,
  743. struct client_dns_entry *b)
  744. {
  745. return strcasecmp(a->address, b->address);
  746. }
  747. static void client_dns_entry_free(struct client_dns_entry *ent)
  748. {
  749. tor_free(ent->address);
  750. tor_free(ent);
  751. }
  752. SPLAY_PROTOTYPE(client_dns_tree, client_dns_entry, node, compare_client_dns_entries);
  753. SPLAY_GENERATE(client_dns_tree, client_dns_entry, node, compare_client_dns_entries);
  754. void client_dns_init(void) {
  755. SPLAY_INIT(&client_dns_root);
  756. client_dns_size = 0;
  757. }
  758. static uint32_t client_dns_lookup_entry(const char *address)
  759. {
  760. struct client_dns_entry *ent;
  761. struct client_dns_entry search;
  762. struct in_addr in;
  763. time_t now;
  764. assert(address);
  765. if (inet_aton(address, &in)) {
  766. log_fn(LOG_DEBUG, "Using static address %s (%08X)", address,
  767. ntohl(in.s_addr));
  768. return ntohl(in.s_addr);
  769. }
  770. search.address = (char*)address;
  771. ent = SPLAY_FIND(client_dns_tree, &client_dns_root, &search);
  772. if (!ent) {
  773. log_fn(LOG_DEBUG, "No entry found for address %s", address);
  774. return 0;
  775. } else {
  776. now = time(NULL);
  777. if (ent->expires < now) {
  778. log_fn(LOG_DEBUG, "Expired entry found for address %s", address);
  779. SPLAY_REMOVE(client_dns_tree, &client_dns_root, ent);
  780. client_dns_entry_free(ent);
  781. --client_dns_size;
  782. return 0;
  783. }
  784. in.s_addr = htonl(ent->addr);
  785. log_fn(LOG_DEBUG, "Found cached entry for address %s: %s", address,
  786. inet_ntoa(in));
  787. return ent->addr;
  788. }
  789. }
  790. static void client_dns_set_entry(const char *address, uint32_t val)
  791. {
  792. struct client_dns_entry *ent;
  793. struct client_dns_entry search;
  794. struct in_addr in;
  795. time_t now;
  796. assert(address);
  797. assert(val);
  798. if (inet_aton(address, &in)) {
  799. if (ntohl(in.s_addr) == val)
  800. return;
  801. in.s_addr = htonl(val);
  802. log_fn(LOG_WARN,
  803. "Trying to store incompatible cached value %s for static address %s",
  804. inet_ntoa(in), address);
  805. return;
  806. }
  807. search.address = (char*) address;
  808. now = time(NULL);
  809. ent = SPLAY_FIND(client_dns_tree, &client_dns_root, &search);
  810. if (ent) {
  811. in.s_addr = htonl(val);
  812. log_fn(LOG_DEBUG, "Updating entry for address %s: %s", address,
  813. inet_ntoa(in));
  814. ent->addr = val;
  815. ent->expires = now+MAX_DNS_ENTRY_AGE;
  816. } else {
  817. in.s_addr = htonl(val);
  818. log_fn(LOG_DEBUG, "Caching result for address %s: %s", address,
  819. inet_ntoa(in));
  820. ent = tor_malloc(sizeof(struct client_dns_entry));
  821. ent->address = tor_strdup(address);
  822. ent->addr = val;
  823. ent->expires = now+MAX_DNS_ENTRY_AGE;
  824. SPLAY_INSERT(client_dns_tree, &client_dns_root, ent);
  825. ++client_dns_size;
  826. }
  827. }
  828. void client_dns_clean(void)
  829. {
  830. struct client_dns_entry **expired_entries;
  831. int n_expired_entries = 0;
  832. struct client_dns_entry *ent;
  833. time_t now;
  834. int i;
  835. if(!client_dns_size)
  836. return;
  837. expired_entries = tor_malloc(client_dns_size *
  838. sizeof(struct client_dns_entry *));
  839. now = time(NULL);
  840. SPLAY_FOREACH(ent, client_dns_tree, &client_dns_root) {
  841. if (ent->expires < now) {
  842. expired_entries[n_expired_entries++] = ent;
  843. }
  844. }
  845. for (i = 0; i < n_expired_entries; ++i) {
  846. SPLAY_REMOVE(client_dns_tree, &client_dns_root, expired_entries[i]);
  847. client_dns_entry_free(expired_entries[i]);
  848. }
  849. tor_free(expired_entries);
  850. }
  851. /*
  852. Local Variables:
  853. mode:c
  854. indent-tabs-mode:nil
  855. c-basic-offset:2
  856. End:
  857. */