connection_edge.c 37 KB

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