connection.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "or.h"
  5. /********* START VARIABLES **********/
  6. extern or_options_t options; /* command-line and config-file options */
  7. char *conn_type_to_string[] = {
  8. "", /* 0 */
  9. "OP listener", /* 1 */
  10. "OP", /* 2 */
  11. "OR listener", /* 3 */
  12. "OR", /* 4 */
  13. "Exit", /* 5 */
  14. "App listener",/* 6 */
  15. "App", /* 7 */
  16. "Dir listener",/* 8 */
  17. "Dir", /* 9 */
  18. "DNS worker", /* 10 */
  19. "CPU worker", /* 11 */
  20. };
  21. char *conn_state_to_string[][_CONN_TYPE_MAX+1] = {
  22. { NULL }, /* no type associated with 0 */
  23. { NULL }, /* op listener, obsolete */
  24. { NULL }, /* op, obsolete */
  25. { "ready" }, /* or listener, 0 */
  26. { "", /* OR, 0 */
  27. "connect()ing", /* 1 */
  28. "handshaking", /* 2 */
  29. "open" }, /* 3 */
  30. { "", /* exit, 0 */
  31. "waiting for dest info", /* 1 */
  32. "connecting", /* 2 */
  33. "open", /* 3 */
  34. "resolve failed" }, /* 4 */
  35. { "ready" }, /* app listener, 0 */
  36. { "", /* 0 */
  37. "", /* 1 */
  38. "", /* 2 */
  39. "", /* 3 */
  40. "", /* 4 */
  41. "awaiting dest info", /* app, 5 */
  42. "waiting for safe circuit", /* 6 */
  43. "waiting for connected", /* 7 */
  44. "open" }, /* 8 */
  45. { "ready" }, /* dir listener, 0 */
  46. { "", /* dir, 0 */
  47. "connecting", /* 1 */
  48. "client sending", /* 2 */
  49. "client reading", /* 3 */
  50. "awaiting command", /* 4 */
  51. "writing" }, /* 5 */
  52. { "", /* dns worker, 0 */
  53. "idle", /* 1 */
  54. "busy" }, /* 2 */
  55. { "", /* cpu worker, 0 */
  56. "idle", /* 1 */
  57. "busy with onion", /* 2 */
  58. "busy with handshake" }, /* 3 */
  59. };
  60. /********* END VARIABLES ************/
  61. static int connection_init_accepted_conn(connection_t *conn);
  62. static int connection_handle_listener_read(connection_t *conn, int new_type);
  63. static int connection_receiver_bucket_should_increase(connection_t *conn);
  64. /**************************************************************/
  65. connection_t *connection_new(int type) {
  66. connection_t *conn;
  67. time_t now = time(NULL);
  68. conn = tor_malloc_zero(sizeof(connection_t));
  69. conn->magic = CONNECTION_MAGIC;
  70. conn->s = -1; /* give it a default of 'not used' */
  71. conn->type = type;
  72. if(!connection_is_listener(conn)) { /* listeners never use their buf */
  73. conn->inbuf = buf_new();
  74. conn->outbuf = buf_new();
  75. }
  76. if (type == CONN_TYPE_AP) {
  77. conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
  78. }
  79. conn->next_circ_id = crypto_pseudo_rand_int(1<<15);
  80. conn->timestamp_created = now;
  81. conn->timestamp_lastread = now;
  82. conn->timestamp_lastwritten = now;
  83. return conn;
  84. }
  85. void connection_free(connection_t *conn) {
  86. assert(conn);
  87. assert(conn->magic == CONNECTION_MAGIC);
  88. if(!connection_is_listener(conn)) {
  89. buf_free(conn->inbuf);
  90. buf_free(conn->outbuf);
  91. }
  92. tor_free(conn->address);
  93. if(connection_speaks_cells(conn)) {
  94. directory_set_dirty();
  95. if (conn->tls)
  96. tor_tls_free(conn->tls);
  97. }
  98. if (conn->onion_pkey)
  99. crypto_free_pk_env(conn->onion_pkey);
  100. if (conn->link_pkey)
  101. crypto_free_pk_env(conn->link_pkey);
  102. if (conn->identity_pkey)
  103. crypto_free_pk_env(conn->identity_pkey);
  104. tor_free(conn->nickname);
  105. tor_free(conn->socks_request);
  106. if(conn->s >= 0) {
  107. log_fn(LOG_INFO,"closing fd %d.",conn->s);
  108. close(conn->s);
  109. }
  110. memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
  111. free(conn);
  112. }
  113. void connection_free_all(void) {
  114. int i, n;
  115. connection_t **carray;
  116. get_connection_array(&carray,&n);
  117. for(i=0;i<n;i++)
  118. connection_free(carray[i]);
  119. }
  120. /* Close the underlying socket for conn, so we don't try to flush it.
  121. * Must be used in conjunction with (right before) connection_mark_for_close
  122. */
  123. void connection_close_immediate(connection_t *conn)
  124. {
  125. assert_connection_ok(conn,0);
  126. if (conn->s < 0) {
  127. log_fn(LOG_WARN,"Attempt to close already-closed connection.");
  128. return;
  129. }
  130. if (conn->outbuf_flushlen) {
  131. log_fn(LOG_INFO,"Closing connection (fd %d, type %s, state %d) with data on outbuf.",
  132. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state);
  133. }
  134. close(conn->s);
  135. conn->s = -1;
  136. if(!connection_is_listener(conn)) {
  137. buf_clear(conn->outbuf);
  138. conn->outbuf_flushlen = 0;
  139. }
  140. }
  141. int
  142. _connection_mark_for_close(connection_t *conn, char reason)
  143. {
  144. int retval = 0;
  145. assert_connection_ok(conn,0);
  146. if (conn->marked_for_close) {
  147. log(LOG_WARN, "Double mark-for-close on connection.");
  148. return -1;
  149. }
  150. switch (conn->type)
  151. {
  152. case CONN_TYPE_OR_LISTENER:
  153. case CONN_TYPE_AP_LISTENER:
  154. case CONN_TYPE_DIR_LISTENER:
  155. case CONN_TYPE_CPUWORKER:
  156. /* No special processing needed. */
  157. break;
  158. case CONN_TYPE_DIR:
  159. if(conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
  160. rend_client_desc_fetched(conn->rend_query, 0);
  161. break;
  162. case CONN_TYPE_OR:
  163. /* Remember why we're closing this connection. */
  164. if (conn->state != OR_CONN_STATE_OPEN) {
  165. /* XXX Nick: this still isn't right, because it might be
  166. * dying even though we didn't initiate the connect. Can
  167. * you look at this more? -RD */
  168. if(conn->nickname)
  169. rep_hist_note_connect_failed(conn->nickname, time(NULL));
  170. } else if (reason == CLOSE_REASON_UNUSED_OR_CONN) {
  171. rep_hist_note_disconnect(conn->nickname, time(NULL));
  172. } else {
  173. rep_hist_note_connection_died(conn->nickname, time(NULL));
  174. }
  175. /* No special processing needed. */
  176. break;
  177. case CONN_TYPE_AP:
  178. if (conn->socks_request->has_finished == 0) {
  179. log_fn(LOG_INFO,"Cleaning up AP -- sending socks reject.");
  180. connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
  181. conn->socks_request->has_finished = 1;
  182. conn->hold_open_until_flushed = 1;
  183. }
  184. /* fall through, to do things for both ap and exit */
  185. case CONN_TYPE_EXIT:
  186. if (conn->state == EXIT_CONN_STATE_RESOLVING)
  187. connection_dns_remove(conn);
  188. if (!conn->has_sent_end && reason &&
  189. connection_edge_end(conn, reason, conn->cpath_layer) < 0)
  190. retval = -1;
  191. break;
  192. case CONN_TYPE_DNSWORKER:
  193. if (conn->state == DNSWORKER_STATE_BUSY) {
  194. dns_cancel_pending_resolve(conn->address);
  195. }
  196. break;
  197. default:
  198. log(LOG_ERR, "Unknown connection type %d", conn->type);
  199. ;
  200. }
  201. conn->marked_for_close = 1;
  202. /* in case we're going to be held-open-til-flushed, reset
  203. * the number of seconds since last successful write, so
  204. * we get our whole 15 seconds */
  205. conn->timestamp_lastwritten = time(NULL);
  206. return retval;
  207. }
  208. void connection_expire_held_open(void)
  209. {
  210. connection_t **carray, *conn;
  211. int n, i;
  212. time_t now;
  213. now = time(NULL);
  214. get_connection_array(&carray, &n);
  215. for (i = 0; i < n; ++i) {
  216. conn = carray[i];
  217. /* If we've been holding the connection open, but we haven't written
  218. * for 15 seconds...
  219. */
  220. if (conn->hold_open_until_flushed) {
  221. assert(conn->marked_for_close);
  222. if (now - conn->timestamp_lastwritten >= 15) {
  223. log_fn(LOG_WARN,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %d).",
  224. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state);
  225. conn->hold_open_until_flushed = 0;
  226. }
  227. }
  228. }
  229. }
  230. int connection_create_listener(char *bindaddress, uint16_t bindport, int type) {
  231. struct sockaddr_in bindaddr; /* where to bind */
  232. struct hostent *rent;
  233. connection_t *conn;
  234. int s; /* the socket we're going to make */
  235. int one=1;
  236. memset(&bindaddr,0,sizeof(struct sockaddr_in));
  237. bindaddr.sin_family = AF_INET;
  238. bindaddr.sin_port = htons(bindport);
  239. rent = gethostbyname(bindaddress);
  240. if (!rent) {
  241. log_fn(LOG_WARN,"Can't resolve BindAddress %s",bindaddress);
  242. return -1;
  243. }
  244. if(rent->h_length != 4)
  245. return -1; /* XXX complain */
  246. memcpy(&(bindaddr.sin_addr.s_addr),rent->h_addr,rent->h_length);
  247. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  248. if (s < 0) {
  249. log_fn(LOG_WARN,"Socket creation failed.");
  250. return -1;
  251. }
  252. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
  253. if(bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
  254. log_fn(LOG_WARN,"Could not bind to port %u: %s",bindport,strerror(errno));
  255. return -1;
  256. }
  257. if(listen(s,SOMAXCONN) < 0) {
  258. log_fn(LOG_WARN,"Could not listen on port %u: %s",bindport,strerror(errno));
  259. return -1;
  260. }
  261. set_socket_nonblocking(s);
  262. conn = connection_new(type);
  263. conn->s = s;
  264. if(connection_add(conn) < 0) { /* no space, forget it */
  265. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  266. connection_free(conn);
  267. return -1;
  268. }
  269. log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string[type], bindport);
  270. conn->state = LISTENER_STATE_READY;
  271. connection_start_reading(conn);
  272. return 0;
  273. }
  274. static int connection_handle_listener_read(connection_t *conn, int new_type) {
  275. int news; /* the new socket */
  276. connection_t *newconn;
  277. struct sockaddr_in remote; /* information about the remote peer when connecting to other routers */
  278. int remotelen = sizeof(struct sockaddr_in); /* length of the remote address */
  279. #ifdef MS_WINDOWS
  280. int e;
  281. #endif
  282. news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
  283. if (news == -1) { /* accept() error */
  284. if(ERRNO_EAGAIN(errno)) {
  285. #ifdef MS_WINDOWS
  286. e = correct_socket_errno(conn->s);
  287. if (ERRNO_EAGAIN(e))
  288. return 0;
  289. #else
  290. return 0; /* he hung up before we could accept(). that's fine. */
  291. #endif
  292. }
  293. /* else there was a real error. */
  294. log_fn(LOG_WARN,"accept() failed. Closing listener.");
  295. connection_mark_for_close(conn,0);
  296. return -1;
  297. }
  298. log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
  299. set_socket_nonblocking(news);
  300. newconn = connection_new(new_type);
  301. newconn->s = news;
  302. newconn->address = tor_strdup(inet_ntoa(remote.sin_addr)); /* remember the remote address */
  303. newconn->addr = ntohl(remote.sin_addr.s_addr);
  304. newconn->port = ntohs(remote.sin_port);
  305. if(connection_add(newconn) < 0) { /* no space, forget it */
  306. connection_free(newconn);
  307. return 0; /* no need to tear down the parent */
  308. }
  309. if(connection_init_accepted_conn(newconn) < 0) {
  310. connection_mark_for_close(newconn,0);
  311. return 0;
  312. }
  313. return 0;
  314. }
  315. static int connection_init_accepted_conn(connection_t *conn) {
  316. connection_start_reading(conn);
  317. switch(conn->type) {
  318. case CONN_TYPE_OR:
  319. return connection_tls_start_handshake(conn, 1);
  320. case CONN_TYPE_AP:
  321. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  322. break;
  323. case CONN_TYPE_DIR:
  324. conn->purpose = DIR_PURPOSE_SERVER;
  325. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  326. break;
  327. }
  328. return 0;
  329. }
  330. /* take conn, make a nonblocking socket; try to connect to
  331. * addr:port (they arrive in *host order*). If fail, return -1. Else
  332. * assign s to conn->s: if connected return 1, if eagain return 0.
  333. * address is used to make the logs useful.
  334. */
  335. int connection_connect(connection_t *conn, char *address, uint32_t addr, uint16_t port) {
  336. int s;
  337. struct sockaddr_in dest_addr;
  338. s=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  339. if (s < 0) {
  340. log_fn(LOG_WARN,"Error creating network socket.");
  341. return -1;
  342. }
  343. set_socket_nonblocking(s);
  344. memset(&dest_addr,0,sizeof(dest_addr));
  345. dest_addr.sin_family = AF_INET;
  346. dest_addr.sin_port = htons(port);
  347. dest_addr.sin_addr.s_addr = htonl(addr);
  348. log_fn(LOG_DEBUG,"Connecting to %s:%u.",address,port);
  349. if(connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
  350. if(!ERRNO_CONN_EINPROGRESS(errno)) {
  351. /* yuck. kill it. */
  352. log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",address,port,strerror(errno));
  353. close(s);
  354. return -1;
  355. } else {
  356. /* it's in progress. set state appropriately and return. */
  357. conn->s = s;
  358. log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
  359. return 0;
  360. }
  361. }
  362. /* it succeeded. we're connected. */
  363. log_fn(LOG_INFO,"Connection to %s:%u established.",address,port);
  364. conn->s = s;
  365. return 1;
  366. }
  367. static void listener_close_if_present(int type) {
  368. connection_t *conn;
  369. assert(type == CONN_TYPE_OR_LISTENER ||
  370. type == CONN_TYPE_AP_LISTENER ||
  371. type == CONN_TYPE_DIR_LISTENER);
  372. conn = connection_get_by_type(type);
  373. if (conn) {
  374. connection_close_immediate(conn);
  375. connection_mark_for_close(conn,0);
  376. }
  377. }
  378. /* start all connections that should be up but aren't */
  379. int retry_all_connections(void) {
  380. if(options.ORPort) {
  381. router_retry_connections();
  382. }
  383. if(options.ORPort) {
  384. listener_close_if_present(CONN_TYPE_OR_LISTENER);
  385. if(connection_create_listener(options.ORBindAddress,
  386. (uint16_t) options.ORPort,
  387. CONN_TYPE_OR_LISTENER) < 0)
  388. return -1;
  389. }
  390. if(options.DirPort) {
  391. listener_close_if_present(CONN_TYPE_DIR_LISTENER);
  392. if(connection_create_listener(options.DirBindAddress,
  393. (uint16_t) options.DirPort,
  394. CONN_TYPE_DIR_LISTENER) < 0)
  395. return -1;
  396. }
  397. if(options.SocksPort) {
  398. listener_close_if_present(CONN_TYPE_AP_LISTENER);
  399. if(connection_create_listener(options.SocksBindAddress,
  400. (uint16_t) options.SocksPort,
  401. CONN_TYPE_AP_LISTENER) < 0)
  402. return -1;
  403. }
  404. return 0;
  405. }
  406. extern int global_read_bucket;
  407. /* how many bytes at most can we read onto this connection? */
  408. int connection_bucket_read_limit(connection_t *conn) {
  409. int at_most;
  410. if(options.LinkPadding) {
  411. at_most = global_read_bucket;
  412. } else {
  413. /* do a rudimentary round-robin so one circuit can't hog a connection */
  414. if(connection_speaks_cells(conn)) {
  415. at_most = 32*(CELL_NETWORK_SIZE);
  416. } else {
  417. at_most = 32*(RELAY_PAYLOAD_SIZE);
  418. }
  419. if(at_most > global_read_bucket)
  420. at_most = global_read_bucket;
  421. }
  422. if(connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
  423. if(at_most > conn->receiver_bucket)
  424. at_most = conn->receiver_bucket;
  425. return at_most;
  426. }
  427. /* we just read num_read onto conn. Decrement buckets appropriately. */
  428. void connection_bucket_decrement(connection_t *conn, int num_read) {
  429. global_read_bucket -= num_read; assert(global_read_bucket >= 0);
  430. if(connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  431. conn->receiver_bucket -= num_read; assert(conn->receiver_bucket >= 0);
  432. }
  433. if(global_read_bucket == 0) {
  434. log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
  435. conn->wants_to_read = 1;
  436. connection_stop_reading(conn);
  437. return;
  438. }
  439. if(connection_speaks_cells(conn) &&
  440. conn->state == OR_CONN_STATE_OPEN &&
  441. conn->receiver_bucket == 0) {
  442. log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
  443. conn->wants_to_read = 1;
  444. connection_stop_reading(conn);
  445. }
  446. }
  447. /* keep a timeval to know when time has passed enough to refill buckets */
  448. static struct timeval current_time;
  449. void connection_bucket_init(void) {
  450. tor_gettimeofday(&current_time);
  451. global_read_bucket = options.BandwidthBurst; /* start it at max traffic */
  452. }
  453. /* some time has passed; increment buckets appropriately. */
  454. void connection_bucket_refill(struct timeval *now) {
  455. int i, n;
  456. connection_t *conn;
  457. connection_t **carray;
  458. if(now->tv_sec <= current_time.tv_sec)
  459. return; /* wait until the second has rolled over */
  460. current_time.tv_sec = now->tv_sec; /* update current_time */
  461. /* (ignore usecs for now) */
  462. /* refill the global bucket */
  463. if(global_read_bucket < options.BandwidthBurst) {
  464. global_read_bucket += options.BandwidthRate;
  465. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  466. }
  467. /* refill the per-connection buckets */
  468. get_connection_array(&carray,&n);
  469. for(i=0;i<n;i++) {
  470. conn = carray[i];
  471. if(connection_receiver_bucket_should_increase(conn)) {
  472. conn->receiver_bucket += conn->bandwidth;
  473. //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  474. }
  475. if(conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  476. && global_read_bucket > 0 /* and we're allowed to read */
  477. && (!connection_speaks_cells(conn) ||
  478. conn->state != OR_CONN_STATE_OPEN ||
  479. conn->receiver_bucket > 0)) {
  480. /* and either a non-cell conn or a cell conn with non-empty bucket */
  481. log_fn(LOG_DEBUG,"waking up conn (fd %d)",conn->s);
  482. conn->wants_to_read = 0;
  483. connection_start_reading(conn);
  484. if(conn->wants_to_write == 1) {
  485. conn->wants_to_write = 0;
  486. connection_start_writing(conn);
  487. }
  488. }
  489. }
  490. }
  491. static int connection_receiver_bucket_should_increase(connection_t *conn) {
  492. assert(conn);
  493. if(!connection_speaks_cells(conn))
  494. return 0; /* edge connections don't use receiver_buckets */
  495. if(conn->state != OR_CONN_STATE_OPEN)
  496. return 0; /* only open connections play the rate limiting game */
  497. assert(conn->bandwidth > 0);
  498. if(conn->receiver_bucket > 9*conn->bandwidth)
  499. return 0;
  500. return 1;
  501. }
  502. int connection_handle_read(connection_t *conn) {
  503. conn->timestamp_lastread = time(NULL);
  504. switch(conn->type) {
  505. case CONN_TYPE_OR_LISTENER:
  506. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  507. case CONN_TYPE_AP_LISTENER:
  508. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  509. case CONN_TYPE_DIR_LISTENER:
  510. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  511. }
  512. if(connection_read_to_buf(conn) < 0) {
  513. if(conn->type == CONN_TYPE_DIR &&
  514. conn->state == DIR_CONN_STATE_CONNECTING) {
  515. /* it's a directory server and connecting failed: forget about this router */
  516. /* XXX I suspect pollerr may make Windows not get to this point. :( */
  517. router_mark_as_down(conn->nickname);
  518. }
  519. /* There's a read error; kill the connection.*/
  520. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  521. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  522. return -1;
  523. }
  524. if(connection_process_inbuf(conn) < 0) {
  525. // log_fn(LOG_DEBUG,"connection_process_inbuf returned -1.");
  526. return -1;
  527. }
  528. return 0;
  529. }
  530. /* return -1 if we want to break conn, else return 0 */
  531. int connection_read_to_buf(connection_t *conn) {
  532. int result;
  533. int at_most;
  534. /* how many bytes are we allowed to read? */
  535. at_most = connection_bucket_read_limit(conn);
  536. if(connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING) {
  537. if(conn->state == OR_CONN_STATE_HANDSHAKING) {
  538. /* continue handshaking even if global token bucket is empty */
  539. return connection_tls_continue_handshake(conn);
  540. }
  541. /* else open, or closing */
  542. result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
  543. switch(result) {
  544. case TOR_TLS_ERROR:
  545. case TOR_TLS_CLOSE:
  546. log_fn(LOG_INFO,"tls error. breaking.");
  547. return -1; /* XXX deal with close better */
  548. case TOR_TLS_WANTWRITE:
  549. connection_start_writing(conn);
  550. return 0;
  551. case TOR_TLS_WANTREAD: /* we're already reading */
  552. case TOR_TLS_DONE: /* no data read, so nothing to process */
  553. result = 0;
  554. break; /* so we call bucket_decrement below */
  555. }
  556. } else {
  557. result = read_to_buf(conn->s, at_most, conn->inbuf,
  558. &conn->inbuf_reached_eof);
  559. // log(LOG_DEBUG,"connection_read_to_buf(): read_to_buf returned %d.",read_result);
  560. if(result < 0)
  561. return -1;
  562. }
  563. connection_bucket_decrement(conn, result);
  564. return 0;
  565. }
  566. int connection_fetch_from_buf(char *string, int len, connection_t *conn) {
  567. return fetch_from_buf(string, len, conn->inbuf);
  568. }
  569. int connection_find_on_inbuf(char *string, int len, connection_t *conn) {
  570. return find_on_inbuf(string, len, conn->inbuf);
  571. }
  572. int connection_wants_to_flush(connection_t *conn) {
  573. return conn->outbuf_flushlen;
  574. }
  575. int connection_outbuf_too_full(connection_t *conn) {
  576. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  577. }
  578. /* return -1 if you want to break the conn, else return 0 */
  579. int connection_handle_write(connection_t *conn) {
  580. assert(!connection_is_listener(conn));
  581. conn->timestamp_lastwritten = time(NULL);
  582. if (connection_speaks_cells(conn) &&
  583. conn->state != OR_CONN_STATE_CONNECTING) {
  584. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  585. connection_stop_writing(conn);
  586. if(connection_tls_continue_handshake(conn) < 0) {
  587. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  588. connection_mark_for_close(conn, 0);
  589. return -1;
  590. }
  591. return 0;
  592. }
  593. /* else open, or closing */
  594. switch(flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen)) {
  595. case TOR_TLS_ERROR:
  596. case TOR_TLS_CLOSE:
  597. log_fn(LOG_INFO,"tls error. breaking.");
  598. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  599. connection_mark_for_close(conn, 0);
  600. return -1; /* XXX deal with close better */
  601. case TOR_TLS_WANTWRITE:
  602. log_fn(LOG_DEBUG,"wanted write.");
  603. /* we're already writing */
  604. return 0;
  605. case TOR_TLS_WANTREAD:
  606. /* Make sure to avoid a loop if the receive buckets are empty. */
  607. log_fn(LOG_DEBUG,"wanted read.");
  608. if(!connection_is_reading(conn)) {
  609. connection_stop_writing(conn);
  610. conn->wants_to_write = 1;
  611. /* we'll start reading again when the next second arrives,
  612. * and then also start writing again.
  613. */
  614. }
  615. /* else no problem, we're already reading */
  616. return 0;
  617. /* case TOR_TLS_DONE:
  618. * for TOR_TLS_DONE, fall through to check if the flushlen
  619. * is empty, so we can stop writing.
  620. */
  621. }
  622. } else {
  623. if (flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen) < 0) {
  624. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  625. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  626. return -1;
  627. }
  628. /* conns in CONNECTING state will fall through... */
  629. }
  630. if(!connection_wants_to_flush(conn)) /* it's done flushing */
  631. if(connection_finished_flushing(conn) < 0) /* ...and get handled here. */
  632. return -1;
  633. return 0;
  634. }
  635. void connection_write_to_buf(const char *string, int len, connection_t *conn) {
  636. if(!len || conn->marked_for_close)
  637. return;
  638. if(write_to_buf(string, len, conn->outbuf) < 0) {
  639. log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
  640. connection_mark_for_close(conn,0);
  641. return;
  642. }
  643. connection_start_writing(conn);
  644. #define MIN_TLS_FLUSHLEN 15872
  645. /* openssl tls record size is 16383, this is close. The goal here is to
  646. * push data out as soon as we know there's enough for a tls record, so
  647. * during periods of high load we won't read the entire megabyte from
  648. * input before pushing any data out. */
  649. if(connection_speaks_cells(conn) &&
  650. conn->outbuf_flushlen < MIN_TLS_FLUSHLEN &&
  651. conn->outbuf_flushlen+len >= MIN_TLS_FLUSHLEN) {
  652. len -= (MIN_TLS_FLUSHLEN - conn->outbuf_flushlen);
  653. conn->outbuf_flushlen = MIN_TLS_FLUSHLEN;
  654. if(connection_handle_write(conn) < 0) {
  655. log_fn(LOG_WARN,"flushing failed.");
  656. connection_mark_for_close(conn,0);
  657. }
  658. }
  659. if(len > 0) { /* if there's any left over */
  660. conn->outbuf_flushlen += len;
  661. connection_start_writing(conn);
  662. /* because connection_handle_write() above might have stopped writing */
  663. }
  664. }
  665. connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
  666. int i, n;
  667. connection_t *conn;
  668. connection_t **carray;
  669. get_connection_array(&carray,&n);
  670. for(i=0;i<n;i++) {
  671. conn = carray[i];
  672. if(conn->addr == addr && conn->port == port && !conn->marked_for_close)
  673. return conn;
  674. }
  675. return NULL;
  676. }
  677. connection_t *connection_twin_get_by_addr_port(uint32_t addr, uint16_t port) {
  678. /* Find a connection to the router described by addr and port,
  679. * or alternately any router which knows its key.
  680. * This connection *must* be in 'open' state.
  681. * If not, return NULL.
  682. */
  683. int i, n;
  684. connection_t *conn;
  685. routerinfo_t *router;
  686. connection_t **carray;
  687. /* first check if it's there exactly */
  688. conn = connection_exact_get_by_addr_port(addr,port);
  689. if(conn && connection_state_is_open(conn)) {
  690. log(LOG_DEBUG,"connection_twin_get_by_addr_port(): Found exact match.");
  691. return conn;
  692. }
  693. /* now check if any of the other open connections are a twin for this one */
  694. router = router_get_by_addr_port(addr,port);
  695. if(!router)
  696. return NULL;
  697. get_connection_array(&carray,&n);
  698. for(i=0;i<n;i++) {
  699. conn = carray[i];
  700. assert(conn);
  701. if(connection_state_is_open(conn) &&
  702. !crypto_pk_cmp_keys(conn->onion_pkey, router->onion_pkey)) {
  703. log(LOG_DEBUG,"connection_twin_get_by_addr_port(): Found twin (%s).",conn->address);
  704. return conn;
  705. }
  706. }
  707. return NULL;
  708. }
  709. connection_t *connection_get_by_type(int type) {
  710. int i, n;
  711. connection_t *conn;
  712. connection_t **carray;
  713. get_connection_array(&carray,&n);
  714. for(i=0;i<n;i++) {
  715. conn = carray[i];
  716. if(conn->type == type && !conn->marked_for_close)
  717. return conn;
  718. }
  719. return NULL;
  720. }
  721. connection_t *connection_get_by_type_state(int type, int state) {
  722. int i, n;
  723. connection_t *conn;
  724. connection_t **carray;
  725. get_connection_array(&carray,&n);
  726. for(i=0;i<n;i++) {
  727. conn = carray[i];
  728. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  729. return conn;
  730. }
  731. return NULL;
  732. }
  733. connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
  734. int i, n;
  735. connection_t *conn, *best=NULL;
  736. connection_t **carray;
  737. get_connection_array(&carray,&n);
  738. for(i=0;i<n;i++) {
  739. conn = carray[i];
  740. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  741. if(!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  742. best = conn;
  743. }
  744. return best;
  745. }
  746. connection_t *connection_get_by_type_rendquery(int type, char *rendquery) {
  747. int i, n;
  748. connection_t *conn;
  749. connection_t **carray;
  750. get_connection_array(&carray,&n);
  751. for(i=0;i<n;i++) {
  752. conn = carray[i];
  753. if(conn->type == type &&
  754. !conn->marked_for_close &&
  755. !rend_cmp_service_ids(rendquery, conn->rend_query))
  756. return conn;
  757. }
  758. return NULL;
  759. }
  760. int connection_is_listener(connection_t *conn) {
  761. if(conn->type == CONN_TYPE_OR_LISTENER ||
  762. conn->type == CONN_TYPE_AP_LISTENER ||
  763. conn->type == CONN_TYPE_DIR_LISTENER)
  764. return 1;
  765. return 0;
  766. }
  767. int connection_state_is_open(connection_t *conn) {
  768. assert(conn);
  769. if(conn->marked_for_close)
  770. return 0;
  771. if((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  772. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  773. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN))
  774. return 1;
  775. return 0;
  776. }
  777. int connection_send_destroy(uint16_t circ_id, connection_t *conn) {
  778. cell_t cell;
  779. assert(conn);
  780. assert(connection_speaks_cells(conn));
  781. memset(&cell, 0, sizeof(cell_t));
  782. cell.circ_id = circ_id;
  783. cell.command = CELL_DESTROY;
  784. log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
  785. connection_or_write_cell_to_buf(&cell, conn);
  786. return 0;
  787. }
  788. int connection_process_inbuf(connection_t *conn) {
  789. assert(conn);
  790. switch(conn->type) {
  791. case CONN_TYPE_OR:
  792. return connection_or_process_inbuf(conn);
  793. case CONN_TYPE_EXIT:
  794. case CONN_TYPE_AP:
  795. return connection_edge_process_inbuf(conn);
  796. case CONN_TYPE_DIR:
  797. return connection_dir_process_inbuf(conn);
  798. case CONN_TYPE_DNSWORKER:
  799. return connection_dns_process_inbuf(conn);
  800. case CONN_TYPE_CPUWORKER:
  801. return connection_cpu_process_inbuf(conn);
  802. default:
  803. log_fn(LOG_WARN,"got unexpected conn->type %d.", conn->type);
  804. return -1;
  805. }
  806. }
  807. int connection_finished_flushing(connection_t *conn) {
  808. assert(conn);
  809. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  810. switch(conn->type) {
  811. case CONN_TYPE_OR:
  812. return connection_or_finished_flushing(conn);
  813. case CONN_TYPE_AP:
  814. case CONN_TYPE_EXIT:
  815. return connection_edge_finished_flushing(conn);
  816. case CONN_TYPE_DIR:
  817. return connection_dir_finished_flushing(conn);
  818. case CONN_TYPE_DNSWORKER:
  819. return connection_dns_finished_flushing(conn);
  820. case CONN_TYPE_CPUWORKER:
  821. return connection_cpu_finished_flushing(conn);
  822. default:
  823. log_fn(LOG_WARN,"got unexpected conn->type %d.", conn->type);
  824. return -1;
  825. }
  826. }
  827. void assert_connection_ok(connection_t *conn, time_t now)
  828. {
  829. assert(conn);
  830. assert(conn->magic == CONNECTION_MAGIC);
  831. assert(conn->type >= _CONN_TYPE_MIN);
  832. assert(conn->type <= _CONN_TYPE_MAX);
  833. if(conn->outbuf_flushlen > 0) {
  834. assert(connection_is_writing(conn) || conn->wants_to_write);
  835. }
  836. if(conn->hold_open_until_flushed)
  837. assert(conn->marked_for_close);
  838. /* XXX check: wants_to_read, wants_to_write, s, poll_index,
  839. * marked_for_close. */
  840. /* buffers */
  841. if (!connection_is_listener(conn)) {
  842. assert_buf_ok(conn->inbuf);
  843. assert_buf_ok(conn->outbuf);
  844. }
  845. #if 0 /* computers often go back in time; no way to know */
  846. assert(!now || conn->timestamp_lastread <= now);
  847. assert(!now || conn->timestamp_lastwritten <= now);
  848. assert(conn->timestamp_created <= conn->timestamp_lastread);
  849. assert(conn->timestamp_created <= conn->timestamp_lastwritten);
  850. #endif
  851. /* XXX Fix this; no longer so.*/
  852. #if 0
  853. if(conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
  854. assert(!conn->pkey);
  855. /* pkey is set if we're a dir client, or if we're an OR in state OPEN
  856. * connected to another OR.
  857. */
  858. #endif
  859. if (conn->type != CONN_TYPE_OR) {
  860. assert(!conn->tls);
  861. } else {
  862. if(conn->state == OR_CONN_STATE_OPEN) {
  863. /* assert(conn->bandwidth > 0); */
  864. /* the above isn't necessarily true: if we just did a TLS
  865. * handshake but we didn't recognize the other peer, or it
  866. * gave a bad cert/etc, then we won't have assigned bandwidth,
  867. * yet it will be open. -RD
  868. */
  869. assert(conn->receiver_bucket >= 0);
  870. }
  871. assert(conn->addr && conn->port);
  872. assert(conn->address);
  873. if (conn->state != OR_CONN_STATE_CONNECTING)
  874. assert(conn->tls);
  875. }
  876. if (conn->type != CONN_TYPE_EXIT && conn->type != CONN_TYPE_AP) {
  877. assert(!conn->stream_id);
  878. assert(!conn->next_stream);
  879. assert(!conn->cpath_layer);
  880. assert(!conn->package_window);
  881. assert(!conn->deliver_window);
  882. assert(!conn->done_sending);
  883. assert(!conn->done_receiving);
  884. } else {
  885. /* XXX unchecked: package window, deliver window. */
  886. }
  887. if (conn->type == CONN_TYPE_AP) {
  888. assert(conn->socks_request);
  889. if (conn->state == AP_CONN_STATE_OPEN) {
  890. assert(conn->socks_request->has_finished);
  891. assert(conn->cpath_layer);
  892. assert_cpath_layer_ok(conn->cpath_layer);
  893. }
  894. } else {
  895. assert(!conn->socks_request);
  896. }
  897. if(conn->type != CONN_TYPE_DIR) {
  898. assert(!conn->purpose); /* only used for dir types currently */
  899. }
  900. switch(conn->type)
  901. {
  902. case CONN_TYPE_OR_LISTENER:
  903. case CONN_TYPE_AP_LISTENER:
  904. case CONN_TYPE_DIR_LISTENER:
  905. assert(conn->state == LISTENER_STATE_READY);
  906. break;
  907. case CONN_TYPE_OR:
  908. assert(conn->state >= _OR_CONN_STATE_MIN &&
  909. conn->state <= _OR_CONN_STATE_MAX);
  910. break;
  911. case CONN_TYPE_EXIT:
  912. assert(conn->state >= _EXIT_CONN_STATE_MIN &&
  913. conn->state <= _EXIT_CONN_STATE_MAX);
  914. break;
  915. case CONN_TYPE_AP:
  916. assert(conn->state >= _AP_CONN_STATE_MIN &&
  917. conn->state <= _AP_CONN_STATE_MAX);
  918. assert(conn->socks_request);
  919. break;
  920. case CONN_TYPE_DIR:
  921. assert(conn->state >= _DIR_CONN_STATE_MIN &&
  922. conn->state <= _DIR_CONN_STATE_MAX);
  923. assert(conn->purpose >= _DIR_PURPOSE_MIN &&
  924. conn->purpose <= _DIR_PURPOSE_MAX);
  925. break;
  926. case CONN_TYPE_DNSWORKER:
  927. assert(conn->state == DNSWORKER_STATE_IDLE ||
  928. conn->state == DNSWORKER_STATE_BUSY);
  929. break;
  930. case CONN_TYPE_CPUWORKER:
  931. assert(conn->state >= _CPUWORKER_STATE_MIN &&
  932. conn->state <= _CPUWORKER_STATE_MAX);
  933. break;
  934. default:
  935. assert(0);
  936. }
  937. }
  938. /*
  939. Local Variables:
  940. mode:c
  941. indent-tabs-mode:nil
  942. c-basic-offset:2
  943. End:
  944. */