main.c 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char main_c_id[] = "$Id$";
  7. /**
  8. * \file main.c
  9. * \brief Tor main loop and startup functions.
  10. **/
  11. #include "or.h"
  12. #ifdef USE_DMALLOC
  13. #include <dmalloc.h>
  14. #endif
  15. /* These signals are defined to help control_signal_act work. */
  16. #ifndef SIGHUP
  17. #define SIGHUP 1
  18. #endif
  19. #ifndef SIGINT
  20. #define SIGINT 2
  21. #endif
  22. #ifndef SIGUSR1
  23. #define SIGUSR1 10
  24. #endif
  25. #ifndef SIGUSR2
  26. #define SIGUSR2 12
  27. #endif
  28. #ifndef SIGTERM
  29. #define SIGTERM 15
  30. #endif
  31. /********* PROTOTYPES **********/
  32. static void dumpstats(int severity); /* log stats */
  33. static void conn_read_callback(int fd, short event, void *_conn);
  34. static void conn_write_callback(int fd, short event, void *_conn);
  35. static void signal_callback(int fd, short events, void *arg);
  36. static void second_elapsed_callback(int fd, short event, void *args);
  37. static int conn_close_if_marked(int i);
  38. void tor_free_all(void);
  39. /********* START VARIABLES **********/
  40. int global_read_bucket; /**< Max number of bytes I can read this second. */
  41. int global_write_bucket; /**< Max number of bytes I can write this second. */
  42. /** What was the read bucket before the last call to prepare_for_pool?
  43. * (used to determine how many bytes we've read). */
  44. static int stats_prev_global_read_bucket;
  45. /** What was the write bucket before the last call to prepare_for_pool?
  46. * (used to determine how many bytes we've written). */
  47. static int stats_prev_global_write_bucket;
  48. /** How many bytes have we read/written since we started the process? */
  49. static uint64_t stats_n_bytes_read = 0;
  50. static uint64_t stats_n_bytes_written = 0;
  51. /** What time did this process start up? */
  52. long time_of_process_start = 0;
  53. /** How many seconds have we been running? */
  54. long stats_n_seconds_working = 0;
  55. /** When do we next download a directory? */
  56. static time_t time_to_fetch_directory = 0;
  57. /** When do we next upload our descriptor? */
  58. static time_t time_to_force_upload_descriptor = 0;
  59. /** When do we next download a running-routers summary? */
  60. static time_t time_to_fetch_running_routers = 0;
  61. /** Array of all open connections; each element corresponds to the element of
  62. * poll_array in the same position. The first nfds elements are valid. */
  63. static connection_t *connection_array[MAXCONNECTIONS+1] =
  64. { NULL };
  65. static smartlist_t *closeable_connection_lst = NULL;
  66. static int nfds=0; /**< Number of connections currently active. */
  67. /** We set this to 1 when we've fetched a dir, to know whether to complain
  68. * yet about unrecognized nicknames in entrynodes, exitnodes, etc.
  69. * Also, we don't try building circuits unless this is 1. */
  70. int has_fetched_directory=0;
  71. /** We set this to 1 when we've opened a circuit, so we can print a log
  72. * entry to inform the user that Tor is working. */
  73. int has_completed_circuit=0;
  74. #ifdef MS_WINDOWS
  75. #define MS_WINDOWS_SERVICE
  76. #endif
  77. #ifdef MS_WINDOWS_SERVICE
  78. #include <tchar.h>
  79. #define GENSRV_SERVICENAME TEXT("tor")
  80. #define GENSRV_DISPLAYNAME TEXT("Tor Win32 Service")
  81. #define GENSRV_DESCRIPTION TEXT("Provides an anonymous Internet communication system")
  82. SERVICE_STATUS service_status;
  83. SERVICE_STATUS_HANDLE hStatus;
  84. static char **backup_argv;
  85. static int backup_argc;
  86. static int nt_service_is_stopped(void);
  87. #else
  88. #define nt_service_is_stopped() (0)
  89. #endif
  90. #define CHECK_DESCRIPTOR_INTERVAL 60 /* one minute */
  91. #define TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT (20*60) /* 20 minutes */
  92. /********* END VARIABLES ************/
  93. /****************************************************************************
  94. *
  95. * This section contains accessors and other methods on the connection_array
  96. * and poll_array variables (which are global within this file and unavailable
  97. * outside it).
  98. *
  99. ****************************************************************************/
  100. /** Add <b>conn</b> to the array of connections that we can poll on. The
  101. * connection's socket must be set; the connection starts out
  102. * non-reading and non-writing.
  103. */
  104. int connection_add(connection_t *conn) {
  105. tor_assert(conn);
  106. tor_assert(conn->s >= 0);
  107. if (nfds >= get_options()->_ConnLimit-1) {
  108. log_fn(LOG_WARN,"Failing because we have %d connections already. Please raise your ulimit -n.", nfds);
  109. return -1;
  110. }
  111. tor_assert(conn->poll_index == -1); /* can only connection_add once */
  112. conn->poll_index = nfds;
  113. connection_array[nfds] = conn;
  114. conn->read_event = tor_malloc_zero(sizeof(struct event));
  115. conn->write_event = tor_malloc_zero(sizeof(struct event));
  116. event_set(conn->read_event, conn->s, EV_READ|EV_PERSIST,
  117. conn_read_callback, conn);
  118. event_set(conn->write_event, conn->s, EV_WRITE|EV_PERSIST,
  119. conn_write_callback, conn);
  120. nfds++;
  121. log_fn(LOG_INFO,"new conn type %s, socket %d, nfds %d.",
  122. CONN_TYPE_TO_STRING(conn->type), conn->s, nfds);
  123. return 0;
  124. }
  125. /** Remove the connection from the global list, and remove the
  126. * corresponding poll entry. Calling this function will shift the last
  127. * connection (if any) into the position occupied by conn.
  128. */
  129. int connection_remove(connection_t *conn) {
  130. int current_index;
  131. tor_assert(conn);
  132. tor_assert(nfds>0);
  133. log_fn(LOG_INFO,"removing socket %d (type %s), nfds now %d",
  134. conn->s, CONN_TYPE_TO_STRING(conn->type), nfds-1);
  135. tor_assert(conn->poll_index >= 0);
  136. current_index = conn->poll_index;
  137. if (current_index == nfds-1) { /* this is the end */
  138. nfds--;
  139. return 0;
  140. }
  141. connection_unregister(conn);
  142. /* replace this one with the one at the end */
  143. nfds--;
  144. connection_array[current_index] = connection_array[nfds];
  145. connection_array[current_index]->poll_index = current_index;
  146. return 0;
  147. }
  148. /** If it's an edge conn, remove it from the list
  149. * of conn's on this circuit. If it's not on an edge,
  150. * flush and send destroys for all circuits on this conn.
  151. *
  152. * If <b>remove</b> is non-zero, then remove it from the
  153. * connection_array and closeable_connection_lst.
  154. *
  155. * Then free it.
  156. */
  157. static void connection_unlink(connection_t *conn, int remove) {
  158. circuit_about_to_close_connection(conn);
  159. connection_about_to_close_connection(conn);
  160. if (remove) {
  161. connection_remove(conn);
  162. }
  163. smartlist_remove(closeable_connection_lst, conn);
  164. if (conn->type == CONN_TYPE_EXIT) {
  165. assert_connection_edge_not_dns_pending(conn);
  166. }
  167. connection_free(conn);
  168. }
  169. /** Schedule <b>conn</b> to be closed. **/
  170. void
  171. add_connection_to_closeable_list(connection_t *conn)
  172. {
  173. tor_assert(!smartlist_isin(closeable_connection_lst, conn));
  174. tor_assert(conn->marked_for_close);
  175. assert_connection_ok(conn, time(NULL));
  176. smartlist_add(closeable_connection_lst, conn);
  177. }
  178. /** Return 1 if conn is on the closeable list, else return 0. */
  179. int connection_is_on_closeable_list(connection_t *conn) {
  180. return smartlist_isin(closeable_connection_lst, conn);
  181. }
  182. /** Return true iff conn is in the current poll array. */
  183. int connection_in_array(connection_t *conn) {
  184. int i;
  185. for (i=0; i<nfds; ++i) {
  186. if (conn==connection_array[i])
  187. return 1;
  188. }
  189. return 0;
  190. }
  191. /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
  192. * to the length of the array. <b>*array</b> and <b>*n</b> must not
  193. * be modified.
  194. */
  195. void get_connection_array(connection_t ***array, int *n) {
  196. *array = connection_array;
  197. *n = nfds;
  198. }
  199. /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
  200. * mask is a bitmask whose bits are EV_READ and EV_WRITE.)
  201. */
  202. void connection_watch_events(connection_t *conn, short events) {
  203. int r;
  204. tor_assert(conn);
  205. tor_assert(conn->read_event);
  206. tor_assert(conn->write_event);
  207. if (events & EV_READ) {
  208. r = event_add(conn->read_event, NULL);
  209. } else {
  210. r = event_del(conn->read_event);
  211. }
  212. if (r<0)
  213. log_fn(LOG_WARN,
  214. "Error from libevent setting read event state for %d to %swatched.",
  215. (int)conn->s, (events & EV_READ)?"":"un");
  216. if (events & EV_WRITE) {
  217. r = event_add(conn->write_event, NULL);
  218. } else {
  219. r = event_del(conn->write_event);
  220. }
  221. if (r<0)
  222. log_fn(LOG_WARN,
  223. "Error from libevent setting read event state for %d to %swatched.",
  224. (int)conn->s, (events & EV_WRITE)?"":"un");
  225. }
  226. /** Return true iff <b>conn</b> is listening for read events. */
  227. int connection_is_reading(connection_t *conn) {
  228. tor_assert(conn);
  229. return conn->read_event && event_pending(conn->read_event, EV_READ, NULL);
  230. }
  231. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  232. void connection_stop_reading(connection_t *conn) {
  233. tor_assert(conn);
  234. tor_assert(conn->read_event);
  235. log(LOG_DEBUG,"connection_stop_reading() called.");
  236. if (event_del(conn->read_event))
  237. log_fn(LOG_WARN, "Error from libevent setting read event state for %d to unwatched.",
  238. (int)conn->s);
  239. }
  240. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  241. void connection_start_reading(connection_t *conn) {
  242. tor_assert(conn);
  243. tor_assert(conn->read_event);
  244. if (event_add(conn->read_event, NULL))
  245. log_fn(LOG_WARN, "Error from libevent setting read event state for %d to watched.",
  246. (int)conn->s);
  247. }
  248. /** Return true iff <b>conn</b> is listening for write events. */
  249. int connection_is_writing(connection_t *conn) {
  250. tor_assert(conn);
  251. return conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL);
  252. }
  253. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  254. void connection_stop_writing(connection_t *conn) {
  255. tor_assert(conn);
  256. tor_assert(conn->write_event);
  257. if (event_del(conn->write_event))
  258. log_fn(LOG_WARN, "Error from libevent setting write event state for %d to unwatched.",
  259. (int)conn->s);
  260. }
  261. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  262. void connection_start_writing(connection_t *conn) {
  263. tor_assert(conn);
  264. tor_assert(conn->write_event);
  265. if (event_add(conn->write_event, NULL))
  266. log_fn(LOG_WARN, "Error from libevent setting write event state for %d to watched.",
  267. (int)conn->s);
  268. }
  269. /** Close all connections that have been schedule to get closed */
  270. static void
  271. close_closeable_connections(void)
  272. {
  273. int i;
  274. if (!smartlist_len(closeable_connection_lst))
  275. return;
  276. for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
  277. connection_t *conn = smartlist_get(closeable_connection_lst, i);
  278. if (conn->poll_index < 0) {
  279. connection_unlink(conn, 0); /* blow it away right now */
  280. } else {
  281. if (!conn_close_if_marked(conn->poll_index))
  282. ++i;
  283. }
  284. }
  285. }
  286. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  287. * some data to read. */
  288. static void
  289. conn_read_callback(int fd, short event, void *_conn)
  290. {
  291. connection_t *conn = _conn;
  292. if (conn->marked_for_close)
  293. return;
  294. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  295. assert_connection_ok(conn, time(NULL));
  296. assert_all_pending_dns_resolves_ok();
  297. if (connection_handle_read(conn) < 0) {
  298. if (!conn->marked_for_close) {
  299. #ifndef MS_WINDOWS
  300. log_fn(LOG_WARN,"Bug: unhandled error on read for %s connection (fd %d); removing",
  301. CONN_TYPE_TO_STRING(conn->type), conn->s);
  302. #ifdef TOR_FRAGILE
  303. tor_assert(0);
  304. #endif
  305. #endif
  306. if (CONN_IS_EDGE(conn))
  307. connection_edge_end_errno(conn, conn->cpath_layer);
  308. connection_mark_for_close(conn);
  309. }
  310. }
  311. assert_connection_ok(conn, time(NULL));
  312. assert_all_pending_dns_resolves_ok();
  313. if (smartlist_len(closeable_connection_lst))
  314. close_closeable_connections();
  315. }
  316. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  317. * some data to write. */
  318. static void conn_write_callback(int fd, short events, void *_conn)
  319. {
  320. connection_t *conn = _conn;
  321. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  322. if (conn->marked_for_close)
  323. return;
  324. assert_connection_ok(conn, time(NULL));
  325. assert_all_pending_dns_resolves_ok();
  326. if (connection_handle_write(conn) < 0) {
  327. if (!conn->marked_for_close) {
  328. /* this connection is broken. remove it. */
  329. log_fn(LOG_WARN,"Bug: unhandled error on write for %s connection (fd %d); removing",
  330. CONN_TYPE_TO_STRING(conn->type), conn->s);
  331. #ifdef TOR_FRAGILE
  332. tor_assert(0);
  333. #endif
  334. conn->has_sent_end = 1; /* otherwise we cry wolf about duplicate close */
  335. /* XXX do we need a close-immediate here, so we don't try to flush? */
  336. connection_mark_for_close(conn);
  337. }
  338. }
  339. assert_connection_ok(conn, time(NULL));
  340. assert_all_pending_dns_resolves_ok();
  341. if (smartlist_len(closeable_connection_lst))
  342. close_closeable_connections();
  343. }
  344. /** If the connection at connection_array[i] is marked for close, then:
  345. * - If it has data that it wants to flush, try to flush it.
  346. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  347. * true, then leave the connection open and return.
  348. * - Otherwise, remove the connection from connection_array and from
  349. * all other lists, close it, and free it.
  350. * Returns 1 if the connection was closed, 0 otherwise.
  351. */
  352. static int conn_close_if_marked(int i) {
  353. connection_t *conn;
  354. int retval;
  355. conn = connection_array[i];
  356. if (!conn->marked_for_close)
  357. return 0; /* nothing to see here, move along */
  358. assert_connection_ok(conn, time(NULL));
  359. assert_all_pending_dns_resolves_ok();
  360. log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
  361. if (conn->s >= 0 && connection_wants_to_flush(conn)) {
  362. /* -1 means it's an incomplete edge connection, or that the socket
  363. * has already been closed as unflushable. */
  364. if (!conn->hold_open_until_flushed)
  365. log_fn(LOG_INFO,
  366. "Conn (addr %s, fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
  367. "(Marked at %s:%d)",
  368. conn->address, conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  369. (int)conn->outbuf_flushlen, conn->marked_for_close_file, conn->marked_for_close);
  370. if (connection_speaks_cells(conn)) {
  371. if (conn->state == OR_CONN_STATE_OPEN) {
  372. retval = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  373. } else
  374. retval = -1; /* never flush non-open broken tls connections */
  375. } else {
  376. retval = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  377. }
  378. if (retval >= 0 &&
  379. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  380. log_fn(LOG_INFO,"Holding conn (fd %d) open for more flushing.",conn->s);
  381. /* XXX should we reset timestamp_lastwritten here? */
  382. return 0;
  383. }
  384. if (connection_wants_to_flush(conn)) {
  385. log_fn(LOG_NOTICE,"Conn (addr %s, fd %d, type %s, state %d) is being closed, but there are still %d bytes we can't write. (Marked at %s:%d)",
  386. conn->address, conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  387. (int)buf_datalen(conn->outbuf), conn->marked_for_close_file,
  388. conn->marked_for_close);
  389. }
  390. }
  391. connection_unlink(conn, 1); /* unlink, remove, free */
  392. return 1;
  393. }
  394. /** We've just tried every dirserver we know about, and none of
  395. * them were reachable. Assume the network is down. Change state
  396. * so next time an application connection arrives we'll delay it
  397. * and try another directory fetch. Kill off all the circuit_wait
  398. * streams that are waiting now, since they will all timeout anyway.
  399. */
  400. void directory_all_unreachable(time_t now) {
  401. connection_t *conn;
  402. has_fetched_directory=0;
  403. stats_n_seconds_working=0; /* reset it */
  404. while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
  405. AP_CONN_STATE_CIRCUIT_WAIT))) {
  406. conn->has_sent_end = 1; /* it's not connected anywhere, so no need to end */
  407. log_fn(LOG_NOTICE,"Network down? Failing connection to '%s:%d'.",
  408. conn->socks_request->address, conn->socks_request->port);
  409. connection_ap_handshake_socks_reply(conn, NULL, 0, SOCKS5_NET_UNREACHABLE);
  410. connection_mark_for_close(conn);
  411. }
  412. }
  413. static INLINE int
  414. get_dir_fetch_period(or_options_t *options)
  415. {
  416. if (options->DirFetchPeriod)
  417. /* Value from config file. */
  418. return options->DirFetchPeriod;
  419. else if (options->DirPort)
  420. /* Default for directory server */
  421. return 20*60;
  422. else
  423. /* Default for average user. */
  424. return 40*60;
  425. }
  426. static INLINE int
  427. get_status_fetch_period(or_options_t *options)
  428. {
  429. if (options->StatusFetchPeriod)
  430. /* Value from config file. */
  431. return options->StatusFetchPeriod;
  432. else if (options->DirPort)
  433. /* Default for directory server */
  434. return 15*60;
  435. else
  436. /* Default for average user. */
  437. return 30*60;
  438. }
  439. /** This function is called whenever we successfully pull down a directory.
  440. * If <b>identity_digest</b> is defined, it contains the digest of the
  441. * router that just gave us this directory. */
  442. void directory_has_arrived(time_t now, char *identity_digest) {
  443. or_options_t *options = get_options();
  444. log_fn(LOG_INFO, "A directory has arrived.");
  445. has_fetched_directory=1;
  446. /* Don't try to upload or download anything for a while
  447. * after the directory we had when we started.
  448. */
  449. if (!time_to_fetch_directory)
  450. time_to_fetch_directory = now + get_dir_fetch_period(options);
  451. if (!time_to_force_upload_descriptor)
  452. time_to_force_upload_descriptor = now + options->DirPostPeriod;
  453. if (!time_to_fetch_running_routers)
  454. time_to_fetch_running_routers = now + get_status_fetch_period(options);
  455. if (identity_digest) { /* if this is us, then our dirport is reachable */
  456. routerinfo_t *router = router_get_by_digest(identity_digest);
  457. if (!router) // XXX
  458. log_fn(LOG_WARN,"Bug: router_get_by_digest doesn't find me.");
  459. if (router && router_is_me(router)) {
  460. router_dirport_found_reachable();
  461. }
  462. }
  463. if (server_mode(options) &&
  464. !we_are_hibernating()) { /* connect to the appropriate routers */
  465. router_retry_connections();
  466. if (identity_digest) /* we got a fresh directory */
  467. consider_testing_reachability();
  468. }
  469. }
  470. /** Perform regular maintenance tasks for a single connection. This
  471. * function gets run once per second per connection by run_scheduled_events.
  472. */
  473. static void run_connection_housekeeping(int i, time_t now) {
  474. cell_t cell;
  475. connection_t *conn = connection_array[i];
  476. or_options_t *options = get_options();
  477. if (conn->outbuf && !buf_datalen(conn->outbuf))
  478. conn->timestamp_lastempty = now;
  479. /* Expire any directory connections that haven't sent anything for 5 min */
  480. if (conn->type == CONN_TYPE_DIR &&
  481. !conn->marked_for_close &&
  482. conn->timestamp_lastwritten + 5*60 < now) {
  483. log_fn(LOG_INFO,"Expiring wedged directory conn (fd %d, purpose %d)", conn->s, conn->purpose);
  484. connection_mark_for_close(conn);
  485. return;
  486. }
  487. /* If we haven't written to an OR connection for a while, then either nuke
  488. the connection or send a keepalive, depending. */
  489. if (connection_speaks_cells(conn) &&
  490. now >= conn->timestamp_lastwritten + options->KeepalivePeriod) {
  491. routerinfo_t *router = router_get_by_digest(conn->identity_digest);
  492. if (!connection_state_is_open(conn)) {
  493. log_fn(LOG_INFO,"Expiring non-open OR connection to %d (%s:%d).",
  494. i,conn->address, conn->port);
  495. connection_mark_for_close(conn);
  496. conn->hold_open_until_flushed = 1;
  497. } else if (we_are_hibernating() && !circuit_get_by_conn(conn) &&
  498. !buf_datalen(conn->outbuf)) {
  499. log_fn(LOG_INFO,"Expiring non-used OR connection to %d (%s:%d) [Hibernating or exiting].",
  500. i,conn->address, conn->port);
  501. connection_mark_for_close(conn);
  502. conn->hold_open_until_flushed = 1;
  503. } else if (!clique_mode(options) && !circuit_get_by_conn(conn) &&
  504. (!router || !server_mode(options) || !router_is_clique_mode(router))) {
  505. log_fn(LOG_INFO,"Expiring non-used connection to %d (%s:%d) [Not in clique mode].",
  506. i,conn->address, conn->port);
  507. connection_mark_for_close(conn);
  508. conn->hold_open_until_flushed = 1;
  509. } else if (
  510. now >= conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
  511. now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
  512. log_fn(LOG_NOTICE,"Expiring stuck connection to %d (%s:%d). (%d bytes to flush; %d seconds since last write)",
  513. i, conn->address, conn->port,
  514. (int)buf_datalen(conn->outbuf),
  515. (int)(now-conn->timestamp_lastwritten));
  516. connection_mark_for_close(conn);
  517. } else {
  518. /* either in clique mode, or we've got a circuit. send a padding cell. */
  519. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  520. conn->address, conn->port);
  521. memset(&cell,0,sizeof(cell_t));
  522. cell.command = CELL_PADDING;
  523. connection_or_write_cell_to_buf(&cell, conn);
  524. }
  525. }
  526. }
  527. /** Perform regular maintenance tasks. This function gets run once per
  528. * second by prepare_for_poll.
  529. */
  530. static void run_scheduled_events(time_t now) {
  531. static time_t last_rotated_certificate = 0;
  532. static time_t time_to_check_listeners = 0;
  533. static time_t time_to_check_descriptor = 0;
  534. or_options_t *options = get_options();
  535. int i;
  536. /** 0. See if we've been asked to shut down and our timeout has
  537. * expired; or if our bandwidth limits are exhausted and we
  538. * should hibernate; or if it's time to wake up from hibernation.
  539. */
  540. consider_hibernation(now);
  541. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  542. * shut down and restart all cpuworkers, and update the directory if
  543. * necessary.
  544. */
  545. if (server_mode(options) &&
  546. get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  547. log_fn(LOG_INFO,"Rotating onion key.");
  548. rotate_onion_key();
  549. cpuworkers_rotate();
  550. if (router_rebuild_descriptor(1)<0) {
  551. log_fn(LOG_WARN, "Couldn't rebuild router descriptor");
  552. }
  553. if (advertised_server_mode())
  554. router_upload_dir_desc_to_dirservers(0);
  555. }
  556. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  557. if (!last_rotated_certificate)
  558. last_rotated_certificate = now;
  559. if (last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
  560. log_fn(LOG_INFO,"Rotating tls context.");
  561. if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
  562. MAX_SSL_KEY_LIFETIME) < 0) {
  563. log_fn(LOG_WARN, "Error reinitializing TLS context");
  564. /* XXX is it a bug here, that we just keep going? */
  565. }
  566. last_rotated_certificate = now;
  567. /* XXXX We should rotate TLS connections as well; this code doesn't change
  568. * them at all. */
  569. }
  570. /** 1c. If we have to change the accounting interval or record
  571. * bandwidth used in this accounting interval, do so. */
  572. if (accounting_is_enabled(options))
  573. accounting_run_housekeeping(now);
  574. /** 2. Periodically, we consider getting a new directory, getting a
  575. * new running-routers list, and/or force-uploading our descriptor
  576. * (if we've passed our internal checks). */
  577. if (time_to_fetch_directory < now) {
  578. time_t next_status_fetch;
  579. /* purge obsolete entries */
  580. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  581. if (authdir_mode(options)) {
  582. /* We're a directory; dump any old descriptors. */
  583. dirserv_remove_old_servers(ROUTER_MAX_AGE);
  584. }
  585. if (server_mode(options) && !we_are_hibernating()) {
  586. /* dirservers try to reconnect, in case connections have failed;
  587. * and normal servers try to reconnect to dirservers */
  588. router_retry_connections();
  589. }
  590. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
  591. time_to_fetch_directory = now + get_dir_fetch_period(options);
  592. next_status_fetch = now + get_status_fetch_period(options);
  593. if (time_to_fetch_running_routers < next_status_fetch) {
  594. time_to_fetch_running_routers = next_status_fetch;
  595. }
  596. /* Also, take this chance to remove old information from rephist. */
  597. rep_history_clean(now-24*60*60);
  598. }
  599. if (time_to_fetch_running_routers < now) {
  600. if (!authdir_mode(options)) {
  601. directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST, NULL, 1);
  602. }
  603. time_to_fetch_running_routers = now + get_status_fetch_period(options);
  604. }
  605. if (time_to_force_upload_descriptor < now) {
  606. consider_publishable_server(now, 1);
  607. rend_cache_clean(); /* this should go elsewhere? */
  608. time_to_force_upload_descriptor = now + options->DirPostPeriod;
  609. }
  610. /* 2b. Once per minute, regenerate and upload the descriptor if the old
  611. * one is inaccurate. */
  612. if (time_to_check_descriptor < now) {
  613. time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
  614. consider_publishable_server(now, 0);
  615. /* also, check religiously for reachability, if it's within the first
  616. * 20 minutes of our uptime. */
  617. if (stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT)
  618. consider_testing_reachability();
  619. }
  620. /** 3a. Every second, we examine pending circuits and prune the
  621. * ones which have been pending for more than a few seconds.
  622. * We do this before step 4, so it can try building more if
  623. * it's not comfortable with the number of available circuits.
  624. */
  625. circuit_expire_building(now);
  626. /** 3b. Also look at pending streams and prune the ones that 'began'
  627. * a long time ago but haven't gotten a 'connected' yet.
  628. * Do this before step 4, so we can put them back into pending
  629. * state to be picked up by the new circuit.
  630. */
  631. connection_ap_expire_beginning();
  632. /** 3c. And expire connections that we've held open for too long.
  633. */
  634. connection_expire_held_open();
  635. /** 3d. And every 60 seconds, we relaunch listeners if any died. */
  636. if (!we_are_hibernating() && time_to_check_listeners < now) {
  637. retry_all_listeners(0); /* 0 means "only if some died." */
  638. time_to_check_listeners = now+60;
  639. }
  640. /** 4. Every second, we try a new circuit if there are no valid
  641. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  642. * that became dirty more than MaxCircuitDirtiness seconds ago,
  643. * and we make a new circ if there are no clean circuits.
  644. */
  645. if (has_fetched_directory && !we_are_hibernating())
  646. circuit_build_needed_circs(now);
  647. /** 5. We do housekeeping for each connection... */
  648. for (i=0;i<nfds;i++) {
  649. run_connection_housekeeping(i, now);
  650. }
  651. /** 6. And remove any marked circuits... */
  652. circuit_close_all_marked();
  653. /** 7. And upload service descriptors if necessary. */
  654. if (has_fetched_directory && !we_are_hibernating())
  655. rend_consider_services_upload(now);
  656. /** 8. and blow away any connections that need to die. have to do this now,
  657. * because if we marked a conn for close and left its socket -1, then
  658. * we'll pass it to poll/select and bad things will happen.
  659. */
  660. close_closeable_connections();
  661. }
  662. /** Libevent callback: invoked once every second. */
  663. static void second_elapsed_callback(int fd, short event, void *args)
  664. {
  665. static struct event *timeout_event = NULL;
  666. static struct timeval one_second;
  667. static long current_second = 0;
  668. struct timeval now;
  669. size_t bytes_written;
  670. size_t bytes_read;
  671. int seconds_elapsed;
  672. or_options_t *options = get_options();
  673. if (!timeout_event) {
  674. timeout_event = tor_malloc_zero(sizeof(struct event));
  675. evtimer_set(timeout_event, second_elapsed_callback, NULL);
  676. one_second.tv_sec = 1;
  677. one_second.tv_usec = 0;
  678. }
  679. /* log_fn(LOG_NOTICE, "Tick."); */
  680. tor_gettimeofday(&now);
  681. /* the second has rolled over. check more stuff. */
  682. bytes_written = stats_prev_global_write_bucket - global_write_bucket;
  683. bytes_read = stats_prev_global_read_bucket - global_read_bucket;
  684. /* XXX below we get suspicious if time jumps forward more than 10
  685. * seconds, but we never notice if it jumps *back* more than 10 seconds.
  686. * This could be useful for detecting that we just NTP'ed to three
  687. * weeks ago and it will be 3 weeks and 15 minutes until any of our
  688. * events trigger.
  689. */
  690. seconds_elapsed = current_second ? (now.tv_sec - current_second) : 0;
  691. stats_n_bytes_read += bytes_read;
  692. stats_n_bytes_written += bytes_written;
  693. if (accounting_is_enabled(options))
  694. accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
  695. control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
  696. connection_bucket_refill(&now);
  697. stats_prev_global_read_bucket = global_read_bucket;
  698. stats_prev_global_write_bucket = global_write_bucket;
  699. if (server_mode(options) &&
  700. stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT &&
  701. stats_n_seconds_working+seconds_elapsed >=
  702. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT &&
  703. !check_whether_ports_reachable()) {
  704. routerinfo_t *me = router_get_my_routerinfo();
  705. log_fn(LOG_WARN,"Your server (%s:%d) has not managed to confirm that it is reachable. Please check your firewalls, ports, address, etc.",
  706. me ? me->address : options->Address, options->ORPort);
  707. }
  708. /* if more than 10s have elapsed, probably the clock jumped: doesn't count. */
  709. if (seconds_elapsed < 100)
  710. stats_n_seconds_working += seconds_elapsed;
  711. else
  712. circuit_note_clock_jumped(seconds_elapsed);
  713. assert_all_pending_dns_resolves_ok();
  714. run_scheduled_events(now.tv_sec);
  715. assert_all_pending_dns_resolves_ok();
  716. current_second = now.tv_sec; /* remember which second it is, for next time */
  717. #if 0
  718. for (i=0;i<nfds;i++) {
  719. conn = connection_array[i];
  720. if (connection_has_pending_tls_data(conn) &&
  721. connection_is_reading(conn)) {
  722. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  723. return; /* has pending bytes to read; don't let poll wait. */
  724. }
  725. }
  726. #endif
  727. if (evtimer_add(timeout_event, &one_second))
  728. log_fn(LOG_ERR,
  729. "Error from libevent when setting one-second timeout event");
  730. }
  731. /** Called when we get a SIGHUP: reload configuration files and keys,
  732. * retry all connections, re-upload all descriptors, and so on. */
  733. static int do_hup(void) {
  734. char keydir[512];
  735. or_options_t *options = get_options();
  736. log_fn(LOG_NOTICE,"Received sighup. Reloading config.");
  737. has_completed_circuit=0;
  738. if (accounting_is_enabled(options))
  739. accounting_record_bandwidth_usage(time(NULL));
  740. addressmap_clear_transient();
  741. /* first, reload config variables, in case they've changed */
  742. /* no need to provide argc/v, they've been cached inside init_from_config */
  743. if (init_from_config(0, NULL) < 0) {
  744. log_fn(LOG_ERR,"Reading config failed--see warnings above. For usage, try -h.");
  745. return -1;
  746. }
  747. options = get_options(); /* they have changed now */
  748. if (authdir_mode(options)) {
  749. /* reload the approved-routers file */
  750. tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", options->DataDirectory);
  751. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  752. if (dirserv_parse_fingerprint_file(keydir) < 0) {
  753. log_fn(LOG_NOTICE, "Error reloading fingerprints. Continuing with old list.");
  754. }
  755. }
  756. /* Fetch a new directory. Even authdirservers do this. */
  757. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
  758. if (server_mode(options)) {
  759. const char *descriptor;
  760. /* Restart cpuworker and dnsworker processes, so they get up-to-date
  761. * configuration options. */
  762. cpuworkers_rotate();
  763. dnsworkers_rotate();
  764. /* Rebuild fresh descriptor, but leave old one on failure. */
  765. router_rebuild_descriptor(1);
  766. descriptor = router_get_my_descriptor();
  767. if (!descriptor) {
  768. log_fn(LOG_WARN,"No descriptor to save.");
  769. return 0;
  770. }
  771. tor_snprintf(keydir,sizeof(keydir),"%s/router.desc",
  772. options->DataDirectory);
  773. log_fn(LOG_INFO,"Saving descriptor to %s...",keydir);
  774. if (write_str_to_file(keydir, descriptor, 0)) {
  775. return 0;
  776. }
  777. }
  778. return 0;
  779. }
  780. /** Tor main loop. */
  781. static int do_main_loop(void) {
  782. int loop_result;
  783. /* load the private keys, if we're supposed to have them, and set up the
  784. * TLS context. */
  785. if (! identity_key_is_set()) {
  786. if (init_keys() < 0) {
  787. log_fn(LOG_ERR,"Error initializing keys; exiting");
  788. return -1;
  789. }
  790. }
  791. /* Set up our buckets */
  792. connection_bucket_init();
  793. stats_prev_global_read_bucket = global_read_bucket;
  794. stats_prev_global_write_bucket = global_write_bucket;
  795. /* load the routers file, or assign the defaults. */
  796. if (router_reload_router_list()) {
  797. return -1;
  798. }
  799. if (authdir_mode(get_options())) {
  800. /* the directory is already here, run startup things */
  801. router_retry_connections();
  802. }
  803. if (server_mode(get_options())) {
  804. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  805. cpu_init();
  806. }
  807. /* set up once-a-second callback. */
  808. second_elapsed_callback(0,0,NULL);
  809. for (;;) {
  810. if (nt_service_is_stopped())
  811. return 0;
  812. /* poll until we have an event, or the second ends */
  813. loop_result = event_dispatch();
  814. /* let catch() handle things like ^c, and otherwise don't worry about it */
  815. if (loop_result < 0) {
  816. int e = errno;
  817. /* let the program survive things like ^z */
  818. if (e != EINTR) {
  819. log_fn(LOG_ERR,"event poll failed: %s [%d]",
  820. tor_socket_strerror(e), e);
  821. return -1;
  822. } else {
  823. log_fn(LOG_DEBUG,"event poll interrupted.");
  824. /* You can't trust the results of this poll(). Go back to the
  825. * top of the big for loop. */
  826. continue;
  827. }
  828. }
  829. /* refilling buckets and sending cells happens at the beginning of the
  830. * next iteration of the loop, inside prepare_for_poll()
  831. * XXXX No longer so.
  832. */
  833. }
  834. }
  835. /** Used to implement the SIGNAL control command: if we accept
  836. * <b>the_signal</b> as a remote pseudo-signal, then act on it and
  837. * return 0. Else return -1. */
  838. /* We don't re-use catch() here because:
  839. * 1. We handle a different set of signals than those allowed in catch.
  840. * 2. Platforms without signal() are unlikely to define SIGfoo.
  841. * 3. The control spec is defined to use fixed numeric signal values
  842. * which just happen to match the unix values.
  843. */
  844. int
  845. control_signal_act(int the_signal)
  846. {
  847. switch (the_signal)
  848. {
  849. case 1:
  850. signal_callback(0,0,(void*)(uintptr_t)SIGHUP);
  851. break;
  852. case 2:
  853. signal_callback(0,0,(void*)(uintptr_t)SIGINT);
  854. break;
  855. case 10:
  856. signal_callback(0,0,(void*)(uintptr_t)SIGUSR1);
  857. break;
  858. case 12:
  859. signal_callback(0,0,(void*)(uintptr_t)SIGUSR2);
  860. break;
  861. case 15:
  862. signal_callback(0,0,(void*)(uintptr_t)SIGTERM);
  863. break;
  864. default:
  865. return -1;
  866. }
  867. return 0;
  868. }
  869. static void signal_callback(int fd, short events, void *arg)
  870. {
  871. uintptr_t sig = (uintptr_t)arg;
  872. switch (sig)
  873. {
  874. case SIGTERM:
  875. log(LOG_ERR,"Catching signal TERM, exiting cleanly.");
  876. tor_cleanup();
  877. exit(0);
  878. break;
  879. case SIGINT:
  880. if (!server_mode(get_options())) { /* do it now */
  881. log(LOG_NOTICE,"Interrupt: exiting cleanly.");
  882. tor_cleanup();
  883. exit(0);
  884. }
  885. hibernate_begin_shutdown();
  886. break;
  887. #ifdef SIGPIPE
  888. case SIGPIPE:
  889. log(LOG_NOTICE,"Caught sigpipe. Ignoring.");
  890. break;
  891. #endif
  892. case SIGUSR1:
  893. /* prefer to log it at INFO, but make sure we always see it */
  894. dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
  895. break;
  896. case SIGUSR2:
  897. switch_logs_debug();
  898. log(LOG_NOTICE,"Caught USR2. Going to loglevel debug.");
  899. break;
  900. case SIGHUP:
  901. if (do_hup() < 0) {
  902. log_fn(LOG_WARN,"Restart failed (config error?). Exiting.");
  903. tor_cleanup();
  904. exit(1);
  905. }
  906. break;
  907. #ifdef SIGCHLD
  908. case SIGCHLD:
  909. while (waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more zombies */
  910. break;
  911. #endif
  912. }
  913. }
  914. /** Write all statistics to the log, with log level 'severity'. Called
  915. * in response to a SIGUSR1. */
  916. static void
  917. dumpstats(int severity) {
  918. int i;
  919. connection_t *conn;
  920. time_t now = time(NULL);
  921. time_t elapsed;
  922. log(severity, "Dumping stats:");
  923. for (i=0;i<nfds;i++) {
  924. conn = connection_array[i];
  925. log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  926. i, conn->s, conn->type, CONN_TYPE_TO_STRING(conn->type),
  927. conn->state, conn_state_to_string[conn->type][conn->state], (int)(now - conn->timestamp_created));
  928. if (!connection_is_listener(conn)) {
  929. log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
  930. log(severity,"Conn %d: %d bytes waiting on inbuf (last read %d secs ago)",i,
  931. (int)buf_datalen(conn->inbuf),
  932. (int)(now - conn->timestamp_lastread));
  933. log(severity,"Conn %d: %d bytes waiting on outbuf (last written %d secs ago)",i,
  934. (int)buf_datalen(conn->outbuf), (int)(now - conn->timestamp_lastwritten));
  935. }
  936. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
  937. }
  938. log(severity,
  939. "Cells processed: %10lu padding\n"
  940. " %10lu create\n"
  941. " %10lu created\n"
  942. " %10lu relay\n"
  943. " (%10lu relayed)\n"
  944. " (%10lu delivered)\n"
  945. " %10lu destroy",
  946. stats_n_padding_cells_processed,
  947. stats_n_create_cells_processed,
  948. stats_n_created_cells_processed,
  949. stats_n_relay_cells_processed,
  950. stats_n_relay_cells_relayed,
  951. stats_n_relay_cells_delivered,
  952. stats_n_destroy_cells_processed);
  953. if (stats_n_data_cells_packaged)
  954. log(severity,"Average packaged cell fullness: %2.3f%%",
  955. 100*(((double)stats_n_data_bytes_packaged) /
  956. (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  957. if (stats_n_data_cells_received)
  958. log(severity,"Average delivered cell fullness: %2.3f%%",
  959. 100*(((double)stats_n_data_bytes_received) /
  960. (stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  961. if (now - time_of_process_start >= 0)
  962. elapsed = now - time_of_process_start;
  963. else
  964. elapsed = 0;
  965. if (elapsed) {
  966. log(severity,
  967. "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
  968. U64_PRINTF_ARG(stats_n_bytes_read),
  969. (int)elapsed,
  970. (int) (stats_n_bytes_read/elapsed));
  971. log(severity,
  972. "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
  973. U64_PRINTF_ARG(stats_n_bytes_written),
  974. (int)elapsed,
  975. (int) (stats_n_bytes_written/elapsed));
  976. }
  977. rep_hist_dump_stats(now,severity);
  978. rend_service_dump_stats(severity);
  979. }
  980. /** Called by exit() as we shut down the process.
  981. */
  982. static void exit_function(void)
  983. {
  984. /* NOTE: If we ever daemonize, this gets called immediately. That's
  985. * okay for now, because we only use this on Windows. */
  986. #ifdef MS_WINDOWS
  987. WSACleanup();
  988. #endif
  989. }
  990. /** Set up the signal handlers for either parent or child. */
  991. void handle_signals(int is_parent)
  992. {
  993. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  994. int i;
  995. static int signals[] = {
  996. SIGINT, /* do a controlled slow shutdown */
  997. SIGTERM, /* to terminate now */
  998. SIGPIPE, /* otherwise sigpipe kills us */
  999. SIGUSR1, /* dump stats */
  1000. SIGUSR2, /* go to loglevel debug */
  1001. SIGHUP, /* to reload config, retry conns, etc */
  1002. #ifdef SIGXFSZ
  1003. SIGXFSZ, /* handle file-too-big resource exhaustion */
  1004. #endif
  1005. SIGCHLD, /* handle dns/cpu workers that exit */
  1006. -1 };
  1007. static struct event signal_events[16]; /* bigger than it has to be. */
  1008. if (is_parent) {
  1009. for (i = 0; signals[i] >= 0; ++i) {
  1010. signal_set(&signal_events[i], signals[i], signal_callback,
  1011. (void*)(uintptr_t)signals[i]);
  1012. if (signal_add(&signal_events[i], NULL))
  1013. log_fn(LOG_WARN, "Error from libevent when adding event for signal %d",
  1014. signals[i]);
  1015. }
  1016. } else {
  1017. struct sigaction action;
  1018. action.sa_flags = 0;
  1019. sigemptyset(&action.sa_mask);
  1020. action.sa_handler = SIG_IGN;
  1021. sigaction(SIGINT, &action, NULL);
  1022. sigaction(SIGTERM, &action, NULL);
  1023. sigaction(SIGPIPE, &action, NULL);
  1024. sigaction(SIGUSR1, &action, NULL);
  1025. sigaction(SIGUSR2, &action, NULL);
  1026. sigaction(SIGHUP, &action, NULL);
  1027. #ifdef SIGXFSZ
  1028. sigaction(SIGXFSZ, &action, NULL);
  1029. #endif
  1030. }
  1031. #endif /* signal stuff */
  1032. }
  1033. /** Main entry point for the Tor command-line client.
  1034. */
  1035. static int tor_init(int argc, char *argv[]) {
  1036. time_of_process_start = time(NULL);
  1037. closeable_connection_lst = smartlist_create();
  1038. /* Initialize the history structures. */
  1039. rep_hist_init();
  1040. /* Initialize the service cache. */
  1041. rend_cache_init();
  1042. addressmap_init(); /* Init the client dns cache. Do it always, since it's cheap. */
  1043. /* give it somewhere to log to initially */
  1044. add_temp_log();
  1045. log_fn(LOG_NOTICE,"Tor v%s. This is experimental software. Do not rely on it for strong anonymity.",VERSION);
  1046. if (network_init()<0) {
  1047. log_fn(LOG_ERR,"Error initializing network; exiting.");
  1048. return -1;
  1049. }
  1050. atexit(exit_function);
  1051. if (init_from_config(argc,argv) < 0) {
  1052. log_fn(LOG_ERR,"Reading config failed--see warnings above. For usage, try -h.");
  1053. return -1;
  1054. }
  1055. #ifndef MS_WINDOWS
  1056. if (geteuid()==0)
  1057. log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
  1058. #endif
  1059. /* only spawn dns handlers if we're a router */
  1060. if (server_mode(get_options()) && get_options()->command == CMD_RUN_TOR) {
  1061. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  1062. /* XXX really, this should get moved to do_main_loop */
  1063. }
  1064. handle_signals(1);
  1065. crypto_global_init();
  1066. crypto_seed_rng();
  1067. return 0;
  1068. }
  1069. /** Free all memory that we might have allocated somewhere.
  1070. * Helps us find the real leaks with dmalloc and the like.
  1071. *
  1072. * Also valgrind should then report 0 reachable in its
  1073. * leak report */
  1074. void tor_free_all(void)
  1075. {
  1076. routerlist_free_current();
  1077. free_trusted_dir_servers();
  1078. addressmap_free_all();
  1079. free_socks_policy();
  1080. free_dir_policy();
  1081. dirserv_free_all();
  1082. rend_service_free_all();
  1083. rend_cache_free_all();
  1084. rep_hist_free_all();
  1085. dns_free_all();
  1086. clear_pending_onions();
  1087. circuit_free_all();
  1088. connection_free_all();
  1089. config_free_all();
  1090. router_free_all_keys();
  1091. tor_tls_free_all();
  1092. /* stuff in main.c */
  1093. smartlist_free(closeable_connection_lst);
  1094. close_logs(); /* free log strings. do this last so logs keep working. */
  1095. }
  1096. /** Do whatever cleanup is necessary before shutting Tor down. */
  1097. void tor_cleanup(void) {
  1098. or_options_t *options = get_options();
  1099. /* Remove our pid file. We don't care if there was an error when we
  1100. * unlink, nothing we could do about it anyways. */
  1101. if (options->PidFile && options->command == CMD_RUN_TOR)
  1102. unlink(options->PidFile);
  1103. if (accounting_is_enabled(options))
  1104. accounting_record_bandwidth_usage(time(NULL));
  1105. tor_free_all(); /* move tor_free_all back into the ifdef below later. XXX*/
  1106. crypto_global_cleanup();
  1107. #ifdef USE_DMALLOC
  1108. dmalloc_log_unfreed();
  1109. dmalloc_shutdown();
  1110. #endif
  1111. }
  1112. /** Read/create keys as needed, and echo our fingerprint to stdout. */
  1113. static void do_list_fingerprint(void)
  1114. {
  1115. char buf[FINGERPRINT_LEN+1];
  1116. crypto_pk_env_t *k;
  1117. const char *nickname = get_options()->Nickname;
  1118. if (!server_mode(get_options())) {
  1119. printf("Clients don't have long-term identity keys. Exiting.\n");
  1120. return;
  1121. }
  1122. tor_assert(nickname);
  1123. if (init_keys() < 0) {
  1124. log_fn(LOG_ERR,"Error initializing keys; exiting");
  1125. return;
  1126. }
  1127. if (!(k = get_identity_key())) {
  1128. log_fn(LOG_ERR,"Error: missing identity key.");
  1129. return;
  1130. }
  1131. if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
  1132. log_fn(LOG_ERR, "Error computing fingerprint");
  1133. return;
  1134. }
  1135. printf("%s %s\n", nickname, buf);
  1136. }
  1137. /** Entry point for password hashing: take the desired password from
  1138. * the command line, and print its salted hash to stdout. **/
  1139. static void do_hash_password(void)
  1140. {
  1141. char output[256];
  1142. char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
  1143. crypto_rand(key, S2K_SPECIFIER_LEN-1);
  1144. key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
  1145. secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
  1146. get_options()->command_arg, strlen(get_options()->command_arg),
  1147. key);
  1148. if (base64_encode(output, sizeof(output), key, sizeof(key))<0) {
  1149. log_fn(LOG_ERR, "Unable to compute base64");
  1150. } else {
  1151. printf("%s",output);
  1152. }
  1153. }
  1154. #ifdef MS_WINDOWS_SERVICE
  1155. /** If we're compile to run as an NT service, and the service has been
  1156. * shut down, then change our current status and return 1. Else
  1157. * return 0.
  1158. */
  1159. static int
  1160. nt_service_is_stopped(void)
  1161. {
  1162. if (service_status.dwCurrentState == SERVICE_STOP_PENDING) {
  1163. service_status.dwWin32ExitCode = 0;
  1164. service_status.dwCurrentState = SERVICE_STOPPED;
  1165. SetServiceStatus(hStatus, &service_status);
  1166. return 1;
  1167. }
  1168. return 0;
  1169. }
  1170. void nt_service_control(DWORD request)
  1171. {
  1172. switch (request) {
  1173. case SERVICE_CONTROL_STOP:
  1174. case SERVICE_CONTROL_SHUTDOWN:
  1175. log(LOG_ERR, "Got stop/shutdown request; shutting down cleanly.");
  1176. service_status.dwCurrentState = SERVICE_STOP_PENDING;
  1177. return;
  1178. }
  1179. SetServiceStatus(hStatus, &service_status);
  1180. }
  1181. void nt_service_body(int argc, char **argv)
  1182. {
  1183. int err;
  1184. service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  1185. service_status.dwCurrentState = SERVICE_START_PENDING;
  1186. service_status.dwControlsAccepted =
  1187. SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  1188. service_status.dwWin32ExitCode = 0;
  1189. service_status.dwServiceSpecificExitCode = 0;
  1190. service_status.dwCheckPoint = 0;
  1191. service_status.dwWaitHint = 1000;
  1192. hStatus = RegisterServiceCtrlHandler(GENSRV_SERVICENAME, (LPHANDLER_FUNCTION) nt_service_control);
  1193. if (hStatus == 0) {
  1194. // failed;
  1195. return;
  1196. }
  1197. err = tor_init(backup_argc, backup_argv); // refactor this part out of tor_main and do_main_loop
  1198. if (err) {
  1199. // failed.
  1200. service_status.dwCurrentState = SERVICE_STOPPED;
  1201. service_status.dwWin32ExitCode = -1;
  1202. SetServiceStatus(hStatus, &service_status);
  1203. return;
  1204. }
  1205. service_status.dwCurrentState = SERVICE_RUNNING;
  1206. SetServiceStatus(hStatus, &service_status);
  1207. do_main_loop();
  1208. tor_cleanup();
  1209. return;
  1210. }
  1211. void nt_service_main(void)
  1212. {
  1213. SERVICE_TABLE_ENTRY table[2];
  1214. DWORD result = 0;
  1215. table[0].lpServiceName = GENSRV_SERVICENAME;
  1216. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
  1217. table[1].lpServiceName = NULL;
  1218. table[1].lpServiceProc = NULL;
  1219. if (!StartServiceCtrlDispatcher(table)) {
  1220. result = GetLastError();
  1221. printf("Error was %d\n",result);
  1222. if (result == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
  1223. if (tor_init(backup_argc, backup_argv) < 0)
  1224. return;
  1225. switch (get_options()->command) {
  1226. case CMD_RUN_TOR:
  1227. do_main_loop();
  1228. break;
  1229. case CMD_LIST_FINGERPRINT:
  1230. do_list_fingerprint();
  1231. break;
  1232. case CMD_HASH_PASSWORD:
  1233. do_hash_password();
  1234. break;
  1235. default:
  1236. log_fn(LOG_ERR, "Illegal command number %d: internal error.", get_options()->command);
  1237. }
  1238. tor_cleanup();
  1239. }
  1240. }
  1241. }
  1242. int nt_service_install()
  1243. {
  1244. /* XXXX Problems with NT services:
  1245. * 1. The configuration file needs to be in the same directory as the .exe
  1246. *
  1247. * 2. The exe and the configuration file can't be on any directory path
  1248. * that contains a space.
  1249. * mje - you can quote the string (i.e., "c:\program files")
  1250. *
  1251. * 3. Ideally, there should be one EXE that can either run as a
  1252. * separate process (as now) or that can install and run itself
  1253. * as an NT service. I have no idea how hard this is.
  1254. * mje - should be done. It can install and run itself as a service
  1255. *
  1256. * Notes about developing NT services:
  1257. *
  1258. * 1. Don't count on your CWD. If an absolute path is not given, the
  1259. * fopen() function goes wrong.
  1260. * 2. The parameters given to the nt_service_body() function differ
  1261. * from those given to main() function.
  1262. */
  1263. SC_HANDLE hSCManager = NULL;
  1264. SC_HANDLE hService = NULL;
  1265. SERVICE_DESCRIPTION sdBuff;
  1266. TCHAR szPath[_MAX_PATH];
  1267. TCHAR szDrive[_MAX_DRIVE];
  1268. TCHAR szDir[_MAX_DIR];
  1269. char cmd1[] = " -f ";
  1270. char cmd2[] = "\\torrc";
  1271. char *command;
  1272. int len = 0;
  1273. if (0 == GetModuleFileName(NULL, szPath, MAX_PATH))
  1274. return 0;
  1275. _tsplitpath(szPath, szDrive, szDir, NULL, NULL);
  1276. /* Account for the extra quotes */
  1277. //len = _MAX_PATH + strlen(cmd1) + _MAX_DRIVE + _MAX_DIR + strlen(cmd2);
  1278. len = _MAX_PATH + strlen(cmd1) + _MAX_DRIVE + _MAX_DIR + strlen(cmd2) + 64;
  1279. command = tor_malloc(len);
  1280. /* Create a quoted command line, like "c:\with spaces\tor.exe" -f
  1281. * "c:\with spaces\tor.exe"
  1282. */
  1283. if (tor_snprintf(command, len, "\"%s\" --nt-service -f \"%s%storrc\"",
  1284. szPath, szDrive, szDir)<0) {
  1285. printf("Failed: tor_snprinf()\n");
  1286. free(command);
  1287. return 0;
  1288. }
  1289. if ((hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
  1290. printf("Failed: OpenSCManager()\n");
  1291. free(command);
  1292. return 0;
  1293. }
  1294. /* 1/26/2005 mje
  1295. * - changed the service start type to auto
  1296. * - and changed the lpPassword param to "" instead of NULL as per an
  1297. * MSDN article.
  1298. */
  1299. if ((hService = CreateService(hSCManager, GENSRV_SERVICENAME, GENSRV_DISPLAYNAME,
  1300. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  1301. SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, command,
  1302. NULL, NULL, NULL, NULL, "")) == NULL) {
  1303. printf("Failed: CreateService()\n");
  1304. CloseServiceHandle(hSCManager);
  1305. free(command);
  1306. return 0;
  1307. }
  1308. /* Start the service initially, so you don't have to muck with it in the SCM
  1309. */
  1310. /* Set the service's description */
  1311. sdBuff.lpDescription = GENSRV_DESCRIPTION;
  1312. ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &sdBuff);
  1313. /* Start the service, so you don't have to muck with it in the SCM */
  1314. if (StartService(hService, 0, NULL)) {
  1315. /* Loop until the service has finished attempting to start */
  1316. while (QueryServiceStatus(hService, &service_status) &&
  1317. service_status.dwCurrentState == SERVICE_START_PENDING)
  1318. Sleep(500);
  1319. /* Check if it started successfully or not */
  1320. if (service_status.dwCurrentState == SERVICE_RUNNING)
  1321. printf("Service installed and started successfully.\n");
  1322. else
  1323. printf("Service installed, but failed to start.\n");
  1324. } else {
  1325. printf("Service installed, but failed to start.\n");
  1326. }
  1327. CloseServiceHandle(hService);
  1328. CloseServiceHandle(hSCManager);
  1329. tor_free(command);
  1330. return 0;
  1331. }
  1332. int nt_service_remove()
  1333. {
  1334. SC_HANDLE hSCManager = NULL;
  1335. SC_HANDLE hService = NULL;
  1336. SERVICE_STATUS service_status;
  1337. BOOL result = FALSE;
  1338. if ((hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
  1339. printf("Failed: OpenSCManager()\n");
  1340. return 0;
  1341. }
  1342. if ((hService = OpenService(hSCManager, GENSRV_SERVICENAME, SERVICE_ALL_ACCESS)) == NULL) {
  1343. printf("Failed: OpenService()\n");
  1344. CloseServiceHandle(hSCManager);
  1345. return 0;
  1346. }
  1347. result = ControlService(hService, SERVICE_CONTROL_STOP, &service_status);
  1348. if (result) {
  1349. while (QueryServiceStatus(hService, &service_status))
  1350. {
  1351. if (service_status.dwCurrentState == SERVICE_STOP_PENDING)
  1352. Sleep(500);
  1353. else
  1354. break;
  1355. }
  1356. if (DeleteService(hService))
  1357. printf("Removed service successfully\n");
  1358. else
  1359. printf("Failed: DeleteService()\n");
  1360. } else {
  1361. result = DeleteService(hService);
  1362. if (result)
  1363. printf("Removed service successfully\n");
  1364. else
  1365. printf("Failed: DeleteService()\n");
  1366. }
  1367. CloseServiceHandle(hService);
  1368. CloseServiceHandle(hSCManager);
  1369. return 0;
  1370. }
  1371. #endif
  1372. int tor_main(int argc, char *argv[]) {
  1373. #ifdef MS_WINDOWS_SERVICE
  1374. backup_argv = argv;
  1375. backup_argc = argc;
  1376. if ((argc >= 2) && !strcmp(argv[1], "-install"))
  1377. return nt_service_install();
  1378. if ((argc >= 2) && !strcmp(argv[1], "-remove"))
  1379. return nt_service_remove();
  1380. if ((argc >= 2) && !strcmp(argv[1], "--nt-service")) {
  1381. nt_service_main();
  1382. return 0;
  1383. }
  1384. #endif
  1385. if (tor_init(argc, argv)<0)
  1386. return -1;
  1387. switch (get_options()->command) {
  1388. case CMD_RUN_TOR:
  1389. #ifdef MS_WINDOWS_SERVICE
  1390. service_status.dwCurrentState = SERVICE_RUNNING;
  1391. #endif
  1392. do_main_loop();
  1393. break;
  1394. case CMD_LIST_FINGERPRINT:
  1395. do_list_fingerprint();
  1396. break;
  1397. case CMD_HASH_PASSWORD:
  1398. do_hash_password();
  1399. break;
  1400. default:
  1401. log_fn(LOG_ERR, "Illegal command number %d: internal error.",
  1402. get_options()->command);
  1403. }
  1404. tor_cleanup();
  1405. return -1;
  1406. }