main.c 16 KB

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