connection_edge.c 37 KB

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