connection.c 33 KB

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