connection_edge.c 36 KB

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