connection.c 28 KB

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