connection_edge.c 49 KB

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