connection_edge.c 46 KB

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