main.c 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * \file main.c
  6. * \brief Tor main loop and startup functions.
  7. **/
  8. #include "or.h"
  9. /********* PROTOTYPES **********/
  10. static void dumpstats(int severity); /* log stats */
  11. static int init_from_config(int argc, char **argv);
  12. /********* START VARIABLES **********/
  13. /* declared in connection.c */
  14. extern char *conn_state_to_string[][_CONN_TYPE_MAX+1];
  15. or_options_t options; /**< Command-line and config-file options. */
  16. int global_read_bucket; /**< Max number of bytes I can read this second. */
  17. int global_write_bucket; /**< Max number of bytes I can write this second. */
  18. /** What was the read bucket before the last call to prepare_for_pool?
  19. * (used to determine how many bytes we've read). */
  20. static int stats_prev_global_read_bucket;
  21. /** What was the write bucket before the last call to prepare_for_pool?
  22. * (used to determine how many bytes we've written). */
  23. static int stats_prev_global_write_bucket;
  24. /** How many bytes have we read/written since we started the process? */
  25. static uint64_t stats_n_bytes_read = 0;
  26. static uint64_t stats_n_bytes_written = 0;
  27. /** How many seconds have we been running? */
  28. long stats_n_seconds_uptime = 0;
  29. /** Array of all open connections; each element corresponds to the element of
  30. * poll_array in the same position. The first nfds elements are valid. */
  31. static connection_t *connection_array[MAXCONNECTIONS] =
  32. { NULL };
  33. /** Array of pollfd objects for calls to poll(). */
  34. static struct pollfd poll_array[MAXCONNECTIONS];
  35. static int nfds=0; /**< Number of connections currently active. */
  36. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  37. static int please_dumpstats=0; /**< Whether we should dump stats during the loop. */
  38. static int please_reset=0; /**< Whether we just got a sighup. */
  39. static int please_reap_children=0; /**< Whether we should waitpid for exited children. */
  40. static int please_sigpipe=0; /**< Whether we've caught a sigpipe lately. */
  41. static int please_shutdown=0; /**< Whether we should shut down Tor. */
  42. #endif /* signal stuff */
  43. /** We should exit if shutting_down != 0 and now <= shutting_down.
  44. * If it's non-zero, don't accept any new circuits or connections.
  45. * This gets assigned when we receive a sig_int, and if we receive a
  46. * second one we exit immediately. */
  47. int shutting_down=0;
  48. #define SHUTDOWN_WAIT_LENGTH 30 /* seconds */
  49. /** We set this to 1 when we've fetched a dir, to know whether to complain
  50. * yet about unrecognized nicknames in entrynodes, exitnodes, etc.
  51. * Also, we don't try building circuits unless this is 1. */
  52. int has_fetched_directory=0;
  53. /** We set this to 1 when we've opened a circuit, so we can print a log
  54. * entry to inform the user that Tor is working. */
  55. int has_completed_circuit=0;
  56. #ifdef MS_WINDOWS_SERVICE
  57. SERVICE_STATUS service_status;
  58. SERVICE_STATUS_HANDLE hStatus;
  59. #endif
  60. /********* END VARIABLES ************/
  61. /****************************************************************************
  62. *
  63. * This section contains accessors and other methods on the connection_array
  64. * and poll_array variables (which are global within this file and unavailable
  65. * outside it).
  66. *
  67. ****************************************************************************/
  68. /** Add <b>conn</b> to the array of connections that we can poll on. The
  69. * connection's socket must be set; the connection starts out
  70. * non-reading and non-writing.
  71. */
  72. int connection_add(connection_t *conn) {
  73. tor_assert(conn);
  74. tor_assert(conn->s >= 0);
  75. if(nfds >= options.MaxConn-1) {
  76. log_fn(LOG_WARN,"failing because nfds is too high.");
  77. return -1;
  78. }
  79. tor_assert(conn->poll_index == -1); /* can only connection_add once */
  80. conn->poll_index = nfds;
  81. connection_array[nfds] = conn;
  82. poll_array[nfds].fd = conn->s;
  83. /* zero these out here, because otherwise we'll inherit values from the previously freed one */
  84. poll_array[nfds].events = 0;
  85. poll_array[nfds].revents = 0;
  86. nfds++;
  87. log_fn(LOG_INFO,"new conn type %s, socket %d, nfds %d.",
  88. CONN_TYPE_TO_STRING(conn->type), conn->s, nfds);
  89. return 0;
  90. }
  91. /** Remove the connection from the global list, and remove the
  92. * corresponding poll entry. Calling this function will shift the last
  93. * connection (if any) into the position occupied by conn.
  94. */
  95. int connection_remove(connection_t *conn) {
  96. int current_index;
  97. tor_assert(conn);
  98. tor_assert(nfds>0);
  99. log_fn(LOG_INFO,"removing socket %d (type %s), nfds now %d",
  100. conn->s, CONN_TYPE_TO_STRING(conn->type), nfds-1);
  101. tor_assert(conn->poll_index >= 0);
  102. current_index = conn->poll_index;
  103. if(current_index == nfds-1) { /* this is the end */
  104. nfds--;
  105. return 0;
  106. }
  107. /* replace this one with the one at the end */
  108. nfds--;
  109. poll_array[current_index].fd = poll_array[nfds].fd;
  110. poll_array[current_index].events = poll_array[nfds].events;
  111. poll_array[current_index].revents = poll_array[nfds].revents;
  112. connection_array[current_index] = connection_array[nfds];
  113. connection_array[current_index]->poll_index = current_index;
  114. return 0;
  115. }
  116. /** Return true iff conn is in the current poll array. */
  117. int connection_in_array(connection_t *conn) {
  118. int i;
  119. for (i=0; i<nfds; ++i) {
  120. if (conn==connection_array[i])
  121. return 1;
  122. }
  123. return 0;
  124. }
  125. /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
  126. * to the length of the array. <b>*array</b> and <b>*n</b> must not
  127. * be modified.
  128. */
  129. void get_connection_array(connection_t ***array, int *n) {
  130. *array = connection_array;
  131. *n = nfds;
  132. }
  133. /** Set the event mask on <b>conn</b> to <b>events</b>. (The form of
  134. * the event mask is as for poll().)
  135. */
  136. void connection_watch_events(connection_t *conn, short events) {
  137. tor_assert(conn);
  138. tor_assert(conn->poll_index >= 0);
  139. tor_assert(conn->poll_index < nfds);
  140. poll_array[conn->poll_index].events = events;
  141. }
  142. /** Return true iff <b>conn</b> is listening for read events. */
  143. int connection_is_reading(connection_t *conn) {
  144. tor_assert(conn);
  145. tor_assert(conn->poll_index >= 0);
  146. return poll_array[conn->poll_index].events & POLLIN;
  147. }
  148. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  149. void connection_stop_reading(connection_t *conn) {
  150. tor_assert(conn);
  151. tor_assert(conn->poll_index >= 0);
  152. tor_assert(conn->poll_index < nfds);
  153. log(LOG_DEBUG,"connection_stop_reading() called.");
  154. poll_array[conn->poll_index].events &= ~POLLIN;
  155. }
  156. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  157. void connection_start_reading(connection_t *conn) {
  158. tor_assert(conn);
  159. tor_assert(conn->poll_index >= 0);
  160. tor_assert(conn->poll_index < nfds);
  161. poll_array[conn->poll_index].events |= POLLIN;
  162. }
  163. /** Return true iff <b>conn</b> is listening for write events. */
  164. int connection_is_writing(connection_t *conn) {
  165. return poll_array[conn->poll_index].events & POLLOUT;
  166. }
  167. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  168. void connection_stop_writing(connection_t *conn) {
  169. tor_assert(conn);
  170. tor_assert(conn->poll_index >= 0);
  171. tor_assert(conn->poll_index < nfds);
  172. poll_array[conn->poll_index].events &= ~POLLOUT;
  173. }
  174. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  175. void connection_start_writing(connection_t *conn) {
  176. tor_assert(conn);
  177. tor_assert(conn->poll_index >= 0);
  178. tor_assert(conn->poll_index < nfds);
  179. poll_array[conn->poll_index].events |= POLLOUT;
  180. }
  181. /** Called when the connection at connection_array[i] has a read event,
  182. * or it has pending tls data waiting to be read: checks for validity,
  183. * catches numerous errors, and dispatches to connection_handle_read.
  184. */
  185. static void conn_read(int i) {
  186. connection_t *conn = connection_array[i];
  187. if (conn->marked_for_close)
  188. return;
  189. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
  190. * discussion of POLLIN vs POLLHUP */
  191. if(!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
  192. if(!connection_is_reading(conn) ||
  193. !connection_has_pending_tls_data(conn))
  194. return; /* this conn should not read */
  195. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  196. assert_connection_ok(conn, time(NULL));
  197. assert_all_pending_dns_resolves_ok();
  198. if(
  199. /* XXX does POLLHUP also mean it's definitely broken? */
  200. #ifdef MS_WINDOWS
  201. (poll_array[i].revents & POLLERR) ||
  202. #endif
  203. connection_handle_read(conn) < 0) {
  204. if (!conn->marked_for_close) {
  205. /* this connection is broken. remove it */
  206. log_fn(LOG_WARN,"Unhandled error on read for %s connection (fd %d); removing",
  207. CONN_TYPE_TO_STRING(conn->type), conn->s);
  208. connection_mark_for_close(conn);
  209. }
  210. }
  211. assert_connection_ok(conn, time(NULL));
  212. assert_all_pending_dns_resolves_ok();
  213. }
  214. /** Called when the connection at connection_array[i] has a write event:
  215. * checks for validity, catches numerous errors, and dispatches to
  216. * connection_handle_write.
  217. */
  218. static void conn_write(int i) {
  219. connection_t *conn;
  220. if(!(poll_array[i].revents & POLLOUT))
  221. return; /* this conn doesn't want to write */
  222. conn = connection_array[i];
  223. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  224. if (conn->marked_for_close)
  225. return;
  226. assert_connection_ok(conn, time(NULL));
  227. assert_all_pending_dns_resolves_ok();
  228. if (connection_handle_write(conn) < 0) {
  229. if (!conn->marked_for_close) {
  230. /* this connection is broken. remove it. */
  231. log_fn(LOG_WARN,"Unhandled error on write for %s connection (fd %d); removing",
  232. CONN_TYPE_TO_STRING(conn->type), conn->s);
  233. conn->has_sent_end = 1; /* otherwise we cry wolf about duplicate close */
  234. /* XXX do we need a close-immediate here, so we don't try to flush? */
  235. connection_mark_for_close(conn);
  236. }
  237. }
  238. assert_connection_ok(conn, time(NULL));
  239. assert_all_pending_dns_resolves_ok();
  240. }
  241. /** If the connection at connection_array[i] is marked for close, then:
  242. * - If it has data that it wants to flush, try to flush it.
  243. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  244. * true, then leave the connection open and return.
  245. * - Otherwise, remove the connection from connection_array and from
  246. * all other lists, close it, and free it.
  247. * If we remove the connection, then call conn_closed_if_marked at the new
  248. * connection at position i.
  249. */
  250. static void conn_close_if_marked(int i) {
  251. connection_t *conn;
  252. int retval;
  253. conn = connection_array[i];
  254. assert_connection_ok(conn, time(NULL));
  255. assert_all_pending_dns_resolves_ok();
  256. if(!conn->marked_for_close)
  257. return; /* nothing to see here, move along */
  258. log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
  259. if(conn->s >= 0 && connection_wants_to_flush(conn)) {
  260. /* -1 means it's an incomplete edge connection, or that the socket
  261. * has already been closed as unflushable. */
  262. if(!conn->hold_open_until_flushed)
  263. log_fn(LOG_INFO,
  264. "Conn (addr %s, fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
  265. "(Marked at %s:%d)",
  266. conn->address, conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  267. (int)conn->outbuf_flushlen, conn->marked_for_close_file, conn->marked_for_close);
  268. if(connection_speaks_cells(conn)) {
  269. if(conn->state == OR_CONN_STATE_OPEN) {
  270. retval = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  271. } else
  272. retval = -1; /* never flush non-open broken tls connections */
  273. } else {
  274. retval = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  275. }
  276. if(retval >= 0 &&
  277. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  278. log_fn(LOG_INFO,"Holding conn (fd %d) open for more flushing.",conn->s);
  279. /* XXX should we reset timestamp_lastwritten here? */
  280. return;
  281. }
  282. if(connection_wants_to_flush(conn)) {
  283. log_fn(LOG_WARN,"Conn (addr %s, fd %d, type %s, state %d) still wants to flush. Losing %d bytes! (Marked at %s:%d)",
  284. conn->address, conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  285. (int)buf_datalen(conn->outbuf), conn->marked_for_close_file,
  286. conn->marked_for_close);
  287. }
  288. }
  289. /* if it's an edge conn, remove it from the list
  290. * of conn's on this circuit. If it's not on an edge,
  291. * flush and send destroys for all circuits on this conn
  292. */
  293. circuit_about_to_close_connection(conn);
  294. connection_about_to_close_connection(conn);
  295. connection_remove(conn);
  296. if(conn->type == CONN_TYPE_EXIT) {
  297. assert_connection_edge_not_dns_pending(conn);
  298. }
  299. connection_free(conn);
  300. if(i<nfds) { /* we just replaced the one at i with a new one.
  301. process it too. */
  302. conn_close_if_marked(i);
  303. }
  304. }
  305. /** This function is called whenever we successfully pull down a directory */
  306. void directory_has_arrived(void) {
  307. log_fn(LOG_INFO, "A directory has arrived.");
  308. has_fetched_directory=1;
  309. if(server_mode()) { /* connect to the appropriate routers */
  310. router_retry_connections();
  311. }
  312. }
  313. /** Perform regular maintenance tasks for a single connection. This
  314. * function gets run once per second per connection by run_housekeeping.
  315. */
  316. static void run_connection_housekeeping(int i, time_t now) {
  317. cell_t cell;
  318. connection_t *conn = connection_array[i];
  319. /* Expire any directory connections that haven't sent anything for 5 min */
  320. if(conn->type == CONN_TYPE_DIR &&
  321. !conn->marked_for_close &&
  322. conn->timestamp_lastwritten + 5*60 < now) {
  323. log_fn(LOG_INFO,"Expiring wedged directory conn (fd %d, purpose %d)", conn->s, conn->purpose);
  324. connection_mark_for_close(conn);
  325. return;
  326. }
  327. /* If we haven't written to an OR connection for a while, then either nuke
  328. the connection or send a keepalive, depending. */
  329. if(connection_speaks_cells(conn) &&
  330. now >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
  331. routerinfo_t *router = router_get_by_digest(conn->identity_digest);
  332. if((!connection_state_is_open(conn)) ||
  333. (!clique_mode() && !circuit_get_by_conn(conn) &&
  334. (!router || !server_mode() || !router_is_clique_mode(router)))) {
  335. /* our handshake has expired;
  336. * or we have no circuits and we're both either OPs or normal ORs,
  337. * then kill it. */
  338. log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
  339. i,conn->address, conn->port);
  340. /* flush anything waiting, e.g. a destroy for a just-expired circ */
  341. connection_mark_for_close(conn);
  342. conn->hold_open_until_flushed = 1;
  343. } else {
  344. /* either in clique mode, or we've got a circuit. send a padding cell. */
  345. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  346. conn->address, conn->port);
  347. memset(&cell,0,sizeof(cell_t));
  348. cell.command = CELL_PADDING;
  349. connection_or_write_cell_to_buf(&cell, conn);
  350. }
  351. }
  352. }
  353. #define MIN_BW_TO_PUBLISH_DESC 5000 /* 5000 bytes/s sustained */
  354. #define MIN_UPTIME_TO_PUBLISH_DESC (30*60) /* half an hour */
  355. /** Decide if we're a publishable server or just a client. We are a server if:
  356. * - We have the AuthoritativeDirectory option set.
  357. * or
  358. * - We don't have the ClientOnly option set; and
  359. * - We have ORPort set; and
  360. * - We have been up for at least MIN_UPTIME_TO_PUBLISH_DESC seconds; and
  361. * - We have processed some suitable minimum bandwidth recently; and
  362. * - We believe we are reachable from the outside.
  363. */
  364. static int decide_if_publishable_server(time_t now) {
  365. int bw;
  366. bw = rep_hist_bandwidth_assess();
  367. router_set_bandwidth_capacity(bw);
  368. if(options.ClientOnly)
  369. return 0;
  370. if(!options.ORPort)
  371. return 0;
  372. /* XXX008 for now, you're only a server if you're a server */
  373. return server_mode();
  374. /* here, determine if we're reachable */
  375. if(0) { /* we've recently failed to reach our IP/ORPort from the outside */
  376. return 0;
  377. }
  378. if(bw < MIN_BW_TO_PUBLISH_DESC)
  379. return 0;
  380. if(options.AuthoritativeDir)
  381. return 1;
  382. if(stats_n_seconds_uptime < MIN_UPTIME_TO_PUBLISH_DESC)
  383. return 0;
  384. return 1;
  385. }
  386. /** Return true iff we believe ourselves to be an authoritative
  387. * directory server.
  388. */
  389. int authdir_mode(void) {
  390. return (options.AuthoritativeDir != 0);
  391. }
  392. /** Return true iff we try to stay connected to all ORs at once.
  393. */
  394. int clique_mode(void) {
  395. return authdir_mode();
  396. }
  397. /** Return true iff we are trying to be a server.
  398. */
  399. int server_mode(void) {
  400. return (options.ORPort != 0 || options.ORBindAddress);
  401. }
  402. /** Remember if we've advertised ourselves to the dirservers. */
  403. static int server_is_advertised=0;
  404. /** Return true iff we have published our descriptor lately.
  405. */
  406. int advertised_server_mode(void) {
  407. return server_is_advertised;
  408. }
  409. /** Return true iff we are trying to be a socks proxy. */
  410. int proxy_mode(void) {
  411. return (options.SocksPort != 0 || options.SocksBindAddress);
  412. }
  413. /** Perform regular maintenance tasks. This function gets run once per
  414. * second by prepare_for_poll.
  415. */
  416. static void run_scheduled_events(time_t now) {
  417. static long time_to_fetch_directory = 0;
  418. static time_t last_uploaded_services = 0;
  419. static time_t last_rotated_certificate = 0;
  420. static time_t time_to_check_listeners = 0;
  421. int i;
  422. /** 0. See if we've been asked to shut down and our timeout has
  423. * expired. If so, exit now.
  424. */
  425. if(shutting_down && shutting_down <= now) {
  426. log(LOG_NOTICE,"Clean shutdown finished. Exiting.");
  427. tor_cleanup();
  428. exit(0);
  429. }
  430. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  431. * shut down and restart all cpuworkers, and update the directory if
  432. * necessary.
  433. */
  434. if (server_mode() && get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  435. log_fn(LOG_INFO,"Rotating onion key.");
  436. rotate_onion_key();
  437. cpuworkers_rotate();
  438. if (router_rebuild_descriptor()<0) {
  439. log_fn(LOG_WARN, "Couldn't rebuild router descriptor");
  440. }
  441. if(advertised_server_mode())
  442. router_upload_dir_desc_to_dirservers();
  443. }
  444. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  445. if (!last_rotated_certificate)
  446. last_rotated_certificate = now;
  447. if (last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
  448. log_fn(LOG_INFO,"Rotating tls context.");
  449. if (tor_tls_context_new(get_identity_key(), 1, options.Nickname,
  450. MAX_SSL_KEY_LIFETIME) < 0) {
  451. log_fn(LOG_WARN, "Error reinitializing TLS context");
  452. }
  453. last_rotated_certificate = now;
  454. /* XXXX We should rotate TLS connections as well; this code doesn't change
  455. * XXXX them at all. */
  456. }
  457. /** 2. Every DirFetchPostPeriod seconds, we get a new directory and upload
  458. * our descriptor (if we've passed our internal checks). */
  459. if(time_to_fetch_directory < now) {
  460. if(decide_if_publishable_server(now)) {
  461. server_is_advertised = 1;
  462. router_rebuild_descriptor();
  463. router_upload_dir_desc_to_dirservers();
  464. } else {
  465. server_is_advertised = 0;
  466. }
  467. /* purge obsolete entries */
  468. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  469. if(authdir_mode()) {
  470. /* We're a directory; dump any old descriptors. */
  471. dirserv_remove_old_servers(ROUTER_MAX_AGE);
  472. }
  473. if(server_mode()) {
  474. /* dirservers try to reconnect, in case connections have failed;
  475. * and normal servers try to reconnect to dirservers */
  476. router_retry_connections();
  477. }
  478. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  479. /* Force an upload of our rend descriptors every DirFetchPostPeriod seconds. */
  480. rend_services_upload(1);
  481. last_uploaded_services = now;
  482. rend_cache_clean(); /* should this go elsewhere? */
  483. time_to_fetch_directory = now + options.DirFetchPostPeriod;
  484. }
  485. /** 3a. Every second, we examine pending circuits and prune the
  486. * ones which have been pending for more than a few seconds.
  487. * We do this before step 3, so it can try building more if
  488. * it's not comfortable with the number of available circuits.
  489. */
  490. circuit_expire_building(now);
  491. /** 3b. Also look at pending streams and prune the ones that 'began'
  492. * a long time ago but haven't gotten a 'connected' yet.
  493. * Do this before step 3, so we can put them back into pending
  494. * state to be picked up by the new circuit.
  495. */
  496. connection_ap_expire_beginning();
  497. /** 3c. And expire connections that we've held open for too long.
  498. */
  499. connection_expire_held_open();
  500. /** 3d. And every 60 secionds, we relaunch listeners if any died. */
  501. if (time_to_check_listeners < now) {
  502. retry_all_listeners(0); /* 0 means "only if some died." */
  503. time_to_check_listeners = now+60;
  504. }
  505. /** 4. Every second, we try a new circuit if there are no valid
  506. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  507. * that became dirty more than NewCircuitPeriod seconds ago,
  508. * and we make a new circ if there are no clean circuits.
  509. */
  510. if(has_fetched_directory)
  511. circuit_build_needed_circs(now);
  512. /** 5. We do housekeeping for each connection... */
  513. for(i=0;i<nfds;i++) {
  514. run_connection_housekeeping(i, now);
  515. }
  516. /** 6. And remove any marked circuits... */
  517. circuit_close_all_marked();
  518. /** 7. And upload service descriptors for any services whose intro points
  519. * have changed in the last second. */
  520. if (last_uploaded_services < now-5) {
  521. rend_services_upload(0);
  522. last_uploaded_services = now;
  523. }
  524. /** 8. and blow away any connections that need to die. have to do this now,
  525. * because if we marked a conn for close and left its socket -1, then
  526. * we'll pass it to poll/select and bad things will happen.
  527. */
  528. for(i=0;i<nfds;i++)
  529. conn_close_if_marked(i);
  530. }
  531. /** Called every time we're about to call tor_poll. Increments statistics,
  532. * and adjusts token buckets. Returns the number of milliseconds to use for
  533. * the poll() timeout.
  534. */
  535. static int prepare_for_poll(void) {
  536. static long current_second = 0; /* from previous calls to gettimeofday */
  537. connection_t *conn;
  538. struct timeval now;
  539. int i;
  540. tor_gettimeofday(&now);
  541. /* Check how much bandwidth we've consumed, and increment the token
  542. * buckets. */
  543. stats_n_bytes_read += stats_prev_global_read_bucket - global_read_bucket;
  544. stats_n_bytes_written += stats_prev_global_write_bucket - global_write_bucket;
  545. connection_bucket_refill(&now);
  546. stats_prev_global_read_bucket = global_read_bucket;
  547. stats_prev_global_write_bucket = global_write_bucket;
  548. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  549. if(current_second)
  550. stats_n_seconds_uptime += (now.tv_sec - current_second);
  551. assert_all_pending_dns_resolves_ok();
  552. run_scheduled_events(now.tv_sec);
  553. assert_all_pending_dns_resolves_ok();
  554. current_second = now.tv_sec; /* remember which second it is, for next time */
  555. }
  556. for(i=0;i<nfds;i++) {
  557. conn = connection_array[i];
  558. if(connection_has_pending_tls_data(conn) &&
  559. connection_is_reading(conn)) {
  560. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  561. return 0; /* has pending bytes to read; don't let poll wait. */
  562. }
  563. }
  564. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  565. }
  566. /** Configure the Tor process from the command line arguments and from the
  567. * configuration file.
  568. */
  569. static int init_from_config(int argc, char **argv) {
  570. /* read the configuration file. */
  571. if(getconfig(argc,argv,&options)) {
  572. log_fn(LOG_ERR,"Reading config failed--see warnings above. For usage, try -h.");
  573. return -1;
  574. }
  575. /* Setuid/setgid as appropriate */
  576. if(options.User || options.Group) {
  577. if(switch_id(options.User, options.Group) != 0) {
  578. return -1;
  579. }
  580. }
  581. /* Ensure data directory is private; create if possible. */
  582. if (get_data_directory(&options) &&
  583. check_private_dir(get_data_directory(&options), 1) != 0) {
  584. log_fn(LOG_ERR, "Couldn't access/create private data directory %s",
  585. get_data_directory(&options));
  586. return -1;
  587. }
  588. /* Configure the log(s) */
  589. if (config_init_logs(&options)<0)
  590. return -1;
  591. /* Close the temporary log we used while starting up, if it isn't already
  592. * gone. */
  593. close_temp_logs();
  594. /* Start backgrounding the process, if requested. */
  595. if (options.RunAsDaemon) {
  596. start_daemon(get_data_directory(&options));
  597. }
  598. /* Set up our buckets */
  599. connection_bucket_init();
  600. stats_prev_global_read_bucket = global_read_bucket;
  601. stats_prev_global_write_bucket = global_write_bucket;
  602. /* Finish backgrounding the process */
  603. if(options.RunAsDaemon) {
  604. /* XXXX Can we delay this any more? */
  605. finish_daemon();
  606. }
  607. /* Write our pid to the pid file. If we do not have write permissions we
  608. * will log a warning */
  609. if(options.PidFile)
  610. write_pidfile(options.PidFile);
  611. return 0;
  612. }
  613. /** Called when we get a SIGHUP: reload configuration files and keys,
  614. * retry all connections, re-upload all descriptors, and so on. */
  615. static int do_hup(void) {
  616. char keydir[512];
  617. log_fn(LOG_NOTICE,"Received sighup. Reloading config.");
  618. has_completed_circuit=0;
  619. mark_logs_temp(); /* Close current logs once new logs are open. */
  620. /* first, reload config variables, in case they've changed */
  621. /* no need to provide argc/v, they've been cached inside init_from_config */
  622. if (init_from_config(0, NULL) < 0) {
  623. return -1;
  624. }
  625. /* reload keys as needed for rendezvous services. */
  626. if (rend_service_load_keys()<0) {
  627. log_fn(LOG_ERR,"Error reloading rendezvous service keys");
  628. return -1;
  629. }
  630. if(retry_all_listeners(1) < 0) {
  631. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  632. return -1;
  633. }
  634. if(authdir_mode()) {
  635. /* reload the approved-routers file */
  636. snprintf(keydir,sizeof(keydir),"%s/approved-routers", get_data_directory(&options));
  637. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  638. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  639. log_fn(LOG_WARN, "Error reloading fingerprints. Continuing with old list.");
  640. }
  641. }
  642. /* Fetch a new directory. Even authdirservers do this. */
  643. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  644. if(server_mode()) {
  645. /* Restart cpuworker and dnsworker processes, so they get up-to-date
  646. * configuration options. */
  647. cpuworkers_rotate();
  648. dnsworkers_rotate();
  649. /* Rebuild fresh descriptor as needed. */
  650. router_rebuild_descriptor();
  651. snprintf(keydir,sizeof(keydir),"%s/router.desc", get_data_directory(&options));
  652. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  653. if (write_str_to_file(keydir, router_get_my_descriptor(), 0)) {
  654. return -1;
  655. }
  656. }
  657. return 0;
  658. }
  659. /** Tor main loop. */
  660. static int do_main_loop(void) {
  661. int i;
  662. int timeout;
  663. int poll_result;
  664. /* Initialize the history structures. */
  665. rep_hist_init();
  666. /* Intialize the service cache. */
  667. rend_cache_init();
  668. /* load the private keys, if we're supposed to have them, and set up the
  669. * TLS context. */
  670. if (init_keys() < 0 || rend_service_load_keys() < 0) {
  671. log_fn(LOG_ERR,"Error initializing keys; exiting");
  672. return -1;
  673. }
  674. /* load the routers file, or assign the defaults. */
  675. if(router_reload_router_list()) {
  676. return -1;
  677. }
  678. if(authdir_mode()) {
  679. /* the directory is already here, run startup things */
  680. router_retry_connections();
  681. }
  682. if(server_mode()) {
  683. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  684. cpu_init();
  685. }
  686. /* start up the necessary listeners based on which ports are non-zero. */
  687. if(retry_all_listeners(1) < 0) {
  688. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  689. return -1;
  690. }
  691. for(;;) {
  692. #ifdef MS_WINDOWS_SERVICE /* Do service stuff only on windows. */
  693. if (service_status.dwCurrentState != SERVICE_RUNNING) {
  694. return 0;
  695. }
  696. #endif
  697. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  698. if(please_shutdown) {
  699. if(!server_mode()) { /* do it now */
  700. log(LOG_NOTICE,"Interrupt: exiting cleanly.");
  701. tor_cleanup();
  702. exit(0);
  703. }
  704. if(shutting_down) { /* we've already been asked. do it now. */
  705. log(LOG_NOTICE,"Second sigint received; exiting now.");
  706. tor_cleanup();
  707. exit(0);
  708. } else {
  709. log(LOG_NOTICE,"Interrupt: will shut down in %d seconds. Interrupt again to exit now.", SHUTDOWN_WAIT_LENGTH);
  710. shutting_down = time(NULL) + SHUTDOWN_WAIT_LENGTH;
  711. }
  712. please_shutdown = 0;
  713. }
  714. if(please_sigpipe) {
  715. log(LOG_NOTICE,"Caught sigpipe. Ignoring.");
  716. please_sigpipe = 0;
  717. }
  718. if(please_dumpstats) {
  719. /* prefer to log it at INFO, but make sure we always see it */
  720. dumpstats(get_min_log_level()>LOG_INFO ? get_min_log_level() : LOG_INFO);
  721. please_dumpstats = 0;
  722. }
  723. if(please_reset) {
  724. if (do_hup() < 0) {
  725. log_fn(LOG_WARN,"Restart failed (config error?). Exiting.");
  726. tor_cleanup();
  727. exit(1);
  728. }
  729. please_reset = 0;
  730. }
  731. if(please_reap_children) {
  732. while(waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more zombies */
  733. please_reap_children = 0;
  734. }
  735. #endif /* signal stuff */
  736. timeout = prepare_for_poll();
  737. /* poll until we have an event, or the second ends */
  738. poll_result = tor_poll(poll_array, nfds, timeout);
  739. /* let catch() handle things like ^c, and otherwise don't worry about it */
  740. if(poll_result < 0) {
  741. /* let the program survive things like ^z */
  742. if(tor_socket_errno(-1) != EINTR) {
  743. log_fn(LOG_ERR,"poll failed: %s [%d]",
  744. tor_socket_strerror(tor_socket_errno(-1)),
  745. tor_socket_errno(-1));
  746. return -1;
  747. } else {
  748. log_fn(LOG_DEBUG,"poll interrupted.");
  749. }
  750. }
  751. /* do all the reads and errors first, so we can detect closed sockets */
  752. for(i=0;i<nfds;i++)
  753. conn_read(i); /* this also marks broken connections */
  754. /* then do the writes */
  755. for(i=0;i<nfds;i++)
  756. conn_write(i);
  757. /* any of the conns need to be closed now? */
  758. for(i=0;i<nfds;i++)
  759. conn_close_if_marked(i);
  760. /* refilling buckets and sending cells happens at the beginning of the
  761. * next iteration of the loop, inside prepare_for_poll()
  762. */
  763. }
  764. }
  765. /** Unix signal handler. */
  766. static void catch(int the_signal) {
  767. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  768. switch(the_signal) {
  769. // case SIGABRT:
  770. case SIGTERM:
  771. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  772. tor_cleanup();
  773. exit(0);
  774. case SIGINT:
  775. please_shutdown = 1;
  776. break;
  777. case SIGPIPE:
  778. /* don't log here, since it's possible you got the sigpipe because
  779. * your log failed! */
  780. please_sigpipe = 1;
  781. break;
  782. case SIGHUP:
  783. please_reset = 1;
  784. break;
  785. case SIGUSR1:
  786. please_dumpstats = 1;
  787. break;
  788. case SIGCHLD:
  789. please_reap_children = 1;
  790. break;
  791. default:
  792. log(LOG_WARN,"Caught signal %d that we can't handle??", the_signal);
  793. tor_cleanup();
  794. exit(1);
  795. }
  796. #endif /* signal stuff */
  797. }
  798. /** Write all statistics to the log, with log level 'severity'. Called
  799. * in response to a SIGUSR1. */
  800. static void dumpstats(int severity) {
  801. int i;
  802. connection_t *conn;
  803. time_t now = time(NULL);
  804. log(severity, "Dumping stats:");
  805. for(i=0;i<nfds;i++) {
  806. conn = connection_array[i];
  807. log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  808. i, conn->s, conn->type, CONN_TYPE_TO_STRING(conn->type),
  809. conn->state, conn_state_to_string[conn->type][conn->state], (int)(now - conn->timestamp_created));
  810. if(!connection_is_listener(conn)) {
  811. log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
  812. log(severity,"Conn %d: %d bytes waiting on inbuf (last read %d secs ago)",i,
  813. (int)buf_datalen(conn->inbuf),
  814. (int)(now - conn->timestamp_lastread));
  815. log(severity,"Conn %d: %d bytes waiting on outbuf (last written %d secs ago)",i,
  816. (int)buf_datalen(conn->outbuf), (int)(now - conn->timestamp_lastwritten));
  817. }
  818. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
  819. }
  820. log(severity,
  821. "Cells processed: %10lu padding\n"
  822. " %10lu create\n"
  823. " %10lu created\n"
  824. " %10lu relay\n"
  825. " (%10lu relayed)\n"
  826. " (%10lu delivered)\n"
  827. " %10lu destroy",
  828. stats_n_padding_cells_processed,
  829. stats_n_create_cells_processed,
  830. stats_n_created_cells_processed,
  831. stats_n_relay_cells_processed,
  832. stats_n_relay_cells_relayed,
  833. stats_n_relay_cells_delivered,
  834. stats_n_destroy_cells_processed);
  835. if (stats_n_data_cells_packaged)
  836. log(severity,"Average packaged cell fullness: %2.3f%%",
  837. 100*(((double)stats_n_data_bytes_packaged) /
  838. (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  839. if (stats_n_data_cells_received)
  840. log(severity,"Average delivered cell fullness: %2.3f%%",
  841. 100*(((double)stats_n_data_bytes_received) /
  842. (stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  843. if (stats_n_seconds_uptime)
  844. log(severity,
  845. #ifdef MS_WINDOWS
  846. "Average bandwidth used: %I64u/%ld = %d bytes/sec",
  847. stats_n_bytes_read,
  848. #else
  849. "Average bandwidth used: %llu/%ld = %d bytes/sec",
  850. (long long unsigned int)stats_n_bytes_read,
  851. #endif
  852. stats_n_seconds_uptime,
  853. (int) (stats_n_bytes_read/stats_n_seconds_uptime));
  854. rep_hist_dump_stats(now,severity);
  855. rend_service_dump_stats(severity);
  856. }
  857. /** Called before we make any calls to network-related functions.
  858. * (Some operating systems require their network libraries to be
  859. * initialized.) */
  860. static int network_init(void)
  861. {
  862. #ifdef MS_WINDOWS
  863. /* This silly exercise is necessary before windows will allow gethostbyname to work.
  864. */
  865. WSADATA WSAData;
  866. int r;
  867. r = WSAStartup(0x101,&WSAData);
  868. if (r) {
  869. log_fn(LOG_WARN,"Error initializing windows network layer: code was %d",r);
  870. return -1;
  871. }
  872. /* XXXX We should call WSACleanup on exit, I think. */
  873. #endif
  874. return 0;
  875. }
  876. /** Called by exit() as we shut down the process.
  877. */
  878. void exit_function(void)
  879. {
  880. /* XXX if we ever daemonize, this gets called immediately */
  881. #ifdef MS_WINDOWS
  882. WSACleanup();
  883. #endif
  884. }
  885. /** Set up the signal handlers for either parent or child. */
  886. void handle_signals(int is_parent)
  887. {
  888. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  889. struct sigaction action;
  890. action.sa_flags = 0;
  891. sigemptyset(&action.sa_mask);
  892. action.sa_handler = is_parent ? catch : SIG_IGN;
  893. sigaction(SIGINT, &action, NULL); /* do a controlled slow shutdown */
  894. sigaction(SIGTERM, &action, NULL); /* to terminate now */
  895. sigaction(SIGPIPE, &action, NULL); /* otherwise sigpipe kills us */
  896. sigaction(SIGUSR1, &action, NULL); /* dump stats */
  897. sigaction(SIGHUP, &action, NULL); /* to reload config, retry conns, etc */
  898. if(is_parent)
  899. sigaction(SIGCHLD, &action, NULL); /* handle dns/cpu workers that exit */
  900. #endif /* signal stuff */
  901. }
  902. /** Main entry point for the Tor command-line client.
  903. */
  904. static int tor_init(int argc, char *argv[]) {
  905. /* give it somewhere to log to initially */
  906. add_temp_log();
  907. log_fn(LOG_NOTICE,"Tor v%s. This is experimental software. Do not use it if you need anonymity.",VERSION);
  908. if (network_init()<0) {
  909. log_fn(LOG_ERR,"Error initializing network; exiting.");
  910. return -1;
  911. }
  912. atexit(exit_function);
  913. if (init_from_config(argc,argv) < 0)
  914. return -1;
  915. #ifndef MS_WINDOWS
  916. if(geteuid()==0)
  917. log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
  918. #endif
  919. if(server_mode()) { /* only spawn dns handlers if we're a router */
  920. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  921. }
  922. if(proxy_mode()) {
  923. client_dns_init(); /* init the client dns cache */
  924. }
  925. handle_signals(1);
  926. crypto_global_init();
  927. crypto_seed_rng();
  928. return 0;
  929. }
  930. /** Do whatever cleanup is necessary before shutting Tor down. */
  931. void tor_cleanup(void) {
  932. /* Remove our pid file. We don't care if there was an error when we
  933. * unlink, nothing we could do about it anyways. */
  934. if(options.PidFile)
  935. unlink(options.PidFile);
  936. crypto_global_cleanup();
  937. }
  938. #ifdef MS_WINDOWS_SERVICE
  939. void nt_service_control(DWORD request)
  940. {
  941. switch (request) {
  942. case SERVICE_CONTROL_STOP:
  943. case SERVICE_CONTROL_SHUTDOWN:
  944. log(LOG_ERR, "Got stop/shutdown request; shutting down cleanly.");
  945. service_status.dwWin32ExitCode = 0;
  946. service_status.dwCurrentState = SERVICE_STOPPED;
  947. return;
  948. }
  949. SetServiceStatus(hStatus, &service_status);
  950. }
  951. void nt_service_body(int argc, char **argv)
  952. {
  953. int err;
  954. FILE *f;
  955. f = fopen("d:\\foo.txt", "w");
  956. fprintf(f, "POINT 1\n");
  957. fclose(f);
  958. service_status.dwServiceType = SERVICE_WIN32;
  959. service_status.dwCurrentState = SERVICE_START_PENDING;
  960. service_status.dwControlsAccepted =
  961. SERVICE_ACCEPT_STOP |
  962. SERVICE_ACCEPT_SHUTDOWN;
  963. service_status.dwWin32ExitCode = 0;
  964. service_status.dwServiceSpecificExitCode = 0;
  965. service_status.dwCheckPoint = 0;
  966. service_status.dwWaitHint = 0;
  967. hStatus = RegisterServiceCtrlHandler("Tor", (LPHANDLER_FUNCTION) nt_service_control);
  968. if (hStatus == 0) {
  969. // failed;
  970. return;
  971. }
  972. err = tor_init(argc, argv); // refactor this part out of tor_main and do_main_loop
  973. if (err) {
  974. // failed.
  975. service_status.dwCurrentState = SERVICE_STOPPED;
  976. service_status.dwWin32ExitCode = -1;
  977. SetServiceStatus(hStatus, &service_status);
  978. return;
  979. }
  980. service_status.dwCurrentState = SERVICE_RUNNING;
  981. SetServiceStatus(hStatus, &service_status);
  982. do_main_loop();
  983. tor_cleanup();
  984. return;
  985. }
  986. void nt_service_main(void)
  987. {
  988. SERVICE_TABLE_ENTRY table[2];
  989. table[0].lpServiceName = "Tor";
  990. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
  991. table[1].lpServiceName = NULL;
  992. table[1].lpServiceProc = NULL;
  993. if (!StartServiceCtrlDispatcher(table))
  994. printf("Error was %d\n",GetLastError());
  995. }
  996. #endif
  997. int tor_main(int argc, char *argv[]) {
  998. #ifdef MS_WINDOWS_SERVICE
  999. nt_service_main();
  1000. return 0;
  1001. #else
  1002. if (tor_init(argc, argv)<0)
  1003. return -1;
  1004. do_main_loop();
  1005. tor_cleanup();
  1006. return -1;
  1007. #endif
  1008. }
  1009. /*
  1010. Local Variables:
  1011. mode:c
  1012. indent-tabs-mode:nil
  1013. c-basic-offset:2
  1014. End:
  1015. */