main.c 37 KB

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