connection.c 32 KB

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