main.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. /* Copyright 2001,2002 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "or.h"
  5. /********* START VARIABLES **********/
  6. or_options_t options; /* command-line and config-file options */
  7. int global_role;
  8. static connection_t *connection_array[MAXCONNECTIONS] =
  9. { NULL };
  10. static struct pollfd poll_array[MAXCONNECTIONS];
  11. /* = { [0 ... MAXCONNECTIONS-1] = { -1, 0, 0 } };
  12. */
  13. static int nfds=0; /* number of connections currently active */
  14. static int please_dumpstats=0; /* whether we should dump stats during the loop */
  15. /* private key */
  16. static crypto_pk_env_t *prkey;
  17. /* router array */
  18. static routerinfo_t **router_array = NULL;
  19. static int rarray_len = 0;
  20. /********* END VARIABLES ************/
  21. /****************************************************************************
  22. *
  23. * This section contains accessors and other methods on the connection_array
  24. * and poll_array variables (which are global within this file and unavailable
  25. * outside it).
  26. *
  27. ****************************************************************************/
  28. int connection_add(connection_t *conn) {
  29. if(nfds >= options.MaxConn-1) {
  30. log(LOG_INFO,"connection_add(): failing because nfds is too high.");
  31. return -1;
  32. }
  33. conn->poll_index = nfds;
  34. connection_set_poll_socket(conn);
  35. connection_array[nfds] = conn;
  36. /* zero these out here, because otherwise we'll inherit values from the previously freed one */
  37. poll_array[nfds].events = 0;
  38. poll_array[nfds].revents = 0;
  39. nfds++;
  40. log(LOG_INFO,"connection_add(): new conn type %d, socket %d, nfds %d.",conn->type, conn->s, nfds);
  41. return 0;
  42. }
  43. void connection_set_poll_socket(connection_t *conn) {
  44. poll_array[conn->poll_index].fd = conn->s;
  45. }
  46. int connection_remove(connection_t *conn) {
  47. int current_index;
  48. assert(conn);
  49. assert(nfds>0);
  50. log(LOG_INFO,"connection_remove(): removing socket %d, nfds now %d",conn->s, nfds-1);
  51. circuit_about_to_close_connection(conn); /* flush and send destroys for all circuits on this conn */
  52. current_index = conn->poll_index;
  53. if(current_index == nfds-1) { /* this is the end */
  54. nfds--;
  55. return 0;
  56. }
  57. /* we replace this one with the one at the end, then free it */
  58. nfds--;
  59. poll_array[current_index].fd = poll_array[nfds].fd;
  60. poll_array[current_index].events = poll_array[nfds].events;
  61. poll_array[current_index].revents = poll_array[nfds].revents;
  62. connection_array[current_index] = connection_array[nfds];
  63. connection_array[current_index]->poll_index = current_index;
  64. return 0;
  65. }
  66. int pkey_cmp(crypto_pk_env_t *a, crypto_pk_env_t *b) {
  67. /* return 0 if a and b are "the same key". Return non-0 otherwise. */
  68. return crypto_pk_cmp_keys(a, b);
  69. }
  70. connection_t *connection_twin_get_by_addr_port(uint32_t addr, uint16_t port) {
  71. /* Find a connection to the router described by addr and port,
  72. * or alternately any router which knows its key.
  73. * This connection *must* be in 'open' state.
  74. * If not, return NULL.
  75. */
  76. int i;
  77. connection_t *conn;
  78. routerinfo_t *router;
  79. /* first check if it's there exactly */
  80. conn = connection_exact_get_by_addr_port(addr,port);
  81. if(conn && connection_state_is_open(conn)) {
  82. log(LOG_INFO,"connection_twin_get_by_addr_port(): Found exact match.");
  83. return conn;
  84. }
  85. /* now check if any of the other open connections are a twin for this one */
  86. router = router_get_by_addr_port(addr,port);
  87. if(!router)
  88. return NULL;
  89. for(i=0;i<nfds;i++) {
  90. conn = connection_array[i];
  91. assert(conn);
  92. if(connection_state_is_open(conn) && !pkey_cmp(conn->pkey, router->pkey)) {
  93. log(LOG_INFO,"connection_twin_get_by_addr_port(): Found twin (%s).",conn->address);
  94. return conn;
  95. }
  96. }
  97. /* guess not */
  98. return NULL;
  99. }
  100. connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
  101. int i;
  102. connection_t *conn;
  103. for(i=0;i<nfds;i++) {
  104. conn = connection_array[i];
  105. assert(conn);
  106. if(conn->addr == addr && conn->port == port)
  107. return conn;
  108. }
  109. return NULL;
  110. }
  111. connection_t *connection_get_by_type(int type) {
  112. int i;
  113. connection_t *conn;
  114. for(i=0;i<nfds;i++) {
  115. conn = connection_array[i];
  116. if(conn->type == type)
  117. return conn;
  118. }
  119. return NULL;
  120. }
  121. /* the next 4 functions should move to routers.c once we get it
  122. * cleaned up more. The router_array and rarray_len variables should
  123. * move there too.
  124. */
  125. routerinfo_t *router_get_by_addr_port(uint32_t addr, uint16_t port) {
  126. int i;
  127. routerinfo_t *router;
  128. assert(router_array);
  129. for(i=0;i<rarray_len;i++) {
  130. router = router_array[i];
  131. if ((router->addr == addr) && (router->or_port == port))
  132. return router;
  133. }
  134. return NULL;
  135. }
  136. routerinfo_t *router_get_first_in_route(unsigned int *route, int routelen) {
  137. return router_array[route[routelen-1]];
  138. }
  139. /* a wrapper around new_route. put all these in routers.c perhaps? */
  140. unsigned int *router_new_route(int *routelen) {
  141. return new_route(options.CoinWeight, router_array, rarray_len, routelen);
  142. }
  143. /* a wrapper around create_onion */
  144. unsigned char *router_create_onion(unsigned int *route, int routelen, int *len, crypt_path_t **cpath) {
  145. return create_onion(router_array,rarray_len,route,routelen,len,cpath);
  146. }
  147. /* FIXME can we cut this function out? */
  148. connection_t *connect_to_router_as_op(routerinfo_t *router) {
  149. return connection_connect_to_router_as_op(router, options.ORPort);
  150. }
  151. void connection_watch_events(connection_t *conn, short events) {
  152. assert(conn && conn->poll_index < nfds);
  153. poll_array[conn->poll_index].events = events;
  154. }
  155. void connection_stop_reading(connection_t *conn) {
  156. assert(conn && conn->poll_index < nfds);
  157. log(LOG_DEBUG,"connection_stop_reading() called.");
  158. if(poll_array[conn->poll_index].events & POLLIN)
  159. poll_array[conn->poll_index].events -= POLLIN;
  160. }
  161. void connection_start_reading(connection_t *conn) {
  162. assert(conn && conn->poll_index < nfds);
  163. poll_array[conn->poll_index].events |= POLLIN;
  164. }
  165. void connection_stop_writing(connection_t *conn) {
  166. assert(conn && conn->poll_index < nfds);
  167. if(poll_array[conn->poll_index].events & POLLOUT)
  168. poll_array[conn->poll_index].events -= POLLOUT;
  169. }
  170. void connection_start_writing(connection_t *conn) {
  171. assert(conn && conn->poll_index < nfds);
  172. poll_array[conn->poll_index].events |= POLLOUT;
  173. }
  174. void check_conn_read(int i) {
  175. int retval;
  176. connection_t *conn;
  177. if(poll_array[i].revents & POLLIN) { /* something to read */
  178. conn = connection_array[i];
  179. assert(conn);
  180. // log(LOG_DEBUG,"check_conn_read(): socket %d has something to read.",conn->s);
  181. if (conn->type == CONN_TYPE_OP_LISTENER) {
  182. retval = connection_op_handle_listener_read(conn);
  183. } else if (conn->type == CONN_TYPE_OR_LISTENER) {
  184. retval = connection_or_handle_listener_read(conn);
  185. } else if (conn->type == CONN_TYPE_AP_LISTENER) {
  186. retval = connection_ap_handle_listener_read(conn);
  187. } else {
  188. /* else it's an OP, OR, or exit */
  189. retval = connection_read_to_buf(conn);
  190. if (retval >= 0) { /* all still well */
  191. retval = connection_process_inbuf(conn);
  192. // log(LOG_DEBUG,"check_conn_read(): connection_process_inbuf returned %d.",retval);
  193. if(retval >= 0 && !connection_state_is_open(conn) && conn->receiver_bucket == 0) {
  194. log(LOG_DEBUG,"check_conn_read(): receiver bucket reached 0 before handshake finished. Closing.");
  195. retval = -1;
  196. }
  197. }
  198. }
  199. if(retval < 0) { /* this connection is broken. remove it */
  200. log(LOG_INFO,"check_conn_read(): Connection broken, removing.");
  201. connection_remove(conn);
  202. connection_free(conn);
  203. if(i<nfds) { /* we just replaced the one at i with a new one.
  204. process it too. */
  205. check_conn_read(i);
  206. }
  207. }
  208. }
  209. }
  210. void check_conn_write(int i) {
  211. int retval;
  212. connection_t *conn;
  213. if(poll_array[i].revents & POLLOUT) { /* something to write */
  214. conn = connection_array[i];
  215. // log(LOG_DEBUG,"check_conn_write(): socket %d wants to write.",conn->s);
  216. if(conn->type == CONN_TYPE_OP_LISTENER ||
  217. conn->type == CONN_TYPE_OR_LISTENER) {
  218. log(LOG_DEBUG,"check_conn_write(): Got a listener socket. Can't happen!");
  219. retval = -1;
  220. } else {
  221. /* else it's an OP, OR, or exit */
  222. retval = connection_flush_buf(conn); /* conns in CONNECTING state will fall through... */
  223. if(retval == 0) { /* it's done flushing */
  224. retval = connection_finished_flushing(conn); /* ...and get handled here. */
  225. }
  226. }
  227. if(retval < 0) { /* this connection is broken. remove it. */
  228. log(LOG_DEBUG,"check_conn_write(): Connection broken, removing.");
  229. connection_remove(conn);
  230. connection_free(conn);
  231. if(i<nfds) { /* we just replaced the one at i with a new one.
  232. process it too. */
  233. check_conn_write(i);
  234. }
  235. }
  236. }
  237. }
  238. void check_conn_marked(int i) {
  239. connection_t *conn;
  240. conn = connection_array[i];
  241. assert(conn);
  242. if(conn->marked_for_close) {
  243. log(LOG_DEBUG,"check_conn_marked(): Cleaning up connection.");
  244. if(conn->s >= 0) { /* might be an incomplete exit connection */
  245. /* FIXME there's got to be a better way to check for this -- and make other checks? */
  246. connection_flush_buf(conn); /* flush it first */
  247. }
  248. connection_remove(conn);
  249. connection_free(conn);
  250. if(i<nfds) { /* we just replaced the one at i with a new one.
  251. process it too. */
  252. check_conn_marked(i);
  253. }
  254. }
  255. }
  256. int prepare_for_poll(int *timeout) {
  257. int i;
  258. int need_to_refill_buckets = 0;
  259. connection_t *conn = NULL;
  260. connection_t *tmpconn;
  261. struct timeval now, soonest;
  262. static int current_second = 0; /* from previous calls to gettimeofday */
  263. int ms_until_conn;
  264. *timeout = -1; /* set it to never timeout, possibly overridden below */
  265. /* first check if we need to refill buckets */
  266. for(i=0;i<nfds;i++) {
  267. if(connection_receiver_bucket_should_increase(connection_array[i])) {
  268. need_to_refill_buckets = 1;
  269. break;
  270. }
  271. }
  272. if(gettimeofday(&now,NULL) < 0)
  273. return -1;
  274. if(need_to_refill_buckets) {
  275. if(now.tv_sec > current_second) { /* the second has already rolled over! */
  276. // log(LOG_DEBUG,"prepare_for_poll(): The second has rolled over, immediately refilling.");
  277. for(i=0;i<nfds;i++)
  278. connection_increment_receiver_bucket(connection_array[i]);
  279. current_second = now.tv_sec; /* remember which second it is, for next time */
  280. }
  281. *timeout = 1000 - (now.tv_usec / 1000); /* how many milliseconds til the next second? */
  282. // log(LOG_DEBUG,"prepare_for_poll(): %d milliseconds til next second.",*timeout);
  283. }
  284. if(options.LinkPadding) {
  285. /* now check which conn wants to speak soonest */
  286. for(i=0;i<nfds;i++) {
  287. tmpconn = connection_array[i];
  288. if(!connection_speaks_cells(tmpconn))
  289. continue; /* this conn type doesn't send cells */
  290. if(!connection_state_is_open(tmpconn))
  291. continue; /* only conns in state 'open' have a valid send_timeval */
  292. while(tv_cmp(&tmpconn->send_timeval,&now) <= 0) { /* send_timeval has already passed, let it send a cell */
  293. // log(LOG_DEBUG,"prepare_for_poll(): doing backlogged connection_send_cell on socket %d (%d ms old)",tmpconn->s,
  294. // (now.tv_sec - tmpconn->send_timeval.tv_sec)*1000 +
  295. // (now.tv_usec - tmpconn->send_timeval.tv_usec)/1000
  296. // );
  297. connection_send_cell(tmpconn);
  298. }
  299. if(!conn || tv_cmp(&tmpconn->send_timeval, &soonest) < 0) { /* this is the best choice so far */
  300. // log(LOG_DEBUG,"prepare_for_poll(): chose socket %d as best connection so far",tmpconn->s);
  301. conn = tmpconn;
  302. soonest.tv_sec = conn->send_timeval.tv_sec;
  303. soonest.tv_usec = conn->send_timeval.tv_usec;
  304. }
  305. }
  306. if(conn) { /* we might want to set *timeout sooner */
  307. ms_until_conn = (soonest.tv_sec - now.tv_sec)*1000 +
  308. (soonest.tv_usec - now.tv_usec)/1000;
  309. // log(LOG_DEBUG,"prepare_for_poll(): conn %d times out in %d ms.",conn->s, ms_until_conn);
  310. if(*timeout == -1 || ms_until_conn < *timeout) { /* use the new one */
  311. // log(LOG_DEBUG,"prepare_for_poll(): conn %d soonest, in %d ms.",conn->s,ms_until_conn);
  312. *timeout = ms_until_conn;
  313. }
  314. }
  315. }
  316. return 0;
  317. }
  318. int do_main_loop(void) {
  319. int i;
  320. int timeout;
  321. int poll_result;
  322. /* load the routers file */
  323. router_array = getrouters(options.RouterFile,&rarray_len, options.ORPort);
  324. if (!router_array)
  325. {
  326. log(LOG_ERR,"Error loading router list.");
  327. return -1;
  328. }
  329. /* load the private key, if we're supposed to have one */
  330. if(ROLE_IS_OR(global_role)) {
  331. prkey = crypto_new_pk_env(CRYPTO_PK_RSA);
  332. if (!prkey) {
  333. log(LOG_ERR,"Error creating a crypto environment.");
  334. return -1;
  335. }
  336. if (crypto_pk_read_private_key_filename(prkey, options.PrivateKeyFile))
  337. {
  338. log(LOG_ERR,"Error loading private key.");
  339. return -1;
  340. }
  341. }
  342. /* start-up the necessary connections based on global_role. This is where we
  343. * try to connect to all the other ORs, and start the listeners */
  344. retry_all_connections(options.Role, router_array, rarray_len, prkey,
  345. options.ORPort, options.OPPort, options.APPort);
  346. for(;;) {
  347. if(please_dumpstats) {
  348. dumpstats();
  349. }
  350. if(prepare_for_poll(&timeout) < 0) {
  351. log(LOG_DEBUG,"do_main_loop(): prepare_for_poll failed, exiting.");
  352. return -1;
  353. }
  354. /* now timeout is the value we'll hand to poll. It's either -1, meaning
  355. * don't timeout, else it indicates the soonest event (either the
  356. * one-second rollover for refilling receiver buckets, or the soonest
  357. * conn that needs to send a cell)
  358. */
  359. /* if the timeout is less than 10, set it to 10 */
  360. if(timeout >= 0 && timeout < 10)
  361. timeout = 10;
  362. /* poll until we have an event, or it's time to do something */
  363. poll_result = poll(poll_array, nfds, timeout);
  364. #if 0 /* let catch() handle things like ^c, and otherwise don't worry about it */
  365. if(poll_result < 0) {
  366. log(LOG_ERR,"do_main_loop(): poll failed.");
  367. if(errno != EINTR) /* let the program survive things like ^z */
  368. return -1;
  369. }
  370. #endif
  371. if(poll_result > 0) { /* we have at least one connection to deal with */
  372. /* do all the reads first, so we can detect closed sockets */
  373. for(i=0;i<nfds;i++)
  374. check_conn_read(i); /* this also blows away broken connections */
  375. /* then do the writes */
  376. for(i=0;i<nfds;i++)
  377. check_conn_write(i);
  378. /* any of the conns need to be closed now? */
  379. for(i=0;i<nfds;i++)
  380. check_conn_marked(i);
  381. }
  382. /* refilling buckets and sending cells happens at the beginning of the
  383. * next iteration of the loop, inside prepare_for_poll()
  384. */
  385. }
  386. }
  387. void catchint () {
  388. errno = 0; /* netcat does this. it looks fun. */
  389. log(LOG_NOTICE,"Catching ^c, exiting cleanly.");
  390. exit(0);
  391. }
  392. void catchusr1 () {
  393. please_dumpstats = 1;
  394. }
  395. void dumpstats (void) { /* dump stats to stdout */
  396. int i;
  397. connection_t *conn;
  398. extern char *conn_type_to_string[];
  399. extern char *conn_state_to_string[][10];
  400. printf("Dumping stats:\n");
  401. for(i=0;i<nfds;i++) {
  402. conn = connection_array[i];
  403. printf("Conn %d (socket %d) type %d (%s), state %d (%s)\n",
  404. i, conn->s, conn->type, conn_type_to_string[conn->type],
  405. conn->state, conn_state_to_string[conn->type][conn->state]);
  406. if(!connection_is_listener(conn)) {
  407. printf("Conn %d is to '%s:%d'.\n",i,conn->address, conn->port);
  408. }
  409. circuit_dump_by_conn(conn); /* dump info about all the circuits using this conn */
  410. printf("\n");
  411. }
  412. please_dumpstats = 0;
  413. }
  414. int main(int argc, char *argv[]) {
  415. int retval = 0;
  416. signal (SIGINT, catchint); /* to catch ^c so we can exit cleanly */
  417. signal (SIGUSR1, catchusr1); /* to dump stats to stdout */
  418. if ( getoptions(argc,argv,&options) ) exit(1);
  419. log(options.loglevel,NULL); /* assign logging severity level from options */
  420. global_role = options.Role; /* assign global_role from options. FIX: remove from global namespace later. */
  421. crypto_global_init();
  422. retval = do_main_loop();
  423. crypto_global_cleanup();
  424. return retval;
  425. }