connection_edge.c 37 KB

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