connection_edge.c 36 KB

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