connection_edge.c 42 KB

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