main.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "or.h"
  5. /********* PROTOTYPES **********/
  6. static void dumpstats(int severity); /* log stats */
  7. static int init_from_config(int argc, char **argv);
  8. /********* START VARIABLES **********/
  9. extern char *conn_state_to_string[][_CONN_TYPE_MAX+1];
  10. or_options_t options; /* command-line and config-file options */
  11. int global_read_bucket; /* max number of bytes I can read this second */
  12. static int stats_prev_global_read_bucket;
  13. static uint64_t stats_n_bytes_read = 0;
  14. static long stats_n_seconds_reading = 0;
  15. static connection_t *connection_array[MAXCONNECTIONS] =
  16. { NULL };
  17. static struct pollfd poll_array[MAXCONNECTIONS];
  18. static int nfds=0; /* number of connections currently active */
  19. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  20. static int please_dumpstats=0; /* whether we should dump stats during the loop */
  21. static int please_reset=0; /* whether we just got a sighup */
  22. static int please_reap_children=0; /* whether we should waitpid for exited children */
  23. #endif /* signal stuff */
  24. int has_fetched_directory=0;
  25. /* we set this to 1 when we've fetched a dir, to know whether to complain
  26. * yet about unrecognized nicknames in entrynodes, exitnodes, etc. */
  27. int has_completed_circuit=0;
  28. /* we set this to 1 when we've opened a circuit, so we can print a log
  29. * entry to inform the user that Tor is working. */
  30. /********* END VARIABLES ************/
  31. /****************************************************************************
  32. *
  33. * This section contains accessors and other methods on the connection_array
  34. * and poll_array variables (which are global within this file and unavailable
  35. * outside it).
  36. *
  37. ****************************************************************************/
  38. int connection_add(connection_t *conn) {
  39. if(nfds >= options.MaxConn-1) {
  40. log_fn(LOG_WARN,"failing because nfds is too high.");
  41. return -1;
  42. }
  43. conn->poll_index = nfds;
  44. connection_set_poll_socket(conn);
  45. connection_array[nfds] = conn;
  46. /* zero these out here, because otherwise we'll inherit values from the previously freed one */
  47. poll_array[nfds].events = 0;
  48. poll_array[nfds].revents = 0;
  49. nfds++;
  50. log_fn(LOG_INFO,"new conn type %s, socket %d, nfds %d.",
  51. CONN_TYPE_TO_STRING(conn->type), conn->s, nfds);
  52. return 0;
  53. }
  54. void connection_set_poll_socket(connection_t *conn) {
  55. poll_array[conn->poll_index].fd = conn->s;
  56. }
  57. /* Remove the connection from the global list, and remove the
  58. * corresponding poll entry. Calling this function will shift the last
  59. * connection (if any) into the position occupied by conn.
  60. */
  61. int connection_remove(connection_t *conn) {
  62. int current_index;
  63. assert(conn);
  64. assert(nfds>0);
  65. log_fn(LOG_INFO,"removing socket %d (type %s), nfds now %d",
  66. conn->s, CONN_TYPE_TO_STRING(conn->type), nfds-1);
  67. /* if it's an edge conn, remove it from the list
  68. * of conn's on this circuit. If it's not on an edge,
  69. * flush and send destroys for all circuits on this conn
  70. */
  71. circuit_about_to_close_connection(conn);
  72. current_index = conn->poll_index;
  73. if(current_index == nfds-1) { /* this is the end */
  74. nfds--;
  75. return 0;
  76. }
  77. /* replace this one with the one at the end */
  78. nfds--;
  79. poll_array[current_index].fd = poll_array[nfds].fd;
  80. poll_array[current_index].events = poll_array[nfds].events;
  81. poll_array[current_index].revents = poll_array[nfds].revents;
  82. connection_array[current_index] = connection_array[nfds];
  83. connection_array[current_index]->poll_index = current_index;
  84. return 0;
  85. }
  86. void get_connection_array(connection_t ***array, int *n) {
  87. *array = connection_array;
  88. *n = nfds;
  89. }
  90. void connection_watch_events(connection_t *conn, short events) {
  91. assert(conn && conn->poll_index < nfds);
  92. poll_array[conn->poll_index].events = events;
  93. }
  94. int connection_is_reading(connection_t *conn) {
  95. return poll_array[conn->poll_index].events & POLLIN;
  96. }
  97. void connection_stop_reading(connection_t *conn) {
  98. assert(conn && conn->poll_index < nfds);
  99. log(LOG_DEBUG,"connection_stop_reading() called.");
  100. if(poll_array[conn->poll_index].events & POLLIN)
  101. poll_array[conn->poll_index].events -= POLLIN;
  102. }
  103. void connection_start_reading(connection_t *conn) {
  104. assert(conn && conn->poll_index < nfds);
  105. poll_array[conn->poll_index].events |= POLLIN;
  106. }
  107. int connection_is_writing(connection_t *conn) {
  108. return poll_array[conn->poll_index].events & POLLOUT;
  109. }
  110. void connection_stop_writing(connection_t *conn) {
  111. assert(conn && conn->poll_index < nfds);
  112. if(poll_array[conn->poll_index].events & POLLOUT)
  113. poll_array[conn->poll_index].events -= POLLOUT;
  114. }
  115. void connection_start_writing(connection_t *conn) {
  116. assert(conn && conn->poll_index < nfds);
  117. poll_array[conn->poll_index].events |= POLLOUT;
  118. }
  119. static void conn_read(int i) {
  120. connection_t *conn = connection_array[i];
  121. if (conn->marked_for_close)
  122. return;
  123. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
  124. * discussion of POLLIN vs POLLHUP */
  125. if(!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
  126. if(!connection_is_reading(conn) ||
  127. !connection_has_pending_tls_data(conn))
  128. return; /* this conn should not read */
  129. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  130. assert_connection_ok(conn, time(NULL));
  131. if(
  132. /* XXX does POLLHUP also mean it's definitely broken? */
  133. #ifdef MS_WINDOWS
  134. (poll_array[i].revents & POLLERR) ||
  135. #endif
  136. connection_handle_read(conn) < 0) {
  137. if (!conn->marked_for_close) {
  138. /* this connection is broken. remove it */
  139. /* XXX This shouldn't ever happen anymore. */
  140. /* XXX but it'll clearly happen on MS_WINDOWS from POLLERR, right? */
  141. log_fn(LOG_ERR,"Unhandled error on read for %s connection (fd %d); removing",
  142. CONN_TYPE_TO_STRING(conn->type), conn->s);
  143. connection_mark_for_close(conn,0);
  144. }
  145. }
  146. assert_connection_ok(conn, time(NULL));
  147. }
  148. static void conn_write(int i) {
  149. connection_t *conn;
  150. if(!(poll_array[i].revents & POLLOUT))
  151. return; /* this conn doesn't want to write */
  152. conn = connection_array[i];
  153. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  154. if (conn->marked_for_close)
  155. return;
  156. assert_connection_ok(conn, time(NULL));
  157. if (connection_handle_write(conn) < 0) {
  158. if (!conn->marked_for_close) {
  159. /* this connection is broken. remove it. */
  160. log_fn(LOG_WARN,"Unhandled error on read for %s connection (fd %d); removing",
  161. CONN_TYPE_TO_STRING(conn->type), conn->s);
  162. conn->has_sent_end = 1; /* otherwise we cry wolf about duplicate close */
  163. connection_mark_for_close(conn,0);
  164. }
  165. }
  166. assert_connection_ok(conn, time(NULL));
  167. }
  168. static void conn_close_if_marked(int i) {
  169. connection_t *conn;
  170. int retval;
  171. conn = connection_array[i];
  172. assert_connection_ok(conn, time(NULL));
  173. if(!conn->marked_for_close)
  174. return; /* nothing to see here, move along */
  175. log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
  176. if(conn->s >= 0 && connection_wants_to_flush(conn)) {
  177. /* -1 means it's an incomplete edge connection, or that the socket
  178. * has already been closed as unflushable. */
  179. if(!conn->hold_open_until_flushed)
  180. log_fn(LOG_WARN,
  181. "Conn (fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
  182. "(Marked at %s:%d)",
  183. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  184. conn->outbuf_flushlen, conn->marked_for_close_file, conn->marked_for_close);
  185. if(connection_speaks_cells(conn)) {
  186. if(conn->state == OR_CONN_STATE_OPEN) {
  187. retval = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  188. /* XXX actually, some non-zero results are maybe ok. which ones? */
  189. } else
  190. retval = -1; /* never flush non-open broken tls connections */
  191. } else {
  192. retval = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  193. }
  194. if(retval >= 0 &&
  195. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  196. log_fn(LOG_INFO,"Holding conn (fd %d) open for more flushing.",conn->s);
  197. /* XXX should we reset timestamp_lastwritten here? */
  198. return;
  199. }
  200. if(connection_wants_to_flush(conn)) {
  201. log_fn(LOG_WARN,"Conn (fd %d, type %s, state %d) still wants to flush. Losing %d bytes! (Marked at %s:%d)",
  202. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  203. (int)buf_datalen(conn->outbuf), conn->marked_for_close_file,
  204. conn->marked_for_close);
  205. }
  206. }
  207. connection_remove(conn);
  208. connection_free(conn);
  209. if(i<nfds) { /* we just replaced the one at i with a new one.
  210. process it too. */
  211. conn_close_if_marked(i);
  212. }
  213. }
  214. /* Perform regular maintenance tasks for a single connection. This
  215. * function gets run once per second per connection by run_housekeeping.
  216. */
  217. static void run_connection_housekeeping(int i, time_t now) {
  218. cell_t cell;
  219. connection_t *conn = connection_array[i];
  220. /* check connections to see whether we should send a keepalive, expire, or wait */
  221. if(!connection_speaks_cells(conn))
  222. return;
  223. if(now >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
  224. if((!options.ORPort && !circuit_get_by_conn(conn)) ||
  225. (!connection_state_is_open(conn))) {
  226. /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
  227. log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
  228. i,conn->address, conn->port);
  229. /* flush anything waiting, e.g. a destroy for a just-expired circ */
  230. connection_mark_for_close(conn,CLOSE_REASON_UNUSED_OR_CONN);
  231. conn->hold_open_until_flushed = 1;
  232. } else {
  233. /* either a full router, or we've got a circuit. send a padding cell. */
  234. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  235. conn->address, conn->port);
  236. memset(&cell,0,sizeof(cell_t));
  237. cell.command = CELL_PADDING;
  238. connection_or_write_cell_to_buf(&cell, conn);
  239. }
  240. }
  241. }
  242. /* Perform regular maintenance tasks. This function gets run once per
  243. * second by prepare_for_poll.
  244. */
  245. static void run_scheduled_events(time_t now) {
  246. static long time_to_fetch_directory = 0;
  247. static long time_to_new_circuit = 0;
  248. circuit_t *circ;
  249. int i;
  250. /* 1. Every DirFetchPostPeriod seconds, we get a new directory and upload
  251. * our descriptor (if any). */
  252. if(time_to_fetch_directory < now) {
  253. /* it's time to fetch a new directory and/or post our descriptor */
  254. if(options.ORPort) {
  255. router_rebuild_descriptor();
  256. router_upload_desc_to_dirservers();
  257. }
  258. if(!options.DirPort) {
  259. /* NOTE directory servers do not currently fetch directories.
  260. * Hope this doesn't bite us later. */
  261. directory_initiate_command(router_pick_directory_server(),
  262. DIR_CONN_STATE_CONNECTING_FETCH);
  263. }
  264. time_to_fetch_directory = now + options.DirFetchPostPeriod;
  265. }
  266. /* 2. Every second, we examine pending circuits and prune the
  267. * ones which have been pending for more than 3 seconds.
  268. * We do this before step 3, so it can try building more if
  269. * it's not comfortable with the number of available circuits.
  270. */
  271. circuit_expire_building();
  272. /* 2b. Also look at pending streams and prune the ones that 'began'
  273. * a long time ago but haven't gotten a 'connected' yet.
  274. * Do this before step 3, so we can put them back into pending
  275. * state to be picked up by the new circuit.
  276. */
  277. connection_ap_expire_beginning();
  278. /* 2c. And expire connections that we've held open for too long.
  279. */
  280. connection_expire_held_open();
  281. /* 3. Every second, we try a new circuit if there are no valid
  282. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  283. * that became dirty more than NewCircuitPeriod seconds ago,
  284. * and we make a new circ if there are no clean circuits.
  285. */
  286. if(options.SocksPort || options.RunTesting) {
  287. if (options.SocksPort)
  288. /* launch a new circ for any pending streams that need one */
  289. connection_ap_attach_pending();
  290. /* Build a new test circuit every 5 minutes */
  291. #define TESTING_CIRCUIT_INTERVAL 300
  292. circ = circuit_get_newest(NULL, 1);
  293. if(time_to_new_circuit < now) {
  294. client_dns_clean();
  295. circuit_expire_unused_circuits();
  296. circuit_reset_failure_count();
  297. if(circ && circ->timestamp_dirty) {
  298. log_fn(LOG_INFO,"Youngest circuit dirty; launching replacement.");
  299. circuit_launch_new(); /* make a new circuit */
  300. } else if (options.RunTesting && circ &&
  301. circ->timestamp_created + TESTING_CIRCUIT_INTERVAL < now) {
  302. log_fn(LOG_INFO,"Creating a new testing circuit.");
  303. circuit_launch_new();
  304. }
  305. time_to_new_circuit = now + options.NewCircuitPeriod;
  306. }
  307. #define CIRCUIT_MIN_BUILDING 3
  308. if(!circ && circuit_count_building() < CIRCUIT_MIN_BUILDING) {
  309. /* if there's no open circ, and less than 3 are on the way,
  310. * go ahead and try another.
  311. */
  312. circuit_launch_new();
  313. }
  314. }
  315. /* 5. We do housekeeping for each connection... */
  316. for(i=0;i<nfds;i++) {
  317. run_connection_housekeeping(i, now);
  318. }
  319. /* 6. And remove any marked circuits... */
  320. circuit_close_all_marked();
  321. /* 7. and blow away any connections that need to die. can't do this later
  322. * because we might open up a circuit and not realize we're about to cull
  323. * the connection it's running over.
  324. * XXX we can remove this step once we audit circuit-building to make sure
  325. * it doesn't pick a marked-for-close conn. -RD
  326. */
  327. for(i=0;i<nfds;i++)
  328. conn_close_if_marked(i);
  329. }
  330. static int prepare_for_poll(void) {
  331. static long current_second = 0; /* from previous calls to gettimeofday */
  332. connection_t *conn;
  333. struct timeval now;
  334. int i;
  335. tor_gettimeofday(&now);
  336. /* Check how much bandwidth we've consumed,
  337. * and increment the token buckets. */
  338. stats_n_bytes_read += stats_prev_global_read_bucket-global_read_bucket;
  339. connection_bucket_refill(&now);
  340. stats_prev_global_read_bucket = global_read_bucket;
  341. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  342. ++stats_n_seconds_reading;
  343. run_scheduled_events(now.tv_sec);
  344. current_second = now.tv_sec; /* remember which second it is, for next time */
  345. }
  346. for(i=0;i<nfds;i++) {
  347. conn = connection_array[i];
  348. if(connection_has_pending_tls_data(conn) &&
  349. connection_is_reading(conn)) {
  350. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  351. return 0; /* has pending bytes to read; don't let poll wait. */
  352. }
  353. }
  354. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  355. }
  356. static int init_from_config(int argc, char **argv) {
  357. if(getconfig(argc,argv,&options)) {
  358. log_fn(LOG_ERR,"Reading config failed. For usage, try -h.");
  359. return -1;
  360. }
  361. close_logs(); /* we'll close, then open with correct loglevel if necessary */
  362. if(options.User || options.Group) {
  363. if(switch_id(options.User, options.Group) != 0) {
  364. return -1;
  365. }
  366. }
  367. if (options.RunAsDaemon) {
  368. start_daemon(options.DataDirectory);
  369. }
  370. if(!options.LogFile && !options.RunAsDaemon)
  371. add_stream_log(options.loglevel, "<stdout>", stdout);
  372. if(options.LogFile) {
  373. if (add_file_log(options.loglevel, options.LogFile) != 0) {
  374. /* opening the log file failed! Use stderr and log a warning */
  375. add_stream_log(options.loglevel, "<stderr>", stderr);
  376. log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", options.LogFile, strerror(errno));
  377. }
  378. log_fn(LOG_WARN, "Successfully opened LogFile '%s', redirecting output.",
  379. options.LogFile);
  380. }
  381. if(options.DebugLogFile) {
  382. if (add_file_log(LOG_DEBUG, options.DebugLogFile) != 0)
  383. log_fn(LOG_WARN, "Cannot write to DebugLogFile '%s': %s.", options.DebugLogFile, strerror(errno));
  384. log_fn(LOG_DEBUG, "Successfully opened DebugLogFile '%s'.", options.DebugLogFile);
  385. }
  386. connection_bucket_init();
  387. stats_prev_global_read_bucket = global_read_bucket;
  388. if(options.RunAsDaemon) {
  389. /* XXXX Can we delay this any more? */
  390. finish_daemon();
  391. }
  392. /* write our pid to the pid file, if we do not have write permissions we will log a warning */
  393. if(options.PidFile)
  394. write_pidfile(options.PidFile);
  395. return 0;
  396. }
  397. static int do_hup(void) {
  398. char keydir[512];
  399. log_fn(LOG_WARN,"Received sighup. Reloading config.");
  400. has_completed_circuit=0;
  401. /* first, reload config variables, in case they've changed */
  402. /* no need to provide argc/v, they've been cached inside init_from_config */
  403. if (init_from_config(0, NULL) < 0) {
  404. exit(1);
  405. }
  406. if(retry_all_connections() < 0) {
  407. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  408. return -1;
  409. }
  410. if(options.DirPort) {
  411. /* reload the approved-routers file */
  412. sprintf(keydir,"%s/approved-routers", options.DataDirectory);
  413. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  414. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  415. log_fn(LOG_WARN, "Error reloading fingerprints. Continuing with old list.");
  416. }
  417. } else {
  418. /* fetch a new directory */
  419. directory_initiate_command(router_pick_directory_server(), DIR_CONN_STATE_CONNECTING_FETCH);
  420. }
  421. if(options.ORPort) {
  422. router_rebuild_descriptor();
  423. sprintf(keydir,"%s/router.desc", options.DataDirectory);
  424. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  425. if (write_str_to_file(keydir, router_get_my_descriptor())) {
  426. return -1;
  427. }
  428. }
  429. return 0;
  430. }
  431. static int do_main_loop(void) {
  432. int i;
  433. int timeout;
  434. int poll_result;
  435. /* load the routers file */
  436. if(options.RouterFile &&
  437. router_set_routerlist_from_file(options.RouterFile) < 0) {
  438. log_fn(LOG_ERR,"Error loading router list.");
  439. return -1;
  440. }
  441. /* Initialize the history structures. */
  442. rep_hist_init();
  443. /* load the private keys, if we're supposed to have them, and set up the
  444. * TLS context. */
  445. if (init_keys() < 0) {
  446. log_fn(LOG_ERR,"Error initializing keys; exiting");
  447. return -1;
  448. }
  449. if(options.ORPort) {
  450. cpu_init(); /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  451. router_upload_desc_to_dirservers(); /* upload our descriptor to all dirservers */
  452. }
  453. /* start up the necessary connections based on which ports are
  454. * non-zero. This is where we try to connect to all the other ORs,
  455. * and start the listeners.
  456. */
  457. if(retry_all_connections() < 0) {
  458. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  459. return -1;
  460. }
  461. for(;;) {
  462. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  463. if(please_dumpstats) {
  464. /* prefer to log it at INFO, but make sure we always see it */
  465. dumpstats(options.loglevel>LOG_INFO ? options.loglevel : LOG_INFO);
  466. please_dumpstats = 0;
  467. }
  468. if(please_reset) {
  469. do_hup();
  470. please_reset = 0;
  471. }
  472. if(please_reap_children) {
  473. while(waitpid(-1,NULL,WNOHANG)) ; /* keep reaping until no more zombies */
  474. please_reap_children = 0;
  475. }
  476. #endif /* signal stuff */
  477. timeout = prepare_for_poll();
  478. /* poll until we have an event, or the second ends */
  479. poll_result = tor_poll(poll_array, nfds, timeout);
  480. /* let catch() handle things like ^c, and otherwise don't worry about it */
  481. if(poll_result < 0) {
  482. if(errno != EINTR) { /* let the program survive things like ^z */
  483. log_fn(LOG_ERR,"poll failed: %s",strerror(errno));
  484. return -1;
  485. } else {
  486. log_fn(LOG_DEBUG,"poll interrupted.");
  487. }
  488. }
  489. /* do all the reads and errors first, so we can detect closed sockets */
  490. for(i=0;i<nfds;i++)
  491. conn_read(i); /* this also marks broken connections */
  492. /* then do the writes */
  493. for(i=0;i<nfds;i++)
  494. conn_write(i);
  495. /* any of the conns need to be closed now? */
  496. for(i=0;i<nfds;i++)
  497. conn_close_if_marked(i);
  498. /* refilling buckets and sending cells happens at the beginning of the
  499. * next iteration of the loop, inside prepare_for_poll()
  500. */
  501. }
  502. }
  503. static void catch(int the_signal) {
  504. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  505. switch(the_signal) {
  506. // case SIGABRT:
  507. case SIGTERM:
  508. case SIGINT:
  509. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  510. /* we don't care if there was an error when we unlink, nothing
  511. we could do about it anyways */
  512. if(options.PidFile)
  513. unlink(options.PidFile);
  514. exit(0);
  515. case SIGPIPE:
  516. log(LOG_WARN,"Bug: caught sigpipe. Ignoring.");
  517. break;
  518. case SIGHUP:
  519. please_reset = 1;
  520. break;
  521. case SIGUSR1:
  522. please_dumpstats = 1;
  523. break;
  524. case SIGCHLD:
  525. please_reap_children = 1;
  526. break;
  527. default:
  528. log(LOG_WARN,"Caught signal %d that we can't handle??", the_signal);
  529. }
  530. #endif /* signal stuff */
  531. }
  532. static void dumpstats(int severity) {
  533. int i;
  534. connection_t *conn;
  535. time_t now = time(NULL);
  536. log(severity, "Dumping stats:");
  537. for(i=0;i<nfds;i++) {
  538. conn = connection_array[i];
  539. log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %ld secs ago",
  540. i, conn->s, conn->type, CONN_TYPE_TO_STRING(conn->type),
  541. conn->state, conn_state_to_string[conn->type][conn->state], now - conn->timestamp_created);
  542. if(!connection_is_listener(conn)) {
  543. log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
  544. log(severity,"Conn %d: %d bytes waiting on inbuf (last read %ld secs ago)",i,
  545. (int)buf_datalen(conn->inbuf),
  546. now - conn->timestamp_lastread);
  547. log(severity,"Conn %d: %d bytes waiting on outbuf (last written %ld secs ago)",i,
  548. (int)buf_datalen(conn->outbuf), now - conn->timestamp_lastwritten);
  549. }
  550. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
  551. }
  552. log(severity,
  553. "Cells processed: %10lu padding\n"
  554. " %10lu create\n"
  555. " %10lu created\n"
  556. " %10lu relay\n"
  557. " (%10lu relayed)\n"
  558. " (%10lu delivered)\n"
  559. " %10lu destroy",
  560. stats_n_padding_cells_processed,
  561. stats_n_create_cells_processed,
  562. stats_n_created_cells_processed,
  563. stats_n_relay_cells_processed,
  564. stats_n_relay_cells_relayed,
  565. stats_n_relay_cells_delivered,
  566. stats_n_destroy_cells_processed);
  567. if (stats_n_data_cells_packaged)
  568. log(severity,"Average packaged cell fullness: %2.3f%%",
  569. 100*(((double)stats_n_data_bytes_packaged) /
  570. (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  571. if (stats_n_data_cells_received)
  572. log(severity,"Average delivered cell fullness: %2.3f%%",
  573. 100*(((double)stats_n_data_bytes_received) /
  574. (stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  575. if (stats_n_seconds_reading)
  576. log(severity,"Average bandwidth used: %d bytes/sec",
  577. (int) (stats_n_bytes_read/stats_n_seconds_reading));
  578. rep_hist_dump_stats(now,severity);
  579. }
  580. int network_init(void)
  581. {
  582. #ifdef MS_WINDOWS
  583. /* This silly exercise is necessary before windows will allow gethostbyname to work.
  584. */
  585. WSADATA WSAData;
  586. int r;
  587. r = WSAStartup(0x101,&WSAData);
  588. if (r) {
  589. log_fn(LOG_WARN,"Error initializing windows network layer: code was %d",r);
  590. return -1;
  591. }
  592. /* XXXX We should call WSACleanup on exit, I think. */
  593. #endif
  594. return 0;
  595. }
  596. void exit_function(void)
  597. {
  598. #ifdef MS_WINDOWS
  599. WSACleanup();
  600. #endif
  601. }
  602. int tor_main(int argc, char *argv[]) {
  603. /* give it somewhere to log to initially */
  604. add_stream_log(LOG_INFO, "<stdout>", stdout);
  605. log_fn(LOG_WARN,"Tor v%s. This is experimental software. Do not use it if you need anonymity.",VERSION);
  606. if (network_init()<0) {
  607. log_fn(LOG_ERR,"Error initializing network; exiting.");
  608. return 1;
  609. }
  610. atexit(exit_function);
  611. if (init_from_config(argc,argv) < 0)
  612. return -1;
  613. #ifndef MS_WINDOWS
  614. if(geteuid()==0)
  615. log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
  616. #endif
  617. if(options.ORPort) { /* only spawn dns handlers if we're a router */
  618. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  619. }
  620. if(options.SocksPort) {
  621. client_dns_init(); /* init the client dns cache */
  622. }
  623. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  624. {
  625. struct sigaction action;
  626. action.sa_flags = 0;
  627. sigemptyset(&action.sa_mask);
  628. action.sa_handler = catch;
  629. sigaction(SIGINT, &action, NULL);
  630. sigaction(SIGTERM, &action, NULL);
  631. sigaction(SIGPIPE, &action, NULL);
  632. sigaction(SIGUSR1, &action, NULL);
  633. sigaction(SIGHUP, &action, NULL); /* to reload config, retry conns, etc */
  634. sigaction(SIGCHLD, &action, NULL); /* handle dns/cpu workers that exit */
  635. }
  636. #endif /* signal stuff */
  637. crypto_global_init();
  638. crypto_seed_rng();
  639. do_main_loop();
  640. crypto_global_cleanup();
  641. return -1;
  642. }
  643. /*
  644. Local Variables:
  645. mode:c
  646. indent-tabs-mode:nil
  647. c-basic-offset:2
  648. End:
  649. */