connection_edge.c 47 KB

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