connection.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. /* Copyright 2001,2002 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. extern int global_read_bucket;
  8. char *conn_type_to_string[] = {
  9. "", /* 0 */
  10. "OP listener", /* 1 */
  11. "OP", /* 2 */
  12. "OR listener", /* 3 */
  13. "OR", /* 4 */
  14. "Exit", /* 5 */
  15. "App listener",/* 6 */
  16. "App", /* 7 */
  17. "Dir listener",/* 8 */
  18. "Dir", /* 9 */
  19. "DNS worker", /* 10 */
  20. "CPU worker", /* 11 */
  21. };
  22. char *conn_state_to_string[][15] = {
  23. { NULL }, /* no type associated with 0 */
  24. { "ready" }, /* op listener, 0 */
  25. { "awaiting keys", /* op, 0 */
  26. "open", /* 1 */
  27. "close", /* 2 */
  28. "close_wait" }, /* 3 */
  29. { "ready" }, /* or listener, 0 */
  30. { "connecting (as OP)", /* or, 0 */
  31. "sending keys (as OP)", /* 1 */
  32. "connecting (as client)", /* 2 */
  33. "sending auth (as client)", /* 3 */
  34. "waiting for auth (as client)", /* 4 */
  35. "sending nonce (as client)", /* 5 */
  36. "waiting for auth (as server)", /* 6 */
  37. "sending auth (as server)", /* 7 */
  38. "waiting for nonce (as server)",/* 8 */
  39. "open" }, /* 9 */
  40. { "waiting for dest info", /* exit, 0 */
  41. "connecting", /* 1 */
  42. "open" }, /* 2 */
  43. { "ready" }, /* app listener, 0 */
  44. { "", /* 0 */
  45. "", /* 1 */
  46. "", /* 2 */
  47. "awaiting dest info", /* app, 3 */
  48. "waiting for OR connection", /* 4 */
  49. "open" }, /* 5 */
  50. { "ready" }, /* dir listener, 0 */
  51. { "connecting", /* 0 */
  52. "sending command", /* 1 */
  53. "reading", /* 2 */
  54. "awaiting command", /* 3 */
  55. "writing" }, /* 4 */
  56. { "idle", /* dns worker, 0 */
  57. "busy" }, /* 1 */
  58. { "idle", /* cpu worker, 0 */
  59. "busy with onion", /* 1 */
  60. "busy with handshake" }, /* 2 */
  61. };
  62. /********* END VARIABLES ************/
  63. static int connection_init_accepted_conn(connection_t *conn);
  64. static int connection_tls_continue_handshake(connection_t *conn);
  65. static int connection_tls_finish_handshake(connection_t *conn);
  66. /**************************************************************/
  67. connection_t *connection_new(int type) {
  68. connection_t *conn;
  69. struct timeval now;
  70. my_gettimeofday(&now);
  71. conn = (connection_t *)tor_malloc(sizeof(connection_t));
  72. memset(conn,0,sizeof(connection_t)); /* zero it out to start */
  73. conn->type = type;
  74. if(buf_new(&conn->inbuf, &conn->inbuflen, &conn->inbuf_datalen) < 0 ||
  75. buf_new(&conn->outbuf, &conn->outbuflen, &conn->outbuf_datalen) < 0)
  76. return NULL;
  77. conn->receiver_bucket = 10240; /* should be enough to do the handshake */
  78. conn->bandwidth = conn->receiver_bucket / 10; /* give it a default */
  79. conn->timestamp_created = now.tv_sec;
  80. conn->timestamp_lastread = now.tv_sec;
  81. conn->timestamp_lastwritten = now.tv_sec;
  82. #ifndef USE_TLS
  83. if (connection_speaks_cells(conn)) {
  84. conn->f_crypto = crypto_new_cipher_env(CONNECTION_CIPHER);
  85. if (!conn->f_crypto) {
  86. free((void *)conn);
  87. return NULL;
  88. }
  89. conn->b_crypto = crypto_new_cipher_env(CONNECTION_CIPHER);
  90. if (!conn->b_crypto) {
  91. crypto_free_cipher_env(conn->f_crypto);
  92. free((void *)conn);
  93. return NULL;
  94. }
  95. }
  96. #endif
  97. return conn;
  98. }
  99. void connection_free(connection_t *conn) {
  100. assert(conn);
  101. buf_free(conn->inbuf);
  102. buf_free(conn->outbuf);
  103. if(conn->address)
  104. free(conn->address);
  105. if(conn->dest_addr)
  106. free(conn->dest_addr);
  107. if(connection_speaks_cells(conn)) {
  108. directory_set_dirty();
  109. #ifdef USE_TLS
  110. if (conn->tls)
  111. tor_tls_free(conn->tls);
  112. #else
  113. if (conn->f_crypto)
  114. crypto_free_cipher_env(conn->f_crypto);
  115. if (conn->b_crypto)
  116. crypto_free_cipher_env(conn->b_crypto);
  117. #endif
  118. }
  119. if (conn->pkey)
  120. crypto_free_pk_env(conn->pkey);
  121. if(conn->s > 0) {
  122. log_fn(LOG_INFO,"closing fd %d.",conn->s);
  123. close(conn->s);
  124. }
  125. free(conn);
  126. }
  127. int connection_create_listener(struct sockaddr_in *bindaddr, int type) {
  128. connection_t *conn;
  129. int s;
  130. int one=1;
  131. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  132. if (s < 0)
  133. {
  134. log_fn(LOG_ERR,"Socket creation failed.");
  135. return -1;
  136. }
  137. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&one, sizeof(one));
  138. if(bind(s,(struct sockaddr *)bindaddr,sizeof(*bindaddr)) < 0) {
  139. perror("bind ");
  140. log(LOG_ERR,"Could not bind to port %u.",ntohs(bindaddr->sin_port));
  141. return -1;
  142. }
  143. if(listen(s,SOMAXCONN) < 0) {
  144. log(LOG_ERR,"Could not listen on port %u.",ntohs(bindaddr->sin_port));
  145. return -1;
  146. }
  147. set_socket_nonblocking(s);
  148. conn = connection_new(type);
  149. if(!conn) {
  150. log_fn(LOG_DEBUG,"connection_new failed. Giving up.");
  151. return -1;
  152. }
  153. conn->s = s;
  154. if(connection_add(conn) < 0) { /* no space, forget it */
  155. log_fn(LOG_DEBUG,"connection_add failed. Giving up.");
  156. connection_free(conn);
  157. return -1;
  158. }
  159. log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string[type], ntohs(bindaddr->sin_port));
  160. conn->state = LISTENER_STATE_READY;
  161. connection_start_reading(conn);
  162. return 0;
  163. }
  164. int connection_handle_listener_read(connection_t *conn, int new_type) {
  165. int news; /* the new socket */
  166. connection_t *newconn;
  167. struct sockaddr_in remote; /* information about the remote peer when connecting to other routers */
  168. int remotelen = sizeof(struct sockaddr_in); /* length of the remote address */
  169. #ifdef MS_WINDOWS
  170. int e;
  171. #endif
  172. news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
  173. if (news == -1) { /* accept() error */
  174. if(ERRNO_EAGAIN(errno)) {
  175. #ifdef MS_WINDOWS
  176. e = correct_socket_errno(conn->s);
  177. if (ERRNO_EAGAIN(e))
  178. return 0;
  179. #else
  180. return 0; /* he hung up before we could accept(). that's fine. */
  181. #endif
  182. }
  183. /* else there was a real error. */
  184. log_fn(LOG_ERR,"accept() failed. Closing.");
  185. return -1;
  186. }
  187. log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
  188. set_socket_nonblocking(news);
  189. newconn = connection_new(new_type);
  190. newconn->s = news;
  191. if(!connection_speaks_cells(newconn)) {
  192. newconn->receiver_bucket = -1;
  193. newconn->bandwidth = -1;
  194. }
  195. newconn->address = strdup(inet_ntoa(remote.sin_addr)); /* remember the remote address */
  196. newconn->addr = ntohl(remote.sin_addr.s_addr);
  197. newconn->port = ntohs(remote.sin_port);
  198. if(connection_add(newconn) < 0) { /* no space, forget it */
  199. connection_free(newconn);
  200. return 0; /* no need to tear down the parent */
  201. }
  202. if(connection_init_accepted_conn(newconn) < 0) {
  203. connection_free(newconn);
  204. return 0;
  205. }
  206. return 0;
  207. }
  208. static int connection_init_accepted_conn(connection_t *conn) {
  209. connection_start_reading(conn);
  210. switch(conn->type) {
  211. case CONN_TYPE_OR:
  212. #ifdef USE_TLS
  213. if(connection_tls_start_handshake(conn) < 0)
  214. return -1;
  215. #else
  216. conn->state = OR_CONN_STATE_SERVER_AUTH_WAIT;
  217. #endif
  218. break;
  219. case CONN_TYPE_AP:
  220. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  221. break;
  222. case CONN_TYPE_DIR:
  223. conn->state = DIR_CONN_STATE_COMMAND_WAIT;
  224. break;
  225. }
  226. return 0;
  227. }
  228. #ifdef USE_TLS
  229. int connection_tls_start_handshake(connection_t *conn) {
  230. conn->state = OR_CONN_STATE_HANDSHAKING;
  231. conn->tls = tor_tls_new(conn->s, options.OnionRouter);
  232. if(!conn->tls) {
  233. log_fn(LOG_ERR,"tor_tls_new failed. Closing.");
  234. return -1;
  235. }
  236. connection_start_reading(conn);
  237. if(connection_tls_continue_handshake(conn) < 0)
  238. return -1;
  239. return 0;
  240. }
  241. static int connection_tls_continue_handshake(connection_t *conn) {
  242. switch(tor_tls_handshake(conn->tls)) {
  243. case TOR_TLS_ERROR:
  244. case TOR_TLS_CLOSE:
  245. log_fn(LOG_DEBUG,"tls error. breaking.");
  246. return -1;
  247. case TOR_TLS_DONE:
  248. return connection_tls_finish_handshake(conn);
  249. case TOR_TLS_WANTWRITE:
  250. connection_start_writing(conn);
  251. return 0;
  252. case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
  253. return 0;
  254. }
  255. return 0;
  256. }
  257. static int connection_tls_finish_handshake(connection_t *conn) {
  258. crypto_pk_env_t *pk;
  259. routerinfo_t *router;
  260. conn->state = OR_CONN_STATE_OPEN;
  261. directory_set_dirty();
  262. connection_watch_events(conn, POLLIN);
  263. if(options.OnionRouter) { /* I'm an OR */
  264. if(tor_tls_peer_has_cert(conn->tls)) { /* it's another OR */
  265. pk = tor_tls_verify(conn->tls);
  266. if(!pk) {
  267. log_fn(LOG_INFO,"Other side has a cert but it's bad. Closing.");
  268. return -1;
  269. }
  270. router = look up which router I just connected to. /* XXX */
  271. conn->bandwidth = router->bandwidth;
  272. conn->addr = router->addr, conn->port = router->or_port;
  273. conn->pkey = crypto_pk_dup_key(router->pkey);
  274. if(conn->address)
  275. free(conn->address);
  276. conn->address = strdup(router->address);
  277. } else { /* it's an OP */
  278. conn->bandwidth = DEFAULT_BANDWIDTH_OP;
  279. }
  280. } else { /* I'm a client */
  281. conn->bandwidth = DEFAULT_BANDWIDTH_OP;
  282. circuit_n_conn_open(conn); /* send the pending create */
  283. }
  284. log_fn(LOG_DEBUG,"tls handshake done, now open.");
  285. return 0;
  286. }
  287. #endif
  288. /* start all connections that should be up but aren't */
  289. int retry_all_connections(uint16_t or_listenport, uint16_t ap_listenport, uint16_t dir_listenport) {
  290. struct sockaddr_in bindaddr; /* where to bind */
  291. if(or_listenport) {
  292. router_retry_connections();
  293. }
  294. memset(&bindaddr,0,sizeof(struct sockaddr_in));
  295. bindaddr.sin_family = AF_INET;
  296. bindaddr.sin_addr.s_addr = htonl(INADDR_ANY); /* anyone can connect */
  297. if(or_listenport) {
  298. bindaddr.sin_port = htons(or_listenport);
  299. if(!connection_get_by_type(CONN_TYPE_OR_LISTENER)) {
  300. connection_create_listener(&bindaddr, CONN_TYPE_OR_LISTENER);
  301. }
  302. }
  303. if(dir_listenport) {
  304. bindaddr.sin_port = htons(dir_listenport);
  305. if(!connection_get_by_type(CONN_TYPE_DIR_LISTENER)) {
  306. connection_create_listener(&bindaddr, CONN_TYPE_DIR_LISTENER);
  307. }
  308. }
  309. if(ap_listenport) {
  310. bindaddr.sin_port = htons(ap_listenport);
  311. bindaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); /* the AP listens only on localhost! */
  312. if(!connection_get_by_type(CONN_TYPE_AP_LISTENER)) {
  313. connection_create_listener(&bindaddr, CONN_TYPE_AP_LISTENER);
  314. }
  315. }
  316. return 0;
  317. }
  318. int connection_handle_read(connection_t *conn) {
  319. struct timeval now;
  320. my_gettimeofday(&now);
  321. conn->timestamp_lastread = now.tv_sec;
  322. switch(conn->type) {
  323. case CONN_TYPE_OR_LISTENER:
  324. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  325. case CONN_TYPE_AP_LISTENER:
  326. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  327. case CONN_TYPE_DIR_LISTENER:
  328. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  329. }
  330. if(connection_read_to_buf(conn) < 0) {
  331. if(conn->type == CONN_TYPE_DIR && conn->state == DIR_CONN_STATE_CONNECTING) {
  332. /* it's a directory server and connecting failed: forget about this router */
  333. /* XXX I suspect pollerr may make Windows not get to this point. :( */
  334. router_forget_router(conn->addr,conn->port);
  335. /* FIXME i don't think router_forget_router works. */
  336. }
  337. return -1;
  338. }
  339. if(connection_process_inbuf(conn) < 0) {
  340. //log_fn(LOG_DEBUG,"connection_process_inbuf returned %d.",retval);
  341. return -1;
  342. }
  343. if(!connection_state_is_open(conn) && conn->receiver_bucket == 0) {
  344. log_fn(LOG_DEBUG,"receiver bucket reached 0 before handshake finished. Closing.");
  345. return -1;
  346. }
  347. return 0;
  348. }
  349. /* return -1 if we want to break conn, else return 0 */
  350. int connection_read_to_buf(connection_t *conn) {
  351. int result;
  352. int at_most;
  353. assert((connection_speaks_cells(conn) && conn->receiver_bucket >= 0) ||
  354. (!connection_speaks_cells(conn) && conn->receiver_bucket < 0));
  355. if(options.LinkPadding) {
  356. at_most = global_read_bucket;
  357. } else {
  358. /* do a rudimentary round-robin so one connection can't hog a thickpipe */
  359. if(connection_speaks_cells(conn)) {
  360. at_most = 10*(CELL_NETWORK_SIZE);
  361. } else {
  362. at_most = 10*(CELL_PAYLOAD_SIZE - RELAY_HEADER_SIZE);
  363. }
  364. if(at_most > global_read_bucket)
  365. at_most = global_read_bucket;
  366. }
  367. if(conn->receiver_bucket >= 0 && at_most > conn->receiver_bucket)
  368. at_most = conn->receiver_bucket;
  369. #ifdef USE_TLS
  370. if(connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING) {
  371. if(conn->state == OR_CONN_STATE_HANDSHAKING)
  372. return connection_tls_continue_handshake(conn);
  373. /* else open, or closing */
  374. result = read_to_buf_tls(conn->tls, at_most, &conn->inbuf,
  375. &conn->inbuflen, &conn->inbuf_datalen);
  376. switch(result) {
  377. case TOR_TLS_ERROR:
  378. case TOR_TLS_CLOSE:
  379. log_fn(LOG_DEBUG,"tls error. breaking.");
  380. return -1; /* XXX deal with close better */
  381. case TOR_TLS_WANTWRITE:
  382. connection_start_writing(conn);
  383. return 0;
  384. case TOR_TLS_WANTREAD: /* we're already reading */
  385. case TOR_TLS_DONE: /* no data read, so nothing to process */
  386. return 0;
  387. }
  388. } else
  389. #endif
  390. {
  391. result = read_to_buf(conn->s, at_most, &conn->inbuf, &conn->inbuflen,
  392. &conn->inbuf_datalen, &conn->inbuf_reached_eof);
  393. // log(LOG_DEBUG,"connection_read_to_buf(): read_to_buf returned %d.",read_result);
  394. if(result < 0)
  395. return -1;
  396. }
  397. global_read_bucket -= result; assert(global_read_bucket >= 0);
  398. if(connection_speaks_cells(conn))
  399. conn->receiver_bucket -= result;
  400. if(conn->receiver_bucket == 0 || global_read_bucket == 0) {
  401. log_fn(LOG_DEBUG,"buckets (%d, %d) exhausted. Pausing.", global_read_bucket, conn->receiver_bucket);
  402. conn->wants_to_read = 1;
  403. connection_stop_reading(conn);
  404. }
  405. return 0;
  406. }
  407. int connection_fetch_from_buf(char *string, int len, connection_t *conn) {
  408. return fetch_from_buf(string, len, &conn->inbuf, &conn->inbuflen, &conn->inbuf_datalen);
  409. }
  410. int connection_find_on_inbuf(char *string, int len, connection_t *conn) {
  411. return find_on_inbuf(string, len, conn->inbuf, conn->inbuf_datalen);
  412. }
  413. int connection_wants_to_flush(connection_t *conn) {
  414. return conn->outbuf_flushlen;
  415. }
  416. int connection_outbuf_too_full(connection_t *conn) {
  417. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  418. }
  419. int connection_flush_buf(connection_t *conn) {
  420. return flush_buf(conn->s, &conn->outbuf, &conn->outbuflen,
  421. &conn->outbuf_flushlen, &conn->outbuf_datalen);
  422. }
  423. /* return -1 if you want to break the conn, else return 0 */
  424. int connection_handle_write(connection_t *conn) {
  425. struct timeval now;
  426. if(connection_is_listener(conn)) {
  427. log_fn(LOG_DEBUG,"Got a listener socket. Can't happen!");
  428. return -1;
  429. }
  430. my_gettimeofday(&now);
  431. conn->timestamp_lastwritten = now.tv_sec;
  432. #ifdef USE_TLS
  433. if(connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING) {
  434. if(conn->state == OR_CONN_STATE_HANDSHAKING) {
  435. connection_stop_writing(conn);
  436. return connection_tls_continue_handshake(conn);
  437. }
  438. /* else open, or closing */
  439. switch(flush_buf_tls(conn->tls, &conn->outbuf, &conn->outbuflen,
  440. &conn->outbuf_flushlen, &conn->outbuf_datalen)) {
  441. case TOR_TLS_ERROR:
  442. case TOR_TLS_CLOSE:
  443. log_fn(LOG_DEBUG,"tls error. breaking.");
  444. return -1; /* XXX deal with close better */
  445. case TOR_TLS_WANTWRITE:
  446. /* we're already writing */
  447. return 0;
  448. case TOR_TLS_WANTREAD:
  449. /* Make sure to avoid a loop if the receive buckets are empty. */
  450. if(!connection_is_reading(conn)) {
  451. connection_stop_writing(conn);
  452. conn->wants_to_write = 1;
  453. /* we'll start reading again when the next second arrives,
  454. * and then also start writing again.
  455. */
  456. }
  457. /* else no problem, we're already reading */
  458. return 0;
  459. case TOR_TLS_DONE:
  460. /* for TOR_TLS_DONE, fall through to check if the flushlen
  461. * is empty, so we can stop writing.
  462. */
  463. }
  464. } else
  465. #endif
  466. {
  467. if(flush_buf(conn->s, &conn->outbuf, &conn->outbuflen,
  468. &conn->outbuf_flushlen, &conn->outbuf_datalen) < 0)
  469. return -1;
  470. /* conns in CONNECTING state will fall through... */
  471. }
  472. if(!connection_wants_to_flush(conn)) /* it's done flushing */
  473. if(connection_finished_flushing(conn) < 0) /* ...and get handled here. */
  474. return -1;
  475. return 0;
  476. }
  477. int connection_write_to_buf(char *string, int len, connection_t *conn) {
  478. if(!len)
  479. return 0;
  480. if(conn->marked_for_close)
  481. return 0;
  482. if( (!connection_speaks_cells(conn)) ||
  483. (!connection_state_is_open(conn)) ||
  484. (options.LinkPadding == 0) ) {
  485. /* connection types other than or, or or not in 'open' state, should flush immediately */
  486. /* also flush immediately if we're not doing LinkPadding, since otherwise it will never flush */
  487. connection_start_writing(conn);
  488. conn->outbuf_flushlen += len;
  489. }
  490. return write_to_buf(string, len, &conn->outbuf, &conn->outbuflen, &conn->outbuf_datalen);
  491. }
  492. int connection_receiver_bucket_should_increase(connection_t *conn) {
  493. assert(conn);
  494. if(!connection_speaks_cells(conn))
  495. return 0; /* edge connections don't use receiver_buckets */
  496. if(conn->receiver_bucket > 9*conn->bandwidth)
  497. return 0;
  498. return 1;
  499. }
  500. int connection_is_listener(connection_t *conn) {
  501. if(conn->type == CONN_TYPE_OR_LISTENER ||
  502. conn->type == CONN_TYPE_AP_LISTENER ||
  503. conn->type == CONN_TYPE_DIR_LISTENER)
  504. return 1;
  505. return 0;
  506. }
  507. int connection_state_is_open(connection_t *conn) {
  508. assert(conn);
  509. if((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  510. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  511. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN))
  512. return 1;
  513. return 0;
  514. }
  515. int connection_send_destroy(aci_t aci, connection_t *conn) {
  516. cell_t cell;
  517. assert(conn);
  518. if(!connection_speaks_cells(conn)) {
  519. log_fn(LOG_INFO,"Aci %d: At an edge. Marking connection for close.", aci);
  520. conn->marked_for_close = 1;
  521. return 0;
  522. }
  523. memset(&cell, 0, sizeof(cell_t));
  524. cell.aci = aci;
  525. cell.command = CELL_DESTROY;
  526. log_fn(LOG_INFO,"Sending destroy (aci %d).",aci);
  527. return connection_write_cell_to_buf(&cell, conn);
  528. }
  529. int connection_write_cell_to_buf(const cell_t *cellp, connection_t *conn) {
  530. char networkcell[CELL_NETWORK_SIZE];
  531. char *n = networkcell;
  532. cell_pack(n, cellp);
  533. #ifndef USE_TLS
  534. if(connection_encrypt_cell(n,conn)<0) {
  535. return -1;
  536. }
  537. #endif
  538. return connection_write_to_buf(n, CELL_NETWORK_SIZE, conn);
  539. }
  540. #ifndef USE_TLS
  541. int connection_encrypt_cell(char *cellp, connection_t *conn) {
  542. char cryptcell[CELL_NETWORK_SIZE];
  543. #if 0
  544. int x;
  545. char *px;
  546. printf("Sending: Cell header plaintext: ");
  547. px = (char *)cellp;
  548. for(x=0;x<8;x++) {
  549. printf("%u ",px[x]);
  550. }
  551. printf("\n");
  552. #endif
  553. assert(conn);
  554. if(crypto_cipher_encrypt(conn->f_crypto, cellp, CELL_NETWORK_SIZE, cryptcell)) {
  555. log(LOG_ERR,"Could not encrypt cell for connection %s:%u.",conn->address,conn->port);
  556. return -1;
  557. }
  558. #if 0
  559. printf("Sending: Cell header crypttext: ");
  560. px = (char *)&newcell;
  561. for(x=0;x<8;x++) {
  562. printf("%u ",px[x]);
  563. }
  564. printf("\n");
  565. #endif
  566. memcpy(cellp,cryptcell,CELL_NETWORK_SIZE);
  567. return 0;
  568. }
  569. #endif
  570. int connection_process_inbuf(connection_t *conn) {
  571. assert(conn);
  572. switch(conn->type) {
  573. case CONN_TYPE_OR:
  574. return connection_or_process_inbuf(conn);
  575. case CONN_TYPE_EXIT:
  576. case CONN_TYPE_AP:
  577. return connection_edge_process_inbuf(conn);
  578. case CONN_TYPE_DIR:
  579. return connection_dir_process_inbuf(conn);
  580. case CONN_TYPE_DNSWORKER:
  581. return connection_dns_process_inbuf(conn);
  582. case CONN_TYPE_CPUWORKER:
  583. return connection_cpu_process_inbuf(conn);
  584. default:
  585. log_fn(LOG_DEBUG,"got unexpected conn->type.");
  586. return -1;
  587. }
  588. }
  589. int connection_package_raw_inbuf(connection_t *conn) {
  590. int amount_to_process;
  591. cell_t cell;
  592. circuit_t *circ;
  593. assert(conn);
  594. assert(!connection_speaks_cells(conn));
  595. repeat_connection_package_raw_inbuf:
  596. circ = circuit_get_by_conn(conn);
  597. if(!circ) {
  598. log_fn(LOG_DEBUG,"conn has no circuits!");
  599. return -1;
  600. }
  601. if(circuit_consider_stop_edge_reading(circ, conn->type, conn->cpath_layer))
  602. return 0;
  603. if(conn->package_window <= 0) {
  604. log_fn(LOG_ERR,"called with package_window 0. Tell Roger.");
  605. connection_stop_reading(conn);
  606. return 0;
  607. }
  608. amount_to_process = conn->inbuf_datalen;
  609. if(!amount_to_process)
  610. return 0;
  611. /* Initialize the cell with 0's */
  612. memset(&cell, 0, sizeof(cell_t));
  613. if(amount_to_process > CELL_PAYLOAD_SIZE - RELAY_HEADER_SIZE) {
  614. cell.length = CELL_PAYLOAD_SIZE - RELAY_HEADER_SIZE;
  615. } else {
  616. cell.length = amount_to_process;
  617. }
  618. connection_fetch_from_buf(cell.payload+RELAY_HEADER_SIZE, cell.length, conn);
  619. log_fn(LOG_DEBUG,"(%d) Packaging %d bytes (%d waiting).",conn->s,cell.length, conn->inbuf_datalen);
  620. cell.command = CELL_RELAY;
  621. SET_CELL_RELAY_COMMAND(cell, RELAY_COMMAND_DATA);
  622. SET_CELL_STREAM_ID(cell, conn->stream_id);
  623. cell.length += RELAY_HEADER_SIZE;
  624. if(conn->type == CONN_TYPE_EXIT) {
  625. cell.aci = circ->p_aci;
  626. if(circuit_deliver_relay_cell(&cell, circ, CELL_DIRECTION_IN, NULL) < 0) {
  627. log_fn(LOG_DEBUG,"circuit_deliver_relay_cell (backward) failed. Closing.");
  628. circuit_close(circ);
  629. return 0;
  630. }
  631. assert(circ->package_window > 0);
  632. circ->package_window--;
  633. } else { /* send it forward. we're an AP */
  634. assert(conn->type == CONN_TYPE_AP);
  635. cell.aci = circ->n_aci;
  636. if(circuit_deliver_relay_cell(&cell, circ, CELL_DIRECTION_OUT, conn->cpath_layer) < 0) {
  637. log_fn(LOG_DEBUG,"circuit_deliver_relay_cell (forward) failed. Closing.");
  638. circuit_close(circ);
  639. return 0;
  640. }
  641. assert(conn->cpath_layer->package_window > 0);
  642. conn->cpath_layer->package_window--;
  643. }
  644. assert(conn->package_window > 0);
  645. if(--conn->package_window <= 0) { /* is it 0 after decrement? */
  646. connection_stop_reading(conn);
  647. log_fn(LOG_DEBUG,"conn->package_window reached 0.");
  648. circuit_consider_stop_edge_reading(circ, conn->type, conn->cpath_layer);
  649. return 0; /* don't process the inbuf any more */
  650. }
  651. log_fn(LOG_DEBUG,"conn->package_window is now %d",conn->package_window);
  652. /* handle more if there's more, or return 0 if there isn't */
  653. goto repeat_connection_package_raw_inbuf;
  654. }
  655. int connection_consider_sending_sendme(connection_t *conn, int edge_type) {
  656. circuit_t *circ;
  657. cell_t cell;
  658. if(connection_outbuf_too_full(conn))
  659. return 0;
  660. circ = circuit_get_by_conn(conn);
  661. if(!circ) {
  662. /* this can legitimately happen if the destroy has already arrived and torn down the circuit */
  663. log_fn(LOG_DEBUG,"No circuit associated with conn. Skipping.");
  664. return 0;
  665. }
  666. memset(&cell, 0, sizeof(cell_t));
  667. cell.command = CELL_RELAY;
  668. SET_CELL_RELAY_COMMAND(cell, RELAY_COMMAND_SENDME);
  669. SET_CELL_STREAM_ID(cell, conn->stream_id);
  670. cell.length += RELAY_HEADER_SIZE;
  671. if(edge_type == EDGE_EXIT)
  672. cell.aci = circ->p_aci;
  673. else
  674. cell.aci = circ->n_aci;
  675. while(conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  676. log_fn(LOG_DEBUG,"Outbuf %d, Queueing stream sendme.", conn->outbuf_flushlen);
  677. conn->deliver_window += STREAMWINDOW_INCREMENT;
  678. if(circuit_deliver_relay_cell(&cell, circ, CELL_DIRECTION(edge_type), conn->cpath_layer) < 0) {
  679. log_fn(LOG_DEBUG,"circuit_deliver_relay_cell failed. Closing.");
  680. circuit_close(circ);
  681. return 0;
  682. }
  683. }
  684. return 0;
  685. }
  686. int connection_finished_flushing(connection_t *conn) {
  687. assert(conn);
  688. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  689. switch(conn->type) {
  690. case CONN_TYPE_OR:
  691. return connection_or_finished_flushing(conn);
  692. case CONN_TYPE_AP:
  693. case CONN_TYPE_EXIT:
  694. return connection_edge_finished_flushing(conn);
  695. case CONN_TYPE_DIR:
  696. return connection_dir_finished_flushing(conn);
  697. case CONN_TYPE_DNSWORKER:
  698. return connection_dns_finished_flushing(conn);
  699. case CONN_TYPE_CPUWORKER:
  700. return connection_cpu_finished_flushing(conn);
  701. default:
  702. log_fn(LOG_DEBUG,"got unexpected conn->type.");
  703. return -1;
  704. }
  705. }
  706. int connection_process_cell_from_inbuf(connection_t *conn) {
  707. /* check if there's a whole cell there.
  708. * if yes, pull it off, decrypt it if we're not doing TLS, and process it.
  709. */
  710. #ifndef USE_TLS
  711. char networkcell[CELL_NETWORK_SIZE];
  712. #endif
  713. char buf[CELL_NETWORK_SIZE];
  714. // int x;
  715. cell_t cell;
  716. if(conn->inbuf_datalen < CELL_NETWORK_SIZE) /* entire response available? */
  717. return 0; /* not yet */
  718. #ifdef USE_TLS
  719. connection_fetch_from_buf(buf, CELL_NETWORK_SIZE, conn);
  720. #else
  721. connection_fetch_from_buf(networkcell, CELL_NETWORK_SIZE, conn);
  722. #if 0
  723. printf("Cell header crypttext: ");
  724. for(x=0;x<8;x++) {
  725. printf("%u ",crypted[x]);
  726. }
  727. printf("\n");
  728. #endif
  729. /* decrypt */
  730. if(crypto_cipher_decrypt(conn->b_crypto, networkcell, CELL_NETWORK_SIZE, buf)) {
  731. log_fn(LOG_ERR,"Decryption failed, dropping.");
  732. return connection_process_inbuf(conn); /* process the remainder of the buffer */
  733. }
  734. // log_fn(LOG_DEBUG,"Cell decrypted (%d bytes).",outlen);
  735. #if 0
  736. printf("Cell header plaintext: ");
  737. for(x=0;x<8;x++) {
  738. printf("%u ",outbuf[x]);
  739. }
  740. printf("\n");
  741. #endif
  742. #endif
  743. /* retrieve cell info from buf (create the host-order struct from the network-order string) */
  744. cell_unpack(&cell, buf);
  745. // log_fn(LOG_DEBUG,"Decrypted cell is of type %u (ACI %u).",cellp->command,cellp->aci);
  746. command_process_cell(&cell, conn);
  747. return connection_process_inbuf(conn); /* process the remainder of the buffer */
  748. }
  749. void
  750. cell_pack(char *dest, const cell_t *src)
  751. {
  752. *(uint16_t*)dest = htons(src->aci);
  753. *(uint8_t*)(dest+2) = src->command;
  754. *(uint8_t*)(dest+3) = src->length;
  755. *(uint32_t*)(dest+4) = 0; /* Reserved */
  756. memcpy(dest+8, src->payload, CELL_PAYLOAD_SIZE);
  757. }
  758. void
  759. cell_unpack(cell_t *dest, const char *src)
  760. {
  761. dest->aci = ntohs(*(uint16_t*)(src));
  762. dest->command = *(uint8_t*)(src+2);
  763. dest->length = *(uint8_t*)(src+3);
  764. dest->seq = ntohl(*(uint32_t*)(src+4));
  765. memcpy(dest->payload, src+8, CELL_PAYLOAD_SIZE);
  766. }
  767. /*
  768. Local Variables:
  769. mode:c
  770. indent-tabs-mode:nil
  771. c-basic-offset:2
  772. End:
  773. */