connection.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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. 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 master", /* 10 */
  19. };
  20. char *conn_state_to_string[][15] = {
  21. { }, /* no type associated with 0 */
  22. { "ready" }, /* op listener, 0 */
  23. { "awaiting keys", /* op, 0 */
  24. "open", /* 1 */
  25. "close", /* 2 */
  26. "close_wait" }, /* 3 */
  27. { "ready" }, /* or listener, 0 */
  28. { "connecting (as OP)", /* or, 0 */
  29. "sending keys (as OP)", /* 1 */
  30. "connecting (as client)", /* 2 */
  31. "sending auth (as client)", /* 3 */
  32. "waiting for auth (as client)", /* 4 */
  33. "sending nonce (as client)", /* 5 */
  34. "waiting for auth (as server)", /* 6 */
  35. "sending auth (as server)", /* 7 */
  36. "waiting for nonce (as server)",/* 8 */
  37. "open" }, /* 9 */
  38. { "waiting for dest info", /* exit, 0 */
  39. "connecting", /* 1 */
  40. "open" }, /* 2 */
  41. { "ready" }, /* app listener, 0 */
  42. { "", /* 0 */
  43. "", /* 1 */
  44. "", /* 2 */
  45. "awaiting dest info", /* app, 3 */
  46. "waiting for OR connection", /* 4 */
  47. "open" }, /* 5 */
  48. { "ready" }, /* dir listener, 0 */
  49. { "connecting", /* 0 */
  50. "sending command", /* 1 */
  51. "reading", /* 2 */
  52. "awaiting command", /* 3 */
  53. "writing" }, /* 4 */
  54. { "open" }, /* dns master, 0 */
  55. };
  56. /********* END VARIABLES ************/
  57. /**************************************************************/
  58. connection_t *connection_new(int type) {
  59. connection_t *conn;
  60. struct timeval now;
  61. my_gettimeofday(&now);
  62. conn = (connection_t *)malloc(sizeof(connection_t));
  63. if(!conn)
  64. return NULL;
  65. memset(conn,0,sizeof(connection_t)); /* zero it out to start */
  66. conn->type = type;
  67. if(buf_new(&conn->inbuf, &conn->inbuflen, &conn->inbuf_datalen) < 0 ||
  68. buf_new(&conn->outbuf, &conn->outbuflen, &conn->outbuf_datalen) < 0)
  69. return NULL;
  70. conn->receiver_bucket = 10240; /* should be enough to do the handshake */
  71. conn->bandwidth = conn->receiver_bucket / 10; /* give it a default */
  72. conn->timestamp_created = now.tv_sec;
  73. conn->timestamp_lastread = now.tv_sec;
  74. conn->timestamp_lastwritten = now.tv_sec;
  75. if (connection_speaks_cells(conn)) {
  76. conn->f_crypto = crypto_new_cipher_env(CRYPTO_CIPHER_3DES);
  77. if (!conn->f_crypto) {
  78. free((void *)conn);
  79. return NULL;
  80. }
  81. conn->b_crypto = crypto_new_cipher_env(CRYPTO_CIPHER_3DES);
  82. if (!conn->b_crypto) {
  83. crypto_free_cipher_env(conn->f_crypto);
  84. free((void *)conn);
  85. return NULL;
  86. }
  87. }
  88. #ifdef USE_ZLIB
  89. if (type == CONN_TYPE_AP || type == CONN_TYPE_EXIT) {
  90. if (buf_new(&conn->z_outbuf, &conn->z_outbuflen, &conn->z_outbuf_datalen) < 0)
  91. return NULL;
  92. if (! (conn->compression = compression_new()))
  93. return NULL;
  94. if (! (conn->decompression = decompression_new()))
  95. return NULL;
  96. } else {
  97. conn->compression = conn->decompression = NULL;
  98. }
  99. #endif
  100. conn->done_sending = conn->done_receiving = 0;
  101. return conn;
  102. }
  103. void connection_free(connection_t *conn) {
  104. assert(conn);
  105. buf_free(conn->inbuf);
  106. buf_free(conn->outbuf);
  107. if(conn->address)
  108. free(conn->address);
  109. if(conn->dest_addr)
  110. free(conn->dest_addr);
  111. if(connection_speaks_cells(conn)) {
  112. if (conn->f_crypto)
  113. crypto_free_cipher_env(conn->f_crypto);
  114. if (conn->b_crypto)
  115. crypto_free_cipher_env(conn->b_crypto);
  116. }
  117. if (conn->pkey)
  118. crypto_free_pk_env(conn->pkey);
  119. if(conn->s > 0) {
  120. log(LOG_INFO,"connection_free(): closing fd %d.",conn->s);
  121. close(conn->s);
  122. }
  123. if(conn->type == CONN_TYPE_OR) {
  124. directory_set_dirty();
  125. }
  126. #ifdef USE_ZLIB
  127. if (conn->compression) {
  128. decompression_free(conn->decompression);
  129. compression_free(conn->compression);
  130. buf_free(conn->z_outbuf);
  131. }
  132. #endif
  133. free(conn);
  134. }
  135. int connection_create_listener(struct sockaddr_in *bindaddr, int type) {
  136. connection_t *conn;
  137. int s;
  138. int one=1;
  139. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  140. if (s < 0)
  141. {
  142. log(LOG_ERR,"connection_create_listener(): Socket creation failed.");
  143. return -1;
  144. }
  145. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
  146. if(bind(s,(struct sockaddr *)bindaddr,sizeof(*bindaddr)) < 0) {
  147. perror("bind ");
  148. log(LOG_ERR,"Could not bind to port %u.",ntohs(bindaddr->sin_port));
  149. return -1;
  150. }
  151. if(listen(s,SOMAXCONN) < 0) {
  152. log(LOG_ERR,"Could not listen on port %u.",ntohs(bindaddr->sin_port));
  153. return -1;
  154. }
  155. fcntl(s, F_SETFL, O_NONBLOCK); /* set s to non-blocking */
  156. conn = connection_new(type);
  157. if(!conn) {
  158. log(LOG_DEBUG,"connection_create_listener(): connection_new failed. Giving up.");
  159. return -1;
  160. }
  161. conn->s = s;
  162. if(connection_add(conn) < 0) { /* no space, forget it */
  163. log(LOG_DEBUG,"connection_create_listener(): connection_add failed. Giving up.");
  164. connection_free(conn);
  165. return -1;
  166. }
  167. log(LOG_DEBUG,"connection_create_listener(): Listening on port %u.",ntohs(bindaddr->sin_port));
  168. conn->state = LISTENER_STATE_READY;
  169. connection_start_reading(conn);
  170. return 0;
  171. }
  172. int connection_handle_listener_read(connection_t *conn, int new_type, int new_state) {
  173. int news; /* the new socket */
  174. connection_t *newconn;
  175. struct sockaddr_in remote; /* information about the remote peer when connecting to other routers */
  176. int remotelen = sizeof(struct sockaddr_in); /* length of the remote address */
  177. news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
  178. if (news == -1) { /* accept() error */
  179. if(errno==EAGAIN)
  180. return 0; /* he hung up before we could accept(). that's fine. */
  181. /* else there was a real error. */
  182. log(LOG_ERR,"connection_handle_listener_read(): accept() failed. Closing.");
  183. return -1;
  184. }
  185. log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
  186. fcntl(news, F_SETFL, O_NONBLOCK); /* set news to non-blocking */
  187. newconn = connection_new(new_type);
  188. newconn->s = news;
  189. if(!connection_speaks_cells(newconn)) {
  190. newconn->receiver_bucket = -1;
  191. newconn->bandwidth = -1;
  192. }
  193. newconn->address = strdup(inet_ntoa(remote.sin_addr)); /* remember the remote address */
  194. newconn->addr = ntohl(remote.sin_addr.s_addr);
  195. newconn->port = ntohs(remote.sin_port);
  196. if(connection_add(newconn) < 0) { /* no space, forget it */
  197. connection_free(newconn);
  198. return 0; /* no need to tear down the parent */
  199. }
  200. log(LOG_DEBUG,"connection_handle_listener_read(): socket %d entered state %d.",newconn->s, new_state);
  201. newconn->state = new_state;
  202. connection_start_reading(newconn);
  203. return 0;
  204. }
  205. int retry_all_connections(uint16_t or_listenport,
  206. uint16_t op_listenport, uint16_t ap_listenport, uint16_t dir_listenport) {
  207. /* start all connections that should be up but aren't */
  208. struct sockaddr_in bindaddr; /* where to bind */
  209. if(or_listenport) {
  210. router_retry_connections();
  211. }
  212. memset(&bindaddr,0,sizeof(struct sockaddr_in));
  213. bindaddr.sin_family = AF_INET;
  214. bindaddr.sin_addr.s_addr = htonl(INADDR_ANY); /* anyone can connect */
  215. if(or_listenport) {
  216. bindaddr.sin_port = htons(or_listenport);
  217. if(!connection_get_by_type(CONN_TYPE_OR_LISTENER)) {
  218. connection_or_create_listener(&bindaddr);
  219. }
  220. }
  221. if(op_listenport) {
  222. bindaddr.sin_port = htons(op_listenport);
  223. if(!connection_get_by_type(CONN_TYPE_OP_LISTENER)) {
  224. connection_op_create_listener(&bindaddr);
  225. }
  226. }
  227. if(dir_listenport) {
  228. bindaddr.sin_port = htons(dir_listenport);
  229. if(!connection_get_by_type(CONN_TYPE_DIR_LISTENER)) {
  230. connection_dir_create_listener(&bindaddr);
  231. }
  232. }
  233. if(ap_listenport) {
  234. bindaddr.sin_port = htons(ap_listenport);
  235. inet_aton("127.0.0.1", &(bindaddr.sin_addr)); /* the AP listens only on localhost! */
  236. /* XXX inet_aton is missing on solaris. use something simpler? */
  237. if(!connection_get_by_type(CONN_TYPE_AP_LISTENER)) {
  238. connection_ap_create_listener(&bindaddr);
  239. }
  240. }
  241. return 0;
  242. }
  243. int connection_read_to_buf(connection_t *conn) {
  244. int read_result;
  245. struct timeval now;
  246. if(connection_speaks_cells(conn)) {
  247. assert(conn->receiver_bucket >= 0);
  248. }
  249. if(!connection_speaks_cells(conn)) {
  250. assert(conn->receiver_bucket < 0);
  251. }
  252. my_gettimeofday(&now);
  253. conn->timestamp_lastread = now.tv_sec;
  254. read_result = read_to_buf(conn->s, conn->receiver_bucket, &conn->inbuf, &conn->inbuflen,
  255. &conn->inbuf_datalen, &conn->inbuf_reached_eof);
  256. // log(LOG_DEBUG,"connection_read_to_buf(): read_to_buf returned %d.",read_result);
  257. if(read_result >= 0 && connection_speaks_cells(conn)) {
  258. // log(LOG_DEBUG,"connection_read_to_buf(): Read %d, bucket now %d.",read_result,conn->receiver_bucket);
  259. conn->receiver_bucket -= read_result;
  260. if(conn->receiver_bucket <= 0) {
  261. // log(LOG_DEBUG,"connection_read_to_buf() stopping reading, receiver bucket full.");
  262. connection_stop_reading(conn);
  263. /* If we're not in 'open' state here, then we're never going to finish the
  264. * handshake, because we'll never increment the receiver_bucket. But we
  265. * can't check for that here, because the buf we just read might have enough
  266. * on it to finish the handshake. So we check for that in check_conn_read().
  267. */
  268. }
  269. }
  270. return read_result;
  271. }
  272. int connection_fetch_from_buf(char *string, int len, connection_t *conn) {
  273. return fetch_from_buf(string, len, &conn->inbuf, &conn->inbuflen, &conn->inbuf_datalen);
  274. }
  275. #ifdef USE_ZLIB
  276. int connection_compress_from_buf(char *string, int len, connection_t *conn,
  277. int flush) {
  278. return compress_from_buf(string, len,
  279. &conn->inbuf, &conn->inbuflen, &conn->inbuf_datalen,
  280. conn->compression, flush);
  281. }
  282. int connection_decompress_to_buf(char *string, int len, connection_t *conn,
  283. int flush) {
  284. int n;
  285. struct timeval now;
  286. assert(conn);
  287. if (len) {
  288. if (write_to_buf(string, len,
  289. &conn->z_outbuf, &conn->z_outbuflen, &conn->z_outbuf_datalen) < 0)
  290. return -1;
  291. }
  292. /* If we have more that 10 payloads worth of data waiting in outbuf,
  293. * don't uncompress any more; queue this data in z_outbuf.
  294. *
  295. * This check should may be different.
  296. */
  297. if (connection_outbuf_too_full(conn))
  298. return 0;
  299. n = decompress_buf_to_buf(
  300. &conn->z_outbuf, &conn->z_outbuflen, &conn->z_outbuf_datalen,
  301. &conn->outbuf, &conn->outbuflen, &conn->outbuf_datalen,
  302. conn->decompression, flush);
  303. if (n < 0)
  304. return -1;
  305. my_gettimeofday(&now,NULL);
  306. if(!n)
  307. return 0;
  308. if(conn->marked_for_close)
  309. return 0;
  310. conn->timestamp_lastwritten = now.tv_sec;
  311. conn->outbuf_flushlen += n;
  312. return n;
  313. }
  314. #endif
  315. int connection_find_on_inbuf(char *string, int len, connection_t *conn) {
  316. return find_on_inbuf(string, len, conn->inbuf, conn->inbuf_datalen);
  317. }
  318. int connection_wants_to_flush(connection_t *conn) {
  319. return conn->outbuf_flushlen;
  320. }
  321. int connection_outbuf_too_full(connection_t *conn) {
  322. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  323. }
  324. int connection_flush_buf(connection_t *conn) {
  325. return flush_buf(conn->s, &conn->outbuf, &conn->outbuflen, &conn->outbuf_flushlen, &conn->outbuf_datalen);
  326. }
  327. int connection_write_to_buf(char *string, int len, connection_t *conn) {
  328. struct timeval now;
  329. my_gettimeofday(&now);
  330. if(!len)
  331. return 0;
  332. if(conn->marked_for_close)
  333. return 0;
  334. conn->timestamp_lastwritten = now.tv_sec;
  335. if( (!connection_speaks_cells(conn)) ||
  336. (!connection_state_is_open(conn)) ||
  337. (options.LinkPadding == 0) ) {
  338. /* connection types other than or and op, or or/op not in 'open' state, should flush immediately */
  339. /* also flush immediately if we're not doing LinkPadding, since otherwise it will never flush */
  340. connection_start_writing(conn);
  341. conn->outbuf_flushlen += len;
  342. }
  343. return write_to_buf(string, len, &conn->outbuf, &conn->outbuflen, &conn->outbuf_datalen);
  344. }
  345. int connection_receiver_bucket_should_increase(connection_t *conn) {
  346. assert(conn);
  347. if(!connection_speaks_cells(conn))
  348. return 0; /* edge connections don't use receiver_buckets */
  349. if(conn->receiver_bucket > 10*conn->bandwidth)
  350. return 0;
  351. return 1;
  352. }
  353. void connection_increment_receiver_bucket(connection_t *conn) {
  354. assert(conn);
  355. if(connection_receiver_bucket_should_increase(conn)) {
  356. /* yes, the receiver_bucket can become overfull here. But not by much. */
  357. conn->receiver_bucket += conn->bandwidth*1.1;
  358. // log(LOG_DEBUG,"connection_increment_receiver_bucket(): Bucket now %d.",conn->receiver_bucket);
  359. if(connection_state_is_open(conn)) {
  360. /* if we're in state 'open', then start reading again */
  361. connection_start_reading(conn);
  362. }
  363. }
  364. }
  365. int connection_speaks_cells(connection_t *conn) {
  366. assert(conn);
  367. if(conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_OP)
  368. return 1;
  369. return 0;
  370. }
  371. int connection_is_listener(connection_t *conn) {
  372. if(conn->type == CONN_TYPE_OP_LISTENER ||
  373. conn->type == CONN_TYPE_OR_LISTENER ||
  374. conn->type == CONN_TYPE_AP_LISTENER ||
  375. conn->type == CONN_TYPE_DIR_LISTENER)
  376. return 1;
  377. return 0;
  378. }
  379. int connection_state_is_open(connection_t *conn) {
  380. assert(conn);
  381. if((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  382. (conn->type == CONN_TYPE_OP && conn->state == OP_CONN_STATE_OPEN) ||
  383. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  384. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN))
  385. return 1;
  386. return 0;
  387. }
  388. void connection_send_cell(connection_t *conn) {
  389. cell_t cell;
  390. int bytes_in_full_flushlen;
  391. /* this function only gets called if options.LinkPadding is 1 */
  392. assert(options.LinkPadding == 1);
  393. assert(conn);
  394. if(!connection_speaks_cells(conn)) {
  395. /* this conn doesn't speak cells. do nothing. */
  396. return;
  397. }
  398. if(!connection_state_is_open(conn)) {
  399. /* it's not in 'open' state, all data should already be waiting to be flushed */
  400. assert(conn->outbuf_datalen == conn->outbuf_flushlen);
  401. return;
  402. }
  403. #if 0 /* use to send evenly spaced cells, but not padding */
  404. if(conn->outbuf_datalen - conn->outbuf_flushlen >= sizeof(cell_t)) {
  405. conn->outbuf_flushlen += sizeof(cell_t); /* instruct it to send a cell */
  406. connection_start_writing(conn);
  407. }
  408. #endif
  409. connection_increment_send_timeval(conn); /* update when we'll send the next cell */
  410. bytes_in_full_flushlen = conn->bandwidth / 100; /* 10ms worth */
  411. if(bytes_in_full_flushlen < 10*sizeof(cell_t))
  412. bytes_in_full_flushlen = 10*sizeof(cell_t); /* but at least 10 cells worth */
  413. if(conn->outbuf_flushlen > bytes_in_full_flushlen - sizeof(cell_t)) {
  414. /* if we would exceed bytes_in_full_flushlen by adding a new cell */
  415. return;
  416. }
  417. if(conn->outbuf_datalen - conn->outbuf_flushlen < sizeof(cell_t)) {
  418. /* we need to queue a padding cell first */
  419. memset(&cell,0,sizeof(cell_t));
  420. cell.command = CELL_PADDING;
  421. connection_write_cell_to_buf(&cell, conn);
  422. }
  423. /* ???? If we might not have added a cell above, why are we
  424. * ???? increasing outbuf_flushlen? -NM */
  425. /* The connection_write_cell_to_buf() call doesn't increase the flushlen
  426. * (if link padding is on). So if there isn't a whole cell waiting-but-
  427. * not-yet-flushed, we add a padding cell. Thus in any case the gap between
  428. * outbuf_datalen and outbuf_flushlen is at least sizeof(cell_t). -RD
  429. */
  430. /* XXXX actually, there are some subtle bugs lurking in here. They
  431. * have to do with the fact that we don't handle connection failure
  432. * cleanly. Sometimes we mark things to be closed later. Inside
  433. * connection_write_cell_to_buf, it returns successfully without
  434. * writing if the connection has been marked for close. We need to
  435. * look at all our failure cases more carefully and make sure they do
  436. * the right thing.
  437. */
  438. conn->outbuf_flushlen += sizeof(cell_t); /* instruct it to send a cell */
  439. connection_start_writing(conn);
  440. }
  441. void connection_increment_send_timeval(connection_t *conn) {
  442. /* add "1000000 * sizeof(cell_t) / conn->bandwidth" microseconds to conn->send_timeval */
  443. /* FIXME should perhaps use ceil() of this. For now I simply add 1. */
  444. tv_addms(&conn->send_timeval, 1+1000 * sizeof(cell_t) / conn->bandwidth);
  445. }
  446. void connection_init_timeval(connection_t *conn) {
  447. assert(conn);
  448. my_gettimeofday(&conn->send_timeval);
  449. connection_increment_send_timeval(conn);
  450. }
  451. int connection_send_destroy(aci_t aci, connection_t *conn) {
  452. cell_t cell;
  453. assert(conn);
  454. if(!connection_speaks_cells(conn)) {
  455. log(LOG_INFO,"connection_send_destroy(): Aci %d: At an edge. Marking connection for close.", aci);
  456. conn->marked_for_close = 1;
  457. return 0;
  458. }
  459. memset(&cell, 0, sizeof(cell_t));
  460. cell.aci = aci;
  461. cell.command = CELL_DESTROY;
  462. log(LOG_INFO,"connection_send_destroy(): Sending destroy (aci %d).",aci);
  463. return connection_write_cell_to_buf(&cell, conn);
  464. }
  465. int connection_write_cell_to_buf(const cell_t *cellp, connection_t *conn) {
  466. char networkcell[CELL_NETWORK_SIZE];
  467. char *n = networkcell;
  468. cell_pack(n, cellp);
  469. if(connection_encrypt_cell(n,conn)<0) {
  470. return -1;
  471. }
  472. return connection_write_to_buf(n, CELL_NETWORK_SIZE, conn);
  473. }
  474. int connection_encrypt_cell(char *cellp, connection_t *conn) {
  475. char cryptcell[CELL_NETWORK_SIZE];
  476. #if 0
  477. int x;
  478. char *px;
  479. printf("Sending: Cell header plaintext: ");
  480. px = (char *)cellp;
  481. for(x=0;x<8;x++) {
  482. printf("%u ",px[x]);
  483. }
  484. printf("\n");
  485. #endif
  486. assert(conn);
  487. if(crypto_cipher_encrypt(conn->f_crypto, cellp, CELL_NETWORK_SIZE, cryptcell)) {
  488. log(LOG_ERR,"Could not encrypt cell for connection %s:%u.",conn->address,conn->port);
  489. return -1;
  490. }
  491. #if 0
  492. printf("Sending: Cell header crypttext: ");
  493. px = (char *)&newcell;
  494. for(x=0;x<8;x++) {
  495. printf("%u ",px[x]);
  496. }
  497. printf("\n");
  498. #endif
  499. memcpy(cellp,cryptcell,CELL_NETWORK_SIZE);
  500. return 0;
  501. }
  502. int connection_process_inbuf(connection_t *conn) {
  503. assert(conn);
  504. switch(conn->type) {
  505. case CONN_TYPE_OP:
  506. return connection_op_process_inbuf(conn);
  507. case CONN_TYPE_OR:
  508. return connection_or_process_inbuf(conn);
  509. case CONN_TYPE_EXIT:
  510. case CONN_TYPE_AP:
  511. return connection_edge_process_inbuf(conn);
  512. case CONN_TYPE_DIR:
  513. return connection_dir_process_inbuf(conn);
  514. case CONN_TYPE_DNSMASTER:
  515. return connection_dns_process_inbuf(conn);
  516. default:
  517. log(LOG_DEBUG,"connection_process_inbuf() got unexpected conn->type.");
  518. return -1;
  519. }
  520. }
  521. int connection_package_raw_inbuf(connection_t *conn) {
  522. int amount_to_process, len;
  523. cell_t cell;
  524. circuit_t *circ;
  525. assert(conn);
  526. assert(!connection_speaks_cells(conn));
  527. /* this function should never get called if the receive_streamwindow is 0 */
  528. repeat_connection_package_raw_inbuf:
  529. amount_to_process = conn->inbuf_datalen;
  530. if(!amount_to_process)
  531. return 0;
  532. /* Initialize the cell with 0's */
  533. memset(&cell, 0, sizeof(cell_t));
  534. #ifdef USE_ZLIB
  535. /* This compression logic is not necessarily optimal:
  536. * 1) Maybe we should try to read as much as we can onto the inbuf before
  537. * compressing.
  538. * 2)
  539. */
  540. len = connection_compress_from_buf(cell.payload+RELAY_HEADER_SIZE,
  541. CELL_PAYLOAD_SIZE - RELAY_HEADER_SIZE,
  542. conn, Z_SYNC_FLUSH);
  543. if (len < 0)
  544. return -1;
  545. cell.length = len;
  546. #else
  547. if(amount_to_process > CELL_PAYLOAD_SIZE - RELAY_HEADER_SIZE) {
  548. cell.length = CELL_PAYLOAD_SIZE - RELAY_HEADER_SIZE;
  549. } else {
  550. cell.length = amount_to_process;
  551. }
  552. if(connection_fetch_from_buf(cell.payload+RELAY_HEADER_SIZE,
  553. cell.length, conn) < 0)
  554. return -1;
  555. #endif
  556. circ = circuit_get_by_conn(conn);
  557. if(!circ) {
  558. log(LOG_DEBUG,"connection_package_raw_inbuf(): conn has no circuits!");
  559. return -1;
  560. }
  561. log(LOG_DEBUG,"connection_package_raw_inbuf(): (%d) Packaging %d bytes (%d waiting).",conn->s,cell.length, conn->inbuf_datalen);
  562. cell.command = CELL_RELAY;
  563. SET_CELL_RELAY_COMMAND(cell, RELAY_COMMAND_DATA);
  564. SET_CELL_STREAM_ID(cell, conn->stream_id);
  565. cell.length += RELAY_HEADER_SIZE;
  566. if(conn->type == CONN_TYPE_EXIT) {
  567. cell.aci = circ->p_aci;
  568. if(circuit_deliver_relay_cell_from_edge(&cell, circ, EDGE_EXIT, NULL) < 0) {
  569. log(LOG_DEBUG,"connection_package_raw_inbuf(): circuit_deliver_relay_cell_from_edge (backward) failed. Closing.");
  570. circuit_close(circ);
  571. return 0;
  572. }
  573. assert(conn->n_receive_streamwindow > 0);
  574. if(--conn->n_receive_streamwindow <= 0) { /* is it 0 after decrement? */
  575. connection_stop_reading(conn);
  576. log(LOG_DEBUG,"connection_package_raw_inbuf(): receive_streamwindow at exit reached 0.");
  577. return 0; /* don't process the inbuf any more */
  578. }
  579. log(LOG_DEBUG,"connection_package_raw_inbuf(): receive_streamwindow at exit is %d",conn->n_receive_streamwindow);
  580. } else { /* send it forward. we're an AP */
  581. assert(conn->type == CONN_TYPE_AP);
  582. cell.aci = circ->n_aci;
  583. if(circuit_deliver_relay_cell_from_edge(&cell, circ, EDGE_AP, conn->cpath_layer) < 0) {
  584. log(LOG_DEBUG,"connection_package_raw_inbuf(): circuit_deliver_relay_cell_from_edge (forward) failed. Closing.");
  585. circuit_close(circ);
  586. return 0;
  587. }
  588. assert(conn->p_receive_streamwindow > 0);
  589. if(--conn->p_receive_streamwindow <= 0) { /* is it 0 after decrement? */
  590. connection_stop_reading(conn);
  591. log(LOG_DEBUG,"connection_package_raw_inbuf(): receive_streamwindow at AP reached 0.");
  592. return 0; /* don't process the inbuf any more */
  593. }
  594. log(LOG_DEBUG,"connection_package_raw_inbuf(): receive_streamwindow at AP is %d",conn->p_receive_streamwindow);
  595. }
  596. /* handle more if there's more, or return 0 if there isn't */
  597. goto repeat_connection_package_raw_inbuf;
  598. }
  599. int connection_consider_sending_sendme(connection_t *conn, int edge_type) {
  600. circuit_t *circ;
  601. cell_t cell;
  602. if(connection_outbuf_too_full(conn))
  603. return 0;
  604. circ = circuit_get_by_conn(conn);
  605. if(!circ) {
  606. /* this can legitimately happen if the destroy has already arrived and torn down the circuit */
  607. log(LOG_DEBUG,"connection_consider_sending_sendme(): No circuit associated with conn. Skipping.");
  608. return 0;
  609. }
  610. memset(&cell, 0, sizeof(cell_t));
  611. cell.command = CELL_RELAY;
  612. SET_CELL_RELAY_COMMAND(cell, RELAY_COMMAND_SENDME);
  613. SET_CELL_STREAM_ID(cell, conn->stream_id);
  614. cell.length += RELAY_HEADER_SIZE;
  615. if(edge_type == EDGE_EXIT) { /* we're at an exit */
  616. if(conn->p_receive_streamwindow < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  617. log(LOG_DEBUG,"connection_consider_sending_sendme(): Outbuf %d, Queueing stream sendme back.", conn->outbuf_flushlen);
  618. conn->p_receive_streamwindow += STREAMWINDOW_INCREMENT;
  619. cell.aci = circ->p_aci;
  620. if(circuit_deliver_relay_cell_from_edge(&cell, circ, edge_type, NULL) < 0) {
  621. log(LOG_DEBUG,"connection_consider_sending_sendme(): circuit_deliver_relay_cell_from_edge (backward) failed. Closing.");
  622. circuit_close(circ);
  623. return 0;
  624. }
  625. }
  626. } else { /* we're at an AP */
  627. assert(edge_type == EDGE_AP);
  628. if(conn->n_receive_streamwindow < STREAMWINDOW_START-STREAMWINDOW_INCREMENT) {
  629. log(LOG_DEBUG,"connection_consider_sending_sendme(): Outbuf %d, Queueing stream sendme forward.", conn->outbuf_flushlen);
  630. conn->n_receive_streamwindow += STREAMWINDOW_INCREMENT;
  631. cell.aci = circ->n_aci;
  632. if(circuit_deliver_relay_cell_from_edge(&cell, circ, edge_type, conn->cpath_layer) < 0) {
  633. log(LOG_DEBUG,"connection_consider_sending_sendme(): circuit_deliver_relay_cell_from_edge (forward) failed. Closing.");
  634. circuit_close(circ);
  635. return 0;
  636. }
  637. }
  638. }
  639. return 0;
  640. }
  641. int connection_finished_flushing(connection_t *conn) {
  642. assert(conn);
  643. // log(LOG_DEBUG,"connection_finished_flushing() entered. Socket %u.", conn->s);
  644. switch(conn->type) {
  645. case CONN_TYPE_OP:
  646. return connection_op_finished_flushing(conn);
  647. case CONN_TYPE_OR:
  648. return connection_or_finished_flushing(conn);
  649. case CONN_TYPE_AP:
  650. case CONN_TYPE_EXIT:
  651. return connection_edge_finished_flushing(conn);
  652. case CONN_TYPE_DIR:
  653. return connection_dir_finished_flushing(conn);
  654. case CONN_TYPE_DNSMASTER:
  655. return connection_dns_finished_flushing(conn);
  656. default:
  657. log(LOG_DEBUG,"connection_finished_flushing() got unexpected conn->type.");
  658. return -1;
  659. }
  660. }
  661. int connection_process_cell_from_inbuf(connection_t *conn) {
  662. /* check if there's a whole cell there.
  663. * if yes, pull it off, decrypt it, and process it.
  664. */
  665. char crypted[CELL_NETWORK_SIZE];
  666. char outbuf[1024];
  667. // int x;
  668. cell_t cell;
  669. if(conn->inbuf_datalen < CELL_NETWORK_SIZE) /* entire response available? */
  670. return 0; /* not yet */
  671. if(connection_fetch_from_buf(crypted,CELL_NETWORK_SIZE,conn) < 0) {
  672. return -1;
  673. }
  674. #if 0
  675. printf("Cell header crypttext: ");
  676. for(x=0;x<8;x++) {
  677. printf("%u ",crypted[x]);
  678. }
  679. printf("\n");
  680. #endif
  681. /* decrypt */
  682. if(crypto_cipher_decrypt(conn->b_crypto,crypted,CELL_NETWORK_SIZE,outbuf)) {
  683. log(LOG_ERR,"connection_process_cell_from_inbuf(): Decryption failed, dropping.");
  684. return connection_process_inbuf(conn); /* process the remainder of the buffer */
  685. }
  686. // log(LOG_DEBUG,"connection_process_cell_from_inbuf(): Cell decrypted (%d bytes).",outlen);
  687. #if 0
  688. printf("Cell header plaintext: ");
  689. for(x=0;x<8;x++) {
  690. printf("%u ",outbuf[x]);
  691. }
  692. printf("\n");
  693. #endif
  694. /* retrieve cell info from outbuf (create the host-order struct from the network-order string) */
  695. cell_unpack(&cell, outbuf);
  696. // log(LOG_DEBUG,"connection_process_cell_from_inbuf(): Decrypted cell is of type %u (ACI %u).",cellp->command,cellp->aci);
  697. command_process_cell(&cell, conn);
  698. return connection_process_inbuf(conn); /* process the remainder of the buffer */
  699. }
  700. void
  701. cell_pack(char *dest, const cell_t *src)
  702. {
  703. *(uint16_t*)dest = htons(src->aci);
  704. *(uint8_t*)(dest+2) = src->command;
  705. *(uint8_t*)(dest+3) = src->length;
  706. *(uint32_t*)(dest+4) = 0; /* Reserved */
  707. memcpy(dest+8, src->payload, CELL_PAYLOAD_SIZE);
  708. }
  709. void
  710. cell_unpack(cell_t *dest, const char *src)
  711. {
  712. dest->aci = ntohs(*(uint16_t*)(src));
  713. dest->command = *(uint8_t*)(src+2);
  714. dest->length = *(uint8_t*)(src+3);
  715. dest->seq = ntohl(*(uint32_t*)(src+4));
  716. memcpy(dest->payload, src+8, CELL_PAYLOAD_SIZE);
  717. }
  718. /*
  719. Local Variables:
  720. mode:c
  721. indent-tabs-mode:nil
  722. c-basic-offset:2
  723. End:
  724. */