main.c 14 KB

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