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. log_fn(LOG_NOTICE,"Network down? Failing connection to '%s:%d'.",
  407. conn->socks_request->address, conn->socks_request->port);
  408. connection_close_unattached_ap(conn, END_STREAM_REASON_NET_UNREACHABLE);
  409. }
  410. }
  411. static INLINE int
  412. get_dir_fetch_period(or_options_t *options)
  413. {
  414. if (options->DirFetchPeriod)
  415. /* Value from config file. */
  416. return options->DirFetchPeriod;
  417. else if (options->DirPort)
  418. /* Default for directory server */
  419. return 20*60;
  420. else
  421. /* Default for average user. */
  422. return 40*60;
  423. }
  424. static INLINE int
  425. get_status_fetch_period(or_options_t *options)
  426. {
  427. if (options->StatusFetchPeriod)
  428. /* Value from config file. */
  429. return options->StatusFetchPeriod;
  430. else if (options->DirPort)
  431. /* Default for directory server */
  432. return 15*60;
  433. else
  434. /* Default for average user. */
  435. return 30*60;
  436. }
  437. /** This function is called whenever we successfully pull down a directory.
  438. * If <b>identity_digest</b> is defined, it contains the digest of the
  439. * router that just gave us this directory. */
  440. void directory_has_arrived(time_t now, char *identity_digest) {
  441. or_options_t *options = get_options();
  442. log_fn(LOG_INFO, "A directory has arrived.");
  443. has_fetched_directory=1;
  444. /* Don't try to upload or download anything for a while
  445. * after the directory we had when we started.
  446. */
  447. if (!time_to_fetch_directory)
  448. time_to_fetch_directory = now + get_dir_fetch_period(options);
  449. if (!time_to_force_upload_descriptor)
  450. time_to_force_upload_descriptor = now + options->DirPostPeriod;
  451. if (!time_to_fetch_running_routers)
  452. time_to_fetch_running_routers = now + get_status_fetch_period(options);
  453. if (server_mode(options) && identity_digest) {
  454. /* if this is us, then our dirport is reachable */
  455. routerinfo_t *router = router_get_by_digest(identity_digest);
  456. if (!router) // XXX
  457. log_fn(LOG_WARN,"Bug: router_get_by_digest doesn't find me.");
  458. if (router && router_is_me(router)) {
  459. router_dirport_found_reachable();
  460. }
  461. }
  462. if (server_mode(options) &&
  463. !we_are_hibernating()) { /* connect to the appropriate routers */
  464. router_retry_connections();
  465. if (identity_digest) /* we got a fresh directory */
  466. consider_testing_reachability();
  467. }
  468. }
  469. /** Perform regular maintenance tasks for a single connection. This
  470. * function gets run once per second per connection by run_scheduled_events.
  471. */
  472. static void run_connection_housekeeping(int i, time_t now) {
  473. cell_t cell;
  474. connection_t *conn = connection_array[i];
  475. or_options_t *options = get_options();
  476. if (conn->outbuf && !buf_datalen(conn->outbuf))
  477. conn->timestamp_lastempty = now;
  478. /* Expire any directory connections that haven't sent anything for 5 min */
  479. if (conn->type == CONN_TYPE_DIR &&
  480. !conn->marked_for_close &&
  481. conn->timestamp_lastwritten + 5*60 < now) {
  482. log_fn(LOG_INFO,"Expiring wedged directory conn (fd %d, purpose %d)", conn->s, conn->purpose);
  483. connection_mark_for_close(conn);
  484. return;
  485. }
  486. /* If we haven't written to an OR connection for a while, then either nuke
  487. the connection or send a keepalive, depending. */
  488. if (connection_speaks_cells(conn) &&
  489. now >= conn->timestamp_lastwritten + options->KeepalivePeriod) {
  490. routerinfo_t *router = router_get_by_digest(conn->identity_digest);
  491. if (!connection_state_is_open(conn)) {
  492. log_fn(LOG_INFO,"Expiring non-open OR connection to %d (%s:%d).",
  493. i,conn->address, conn->port);
  494. connection_mark_for_close(conn);
  495. conn->hold_open_until_flushed = 1;
  496. } else if (we_are_hibernating() && !circuit_get_by_conn(conn) &&
  497. !buf_datalen(conn->outbuf)) {
  498. log_fn(LOG_INFO,"Expiring non-used OR connection to %d (%s:%d) [Hibernating or exiting].",
  499. i,conn->address, conn->port);
  500. connection_mark_for_close(conn);
  501. conn->hold_open_until_flushed = 1;
  502. } else if (!clique_mode(options) && !circuit_get_by_conn(conn) &&
  503. (!router || !server_mode(options) || !router_is_clique_mode(router))) {
  504. log_fn(LOG_INFO,"Expiring non-used OR connection to %d (%s:%d) [Not in clique mode].",
  505. i,conn->address, conn->port);
  506. connection_mark_for_close(conn);
  507. conn->hold_open_until_flushed = 1;
  508. } else if (
  509. now >= conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
  510. now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
  511. log_fn(LOG_NOTICE,"Expiring stuck OR connection to %d (%s:%d). (%d bytes to flush; %d seconds since last write)",
  512. i, conn->address, conn->port,
  513. (int)buf_datalen(conn->outbuf),
  514. (int)(now-conn->timestamp_lastwritten));
  515. connection_mark_for_close(conn);
  516. } else {
  517. /* either in clique mode, or we've got a circuit. send a padding cell. */
  518. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  519. conn->address, conn->port);
  520. memset(&cell,0,sizeof(cell_t));
  521. cell.command = CELL_PADDING;
  522. connection_or_write_cell_to_buf(&cell, conn);
  523. }
  524. }
  525. }
  526. /** Perform regular maintenance tasks. This function gets run once per
  527. * second by prepare_for_poll.
  528. */
  529. static void run_scheduled_events(time_t now) {
  530. static time_t last_rotated_certificate = 0;
  531. static time_t time_to_check_listeners = 0;
  532. static time_t time_to_check_descriptor = 0;
  533. or_options_t *options = get_options();
  534. int i;
  535. /** 0. See if we've been asked to shut down and our timeout has
  536. * expired; or if our bandwidth limits are exhausted and we
  537. * should hibernate; or if it's time to wake up from hibernation.
  538. */
  539. consider_hibernation(now);
  540. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  541. * shut down and restart all cpuworkers, and update the directory if
  542. * necessary.
  543. */
  544. if (server_mode(options) &&
  545. get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  546. log_fn(LOG_INFO,"Rotating onion key.");
  547. rotate_onion_key();
  548. cpuworkers_rotate();
  549. if (router_rebuild_descriptor(1)<0) {
  550. log_fn(LOG_WARN, "Couldn't rebuild router descriptor");
  551. }
  552. if (advertised_server_mode())
  553. router_upload_dir_desc_to_dirservers(0);
  554. }
  555. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  556. if (!last_rotated_certificate)
  557. last_rotated_certificate = now;
  558. if (last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
  559. log_fn(LOG_INFO,"Rotating tls context.");
  560. if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
  561. MAX_SSL_KEY_LIFETIME) < 0) {
  562. log_fn(LOG_WARN, "Error reinitializing TLS context");
  563. /* XXX is it a bug here, that we just keep going? */
  564. }
  565. last_rotated_certificate = now;
  566. /* XXXX We should rotate TLS connections as well; this code doesn't change
  567. * them at all. */
  568. }
  569. /** 1c. If we have to change the accounting interval or record
  570. * bandwidth used in this accounting interval, do so. */
  571. if (accounting_is_enabled(options))
  572. accounting_run_housekeeping(now);
  573. /** 2. Periodically, we consider getting a new directory, getting a
  574. * new running-routers list, and/or force-uploading our descriptor
  575. * (if we've passed our internal checks). */
  576. if (time_to_fetch_directory < now) {
  577. time_t next_status_fetch;
  578. /* purge obsolete entries */
  579. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  580. if (authdir_mode(options)) {
  581. /* We're a directory; dump any old descriptors. */
  582. dirserv_remove_old_servers(ROUTER_MAX_AGE);
  583. }
  584. if (server_mode(options) && !we_are_hibernating()) {
  585. /* dirservers try to reconnect, in case connections have failed;
  586. * and normal servers try to reconnect to dirservers */
  587. router_retry_connections();
  588. }
  589. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
  590. time_to_fetch_directory = now + get_dir_fetch_period(options);
  591. next_status_fetch = now + get_status_fetch_period(options);
  592. if (time_to_fetch_running_routers < next_status_fetch) {
  593. time_to_fetch_running_routers = next_status_fetch;
  594. }
  595. /* Also, take this chance to remove old information from rephist. */
  596. rep_history_clean(now-24*60*60);
  597. }
  598. if (time_to_fetch_running_routers < now) {
  599. if (!authdir_mode(options)) {
  600. directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST, NULL, 1);
  601. }
  602. time_to_fetch_running_routers = now + get_status_fetch_period(options);
  603. }
  604. if (time_to_force_upload_descriptor < now) {
  605. consider_publishable_server(now, 1);
  606. rend_cache_clean(); /* this should go elsewhere? */
  607. time_to_force_upload_descriptor = now + options->DirPostPeriod;
  608. }
  609. /* 2b. Once per minute, regenerate and upload the descriptor if the old
  610. * one is inaccurate. */
  611. if (time_to_check_descriptor < now) {
  612. time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
  613. consider_publishable_server(now, 0);
  614. /* also, check religiously for reachability, if it's within the first
  615. * 20 minutes of our uptime. */
  616. if (server_mode(options) &&
  617. 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. !check_whether_ports_reachable() &&
  701. stats_n_seconds_working / TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT !=
  702. (stats_n_seconds_working+seconds_elapsed) /
  703. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
  704. /* every 20 minutes, check and complain if necessary */
  705. routerinfo_t *me = router_get_my_routerinfo();
  706. log_fn(LOG_WARN,"Your server (%s:%d) has not managed to confirm that it is reachable. Please check your firewalls, ports, address, etc.",
  707. me ? me->address : options->Address, options->ORPort);
  708. }
  709. /* if more than 10s have elapsed, probably the clock jumped: doesn't count. */
  710. if (seconds_elapsed < 100)
  711. stats_n_seconds_working += seconds_elapsed;
  712. else
  713. circuit_note_clock_jumped(seconds_elapsed);
  714. assert_all_pending_dns_resolves_ok();
  715. run_scheduled_events(now.tv_sec);
  716. assert_all_pending_dns_resolves_ok();
  717. current_second = now.tv_sec; /* remember which second it is, for next time */
  718. #if 0
  719. for (i=0;i<nfds;i++) {
  720. conn = connection_array[i];
  721. if (connection_has_pending_tls_data(conn) &&
  722. connection_is_reading(conn)) {
  723. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  724. return; /* has pending bytes to read; don't let poll wait. */
  725. }
  726. }
  727. #endif
  728. if (evtimer_add(timeout_event, &one_second))
  729. log_fn(LOG_ERR,
  730. "Error from libevent when setting one-second timeout event");
  731. }
  732. /** Called when we get a SIGHUP: reload configuration files and keys,
  733. * retry all connections, re-upload all descriptors, and so on. */
  734. static int do_hup(void) {
  735. char keydir[512];
  736. or_options_t *options = get_options();
  737. log_fn(LOG_NOTICE,"Received sighup. Reloading config.");
  738. has_completed_circuit=0;
  739. if (accounting_is_enabled(options))
  740. accounting_record_bandwidth_usage(time(NULL));
  741. addressmap_clear_transient();
  742. /* first, reload config variables, in case they've changed */
  743. /* no need to provide argc/v, they've been cached inside init_from_config */
  744. if (init_from_config(0, NULL) < 0) {
  745. log_fn(LOG_ERR,"Reading config failed--see warnings above. For usage, try -h.");
  746. return -1;
  747. }
  748. options = get_options(); /* they have changed now */
  749. if (authdir_mode(options)) {
  750. /* reload the approved-routers file */
  751. tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", options->DataDirectory);
  752. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  753. if (dirserv_parse_fingerprint_file(keydir) < 0) {
  754. log_fn(LOG_NOTICE, "Error reloading fingerprints. Continuing with old list.");
  755. }
  756. }
  757. /* Fetch a new directory. Even authdirservers do this. */
  758. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
  759. if (server_mode(options)) {
  760. const char *descriptor;
  761. /* Restart cpuworker and dnsworker processes, so they get up-to-date
  762. * configuration options. */
  763. cpuworkers_rotate();
  764. dnsworkers_rotate();
  765. /* Rebuild fresh descriptor, but leave old one on failure. */
  766. router_rebuild_descriptor(1);
  767. descriptor = router_get_my_descriptor();
  768. if (!descriptor) {
  769. log_fn(LOG_WARN,"No descriptor to save.");
  770. return 0;
  771. }
  772. tor_snprintf(keydir,sizeof(keydir),"%s/router.desc",
  773. options->DataDirectory);
  774. log_fn(LOG_INFO,"Saving descriptor to %s...",keydir);
  775. if (write_str_to_file(keydir, descriptor, 0)) {
  776. return 0;
  777. }
  778. }
  779. return 0;
  780. }
  781. /** Tor main loop. */
  782. static int do_main_loop(void) {
  783. int loop_result;
  784. /* load the private keys, if we're supposed to have them, and set up the
  785. * TLS context. */
  786. if (! identity_key_is_set()) {
  787. if (init_keys() < 0) {
  788. log_fn(LOG_ERR,"Error initializing keys; exiting");
  789. return -1;
  790. }
  791. }
  792. /* Set up our buckets */
  793. connection_bucket_init();
  794. stats_prev_global_read_bucket = global_read_bucket;
  795. stats_prev_global_write_bucket = global_write_bucket;
  796. /* load the routers file, or assign the defaults. */
  797. if (router_reload_router_list()) {
  798. return -1;
  799. }
  800. if (authdir_mode(get_options())) {
  801. /* the directory is already here, run startup things */
  802. router_retry_connections();
  803. }
  804. if (server_mode(get_options())) {
  805. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  806. cpu_init();
  807. }
  808. /* set up once-a-second callback. */
  809. second_elapsed_callback(0,0,NULL);
  810. for (;;) {
  811. if (nt_service_is_stopped())
  812. return 0;
  813. /* poll until we have an event, or the second ends */
  814. loop_result = event_dispatch();
  815. /* let catch() handle things like ^c, and otherwise don't worry about it */
  816. if (loop_result < 0) {
  817. int e = errno;
  818. /* let the program survive things like ^z */
  819. if (e != EINTR) {
  820. log_fn(LOG_ERR,"event poll failed: %s [%d]",
  821. tor_socket_strerror(e), e);
  822. return -1;
  823. } else {
  824. log_fn(LOG_DEBUG,"event poll interrupted.");
  825. /* You can't trust the results of this poll(). Go back to the
  826. * top of the big for loop. */
  827. continue;
  828. }
  829. }
  830. /* refilling buckets and sending cells happens at the beginning of the
  831. * next iteration of the loop, inside prepare_for_poll()
  832. * XXXX No longer so.
  833. */
  834. }
  835. }
  836. /** Used to implement the SIGNAL control command: if we accept
  837. * <b>the_signal</b> as a remote pseudo-signal, then act on it and
  838. * return 0. Else return -1. */
  839. /* We don't re-use catch() here because:
  840. * 1. We handle a different set of signals than those allowed in catch.
  841. * 2. Platforms without signal() are unlikely to define SIGfoo.
  842. * 3. The control spec is defined to use fixed numeric signal values
  843. * which just happen to match the unix values.
  844. */
  845. int
  846. control_signal_act(int the_signal)
  847. {
  848. switch (the_signal)
  849. {
  850. case 1:
  851. signal_callback(0,0,(void*)(uintptr_t)SIGHUP);
  852. break;
  853. case 2:
  854. signal_callback(0,0,(void*)(uintptr_t)SIGINT);
  855. break;
  856. case 10:
  857. signal_callback(0,0,(void*)(uintptr_t)SIGUSR1);
  858. break;
  859. case 12:
  860. signal_callback(0,0,(void*)(uintptr_t)SIGUSR2);
  861. break;
  862. case 15:
  863. signal_callback(0,0,(void*)(uintptr_t)SIGTERM);
  864. break;
  865. default:
  866. return -1;
  867. }
  868. return 0;
  869. }
  870. static void signal_callback(int fd, short events, void *arg)
  871. {
  872. uintptr_t sig = (uintptr_t)arg;
  873. switch (sig)
  874. {
  875. case SIGTERM:
  876. log(LOG_ERR,"Catching signal TERM, exiting cleanly.");
  877. tor_cleanup();
  878. exit(0);
  879. break;
  880. case SIGINT:
  881. if (!server_mode(get_options())) { /* do it now */
  882. log(LOG_NOTICE,"Interrupt: exiting cleanly.");
  883. tor_cleanup();
  884. exit(0);
  885. }
  886. hibernate_begin_shutdown();
  887. break;
  888. #ifdef SIGPIPE
  889. case SIGPIPE:
  890. log(LOG_NOTICE,"Caught sigpipe. Ignoring.");
  891. break;
  892. #endif
  893. case SIGUSR1:
  894. /* prefer to log it at INFO, but make sure we always see it */
  895. dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
  896. break;
  897. case SIGUSR2:
  898. switch_logs_debug();
  899. log(LOG_NOTICE,"Caught USR2. Going to loglevel debug.");
  900. break;
  901. case SIGHUP:
  902. if (do_hup() < 0) {
  903. log_fn(LOG_WARN,"Restart failed (config error?). Exiting.");
  904. tor_cleanup();
  905. exit(1);
  906. }
  907. break;
  908. #ifdef SIGCHLD
  909. case SIGCHLD:
  910. while (waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more zombies */
  911. break;
  912. #endif
  913. }
  914. }
  915. /** Write all statistics to the log, with log level 'severity'. Called
  916. * in response to a SIGUSR1. */
  917. static void
  918. dumpstats(int severity) {
  919. int i;
  920. connection_t *conn;
  921. time_t now = time(NULL);
  922. time_t elapsed;
  923. log(severity, "Dumping stats:");
  924. for (i=0;i<nfds;i++) {
  925. conn = connection_array[i];
  926. log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  927. i, conn->s, conn->type, CONN_TYPE_TO_STRING(conn->type),
  928. conn->state, conn_state_to_string[conn->type][conn->state], (int)(now - conn->timestamp_created));
  929. if (!connection_is_listener(conn)) {
  930. log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
  931. log(severity,"Conn %d: %d bytes waiting on inbuf (last read %d secs ago)",i,
  932. (int)buf_datalen(conn->inbuf),
  933. (int)(now - conn->timestamp_lastread));
  934. log(severity,"Conn %d: %d bytes waiting on outbuf (last written %d secs ago)",i,
  935. (int)buf_datalen(conn->outbuf), (int)(now - conn->timestamp_lastwritten));
  936. }
  937. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
  938. }
  939. log(severity,
  940. "Cells processed: %10lu padding\n"
  941. " %10lu create\n"
  942. " %10lu created\n"
  943. " %10lu relay\n"
  944. " (%10lu relayed)\n"
  945. " (%10lu delivered)\n"
  946. " %10lu destroy",
  947. stats_n_padding_cells_processed,
  948. stats_n_create_cells_processed,
  949. stats_n_created_cells_processed,
  950. stats_n_relay_cells_processed,
  951. stats_n_relay_cells_relayed,
  952. stats_n_relay_cells_delivered,
  953. stats_n_destroy_cells_processed);
  954. if (stats_n_data_cells_packaged)
  955. log(severity,"Average packaged cell fullness: %2.3f%%",
  956. 100*(((double)stats_n_data_bytes_packaged) /
  957. (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  958. if (stats_n_data_cells_received)
  959. log(severity,"Average delivered cell fullness: %2.3f%%",
  960. 100*(((double)stats_n_data_bytes_received) /
  961. (stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  962. if (now - time_of_process_start >= 0)
  963. elapsed = now - time_of_process_start;
  964. else
  965. elapsed = 0;
  966. if (elapsed) {
  967. log(severity,
  968. "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
  969. U64_PRINTF_ARG(stats_n_bytes_read),
  970. (int)elapsed,
  971. (int) (stats_n_bytes_read/elapsed));
  972. log(severity,
  973. "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
  974. U64_PRINTF_ARG(stats_n_bytes_written),
  975. (int)elapsed,
  976. (int) (stats_n_bytes_written/elapsed));
  977. }
  978. rep_hist_dump_stats(now,severity);
  979. rend_service_dump_stats(severity);
  980. }
  981. /** Called by exit() as we shut down the process.
  982. */
  983. static void exit_function(void)
  984. {
  985. /* NOTE: If we ever daemonize, this gets called immediately. That's
  986. * okay for now, because we only use this on Windows. */
  987. #ifdef MS_WINDOWS
  988. WSACleanup();
  989. #endif
  990. }
  991. /** Set up the signal handlers for either parent or child. */
  992. void handle_signals(int is_parent)
  993. {
  994. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  995. int i;
  996. static int signals[] = {
  997. SIGINT, /* do a controlled slow shutdown */
  998. SIGTERM, /* to terminate now */
  999. SIGPIPE, /* otherwise sigpipe kills us */
  1000. SIGUSR1, /* dump stats */
  1001. SIGUSR2, /* go to loglevel debug */
  1002. SIGHUP, /* to reload config, retry conns, etc */
  1003. #ifdef SIGXFSZ
  1004. SIGXFSZ, /* handle file-too-big resource exhaustion */
  1005. #endif
  1006. SIGCHLD, /* handle dns/cpu workers that exit */
  1007. -1 };
  1008. static struct event signal_events[16]; /* bigger than it has to be. */
  1009. if (is_parent) {
  1010. for (i = 0; signals[i] >= 0; ++i) {
  1011. signal_set(&signal_events[i], signals[i], signal_callback,
  1012. (void*)(uintptr_t)signals[i]);
  1013. if (signal_add(&signal_events[i], NULL))
  1014. log_fn(LOG_WARN, "Error from libevent when adding event for signal %d",
  1015. signals[i]);
  1016. }
  1017. } else {
  1018. struct sigaction action;
  1019. action.sa_flags = 0;
  1020. sigemptyset(&action.sa_mask);
  1021. action.sa_handler = SIG_IGN;
  1022. sigaction(SIGINT, &action, NULL);
  1023. sigaction(SIGTERM, &action, NULL);
  1024. sigaction(SIGPIPE, &action, NULL);
  1025. sigaction(SIGUSR1, &action, NULL);
  1026. sigaction(SIGUSR2, &action, NULL);
  1027. sigaction(SIGHUP, &action, NULL);
  1028. #ifdef SIGXFSZ
  1029. sigaction(SIGXFSZ, &action, NULL);
  1030. #endif
  1031. }
  1032. #endif /* signal stuff */
  1033. }
  1034. /** Main entry point for the Tor command-line client.
  1035. */
  1036. static int tor_init(int argc, char *argv[]) {
  1037. time_of_process_start = time(NULL);
  1038. closeable_connection_lst = smartlist_create();
  1039. /* Initialize the history structures. */
  1040. rep_hist_init();
  1041. /* Initialize the service cache. */
  1042. rend_cache_init();
  1043. addressmap_init(); /* Init the client dns cache. Do it always, since it's cheap. */
  1044. /* give it somewhere to log to initially */
  1045. add_temp_log();
  1046. log_fn(LOG_NOTICE,"Tor v%s. This is experimental software. Do not rely on it for strong anonymity.",VERSION);
  1047. if (network_init()<0) {
  1048. log_fn(LOG_ERR,"Error initializing network; exiting.");
  1049. return -1;
  1050. }
  1051. atexit(exit_function);
  1052. if (init_from_config(argc,argv) < 0) {
  1053. log_fn(LOG_ERR,"Reading config failed--see warnings above. For usage, try -h.");
  1054. return -1;
  1055. }
  1056. #ifndef MS_WINDOWS
  1057. if (geteuid()==0)
  1058. log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
  1059. #endif
  1060. /* only spawn dns handlers if we're a router */
  1061. if (server_mode(get_options()) && get_options()->command == CMD_RUN_TOR) {
  1062. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  1063. /* XXX really, this should get moved to do_main_loop */
  1064. }
  1065. handle_signals(1);
  1066. crypto_global_init();
  1067. crypto_seed_rng();
  1068. return 0;
  1069. }
  1070. /** Free all memory that we might have allocated somewhere.
  1071. * Helps us find the real leaks with dmalloc and the like.
  1072. *
  1073. * Also valgrind should then report 0 reachable in its
  1074. * leak report */
  1075. void tor_free_all(void)
  1076. {
  1077. routerlist_free_current();
  1078. free_trusted_dir_servers();
  1079. addressmap_free_all();
  1080. free_socks_policy();
  1081. free_dir_policy();
  1082. dirserv_free_all();
  1083. rend_service_free_all();
  1084. rend_cache_free_all();
  1085. rep_hist_free_all();
  1086. dns_free_all();
  1087. clear_pending_onions();
  1088. circuit_free_all();
  1089. connection_free_all();
  1090. config_free_all();
  1091. router_free_all_keys();
  1092. tor_tls_free_all();
  1093. /* stuff in main.c */
  1094. smartlist_free(closeable_connection_lst);
  1095. close_logs(); /* free log strings. do this last so logs keep working. */
  1096. }
  1097. /** Do whatever cleanup is necessary before shutting Tor down. */
  1098. void tor_cleanup(void) {
  1099. or_options_t *options = get_options();
  1100. /* Remove our pid file. We don't care if there was an error when we
  1101. * unlink, nothing we could do about it anyways. */
  1102. if (options->PidFile && options->command == CMD_RUN_TOR)
  1103. unlink(options->PidFile);
  1104. if (accounting_is_enabled(options))
  1105. accounting_record_bandwidth_usage(time(NULL));
  1106. tor_free_all(); /* move tor_free_all back into the ifdef below later. XXX*/
  1107. crypto_global_cleanup();
  1108. #ifdef USE_DMALLOC
  1109. dmalloc_log_unfreed();
  1110. dmalloc_shutdown();
  1111. #endif
  1112. }
  1113. /** Read/create keys as needed, and echo our fingerprint to stdout. */
  1114. static void do_list_fingerprint(void)
  1115. {
  1116. char buf[FINGERPRINT_LEN+1];
  1117. crypto_pk_env_t *k;
  1118. const char *nickname = get_options()->Nickname;
  1119. if (!server_mode(get_options())) {
  1120. printf("Clients don't have long-term identity keys. Exiting.\n");
  1121. return;
  1122. }
  1123. tor_assert(nickname);
  1124. if (init_keys() < 0) {
  1125. log_fn(LOG_ERR,"Error initializing keys; exiting");
  1126. return;
  1127. }
  1128. if (!(k = get_identity_key())) {
  1129. log_fn(LOG_ERR,"Error: missing identity key.");
  1130. return;
  1131. }
  1132. if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
  1133. log_fn(LOG_ERR, "Error computing fingerprint");
  1134. return;
  1135. }
  1136. printf("%s %s\n", nickname, buf);
  1137. }
  1138. /** Entry point for password hashing: take the desired password from
  1139. * the command line, and print its salted hash to stdout. **/
  1140. static void do_hash_password(void)
  1141. {
  1142. char output[256];
  1143. char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
  1144. crypto_rand(key, S2K_SPECIFIER_LEN-1);
  1145. key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
  1146. secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
  1147. get_options()->command_arg, strlen(get_options()->command_arg),
  1148. key);
  1149. if (base64_encode(output, sizeof(output), key, sizeof(key))<0) {
  1150. log_fn(LOG_ERR, "Unable to compute base64");
  1151. } else {
  1152. printf("%s",output);
  1153. }
  1154. }
  1155. #ifdef MS_WINDOWS_SERVICE
  1156. /** If we're compile to run as an NT service, and the service has been
  1157. * shut down, then change our current status and return 1. Else
  1158. * return 0.
  1159. */
  1160. static int
  1161. nt_service_is_stopped(void)
  1162. {
  1163. if (service_status.dwCurrentState == SERVICE_STOP_PENDING) {
  1164. service_status.dwWin32ExitCode = 0;
  1165. service_status.dwCurrentState = SERVICE_STOPPED;
  1166. SetServiceStatus(hStatus, &service_status);
  1167. return 1;
  1168. }
  1169. return 0;
  1170. }
  1171. void nt_service_control(DWORD request)
  1172. {
  1173. switch (request) {
  1174. case SERVICE_CONTROL_STOP:
  1175. case SERVICE_CONTROL_SHUTDOWN:
  1176. log(LOG_ERR, "Got stop/shutdown request; shutting down cleanly.");
  1177. service_status.dwCurrentState = SERVICE_STOP_PENDING;
  1178. return;
  1179. }
  1180. SetServiceStatus(hStatus, &service_status);
  1181. }
  1182. void nt_service_body(int argc, char **argv)
  1183. {
  1184. int err;
  1185. service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  1186. service_status.dwCurrentState = SERVICE_START_PENDING;
  1187. service_status.dwControlsAccepted =
  1188. SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  1189. service_status.dwWin32ExitCode = 0;
  1190. service_status.dwServiceSpecificExitCode = 0;
  1191. service_status.dwCheckPoint = 0;
  1192. service_status.dwWaitHint = 1000;
  1193. hStatus = RegisterServiceCtrlHandler(GENSRV_SERVICENAME, (LPHANDLER_FUNCTION) nt_service_control);
  1194. if (hStatus == 0) {
  1195. // failed;
  1196. return;
  1197. }
  1198. err = tor_init(backup_argc, backup_argv); // refactor this part out of tor_main and do_main_loop
  1199. if (err) {
  1200. // failed.
  1201. service_status.dwCurrentState = SERVICE_STOPPED;
  1202. service_status.dwWin32ExitCode = -1;
  1203. SetServiceStatus(hStatus, &service_status);
  1204. return;
  1205. }
  1206. service_status.dwCurrentState = SERVICE_RUNNING;
  1207. SetServiceStatus(hStatus, &service_status);
  1208. do_main_loop();
  1209. tor_cleanup();
  1210. return;
  1211. }
  1212. void nt_service_main(void)
  1213. {
  1214. SERVICE_TABLE_ENTRY table[2];
  1215. DWORD result = 0;
  1216. table[0].lpServiceName = GENSRV_SERVICENAME;
  1217. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
  1218. table[1].lpServiceName = NULL;
  1219. table[1].lpServiceProc = NULL;
  1220. if (!StartServiceCtrlDispatcher(table)) {
  1221. result = GetLastError();
  1222. printf("Error was %d\n",result);
  1223. if (result == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
  1224. if (tor_init(backup_argc, backup_argv) < 0)
  1225. return;
  1226. switch (get_options()->command) {
  1227. case CMD_RUN_TOR:
  1228. do_main_loop();
  1229. break;
  1230. case CMD_LIST_FINGERPRINT:
  1231. do_list_fingerprint();
  1232. break;
  1233. case CMD_HASH_PASSWORD:
  1234. do_hash_password();
  1235. break;
  1236. default:
  1237. log_fn(LOG_ERR, "Illegal command number %d: internal error.", get_options()->command);
  1238. }
  1239. tor_cleanup();
  1240. }
  1241. }
  1242. }
  1243. int nt_service_install()
  1244. {
  1245. /* XXXX Problems with NT services:
  1246. * 1. The configuration file needs to be in the same directory as the .exe
  1247. *
  1248. * 2. The exe and the configuration file can't be on any directory path
  1249. * that contains a space.
  1250. * mje - you can quote the string (i.e., "c:\program files")
  1251. *
  1252. * 3. Ideally, there should be one EXE that can either run as a
  1253. * separate process (as now) or that can install and run itself
  1254. * as an NT service. I have no idea how hard this is.
  1255. * mje - should be done. It can install and run itself as a service
  1256. *
  1257. * Notes about developing NT services:
  1258. *
  1259. * 1. Don't count on your CWD. If an absolute path is not given, the
  1260. * fopen() function goes wrong.
  1261. * 2. The parameters given to the nt_service_body() function differ
  1262. * from those given to main() function.
  1263. */
  1264. SC_HANDLE hSCManager = NULL;
  1265. SC_HANDLE hService = NULL;
  1266. SERVICE_DESCRIPTION sdBuff;
  1267. TCHAR szPath[_MAX_PATH];
  1268. TCHAR szDrive[_MAX_DRIVE];
  1269. TCHAR szDir[_MAX_DIR];
  1270. char cmd1[] = " -f ";
  1271. char cmd2[] = "\\torrc";
  1272. char *command;
  1273. int len = 0;
  1274. if (0 == GetModuleFileName(NULL, szPath, MAX_PATH))
  1275. return 0;
  1276. _tsplitpath(szPath, szDrive, szDir, NULL, NULL);
  1277. /* Account for the extra quotes */
  1278. //len = _MAX_PATH + strlen(cmd1) + _MAX_DRIVE + _MAX_DIR + strlen(cmd2);
  1279. len = _MAX_PATH + strlen(cmd1) + _MAX_DRIVE + _MAX_DIR + strlen(cmd2) + 64;
  1280. command = tor_malloc(len);
  1281. /* Create a quoted command line, like "c:\with spaces\tor.exe" -f
  1282. * "c:\with spaces\tor.exe"
  1283. */
  1284. if (tor_snprintf(command, len, "\"%s\" --nt-service -f \"%s%storrc\"",
  1285. szPath, szDrive, szDir)<0) {
  1286. printf("Failed: tor_snprinf()\n");
  1287. free(command);
  1288. return 0;
  1289. }
  1290. if ((hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
  1291. printf("Failed: OpenSCManager()\n");
  1292. free(command);
  1293. return 0;
  1294. }
  1295. /* 1/26/2005 mje
  1296. * - changed the service start type to auto
  1297. * - and changed the lpPassword param to "" instead of NULL as per an
  1298. * MSDN article.
  1299. */
  1300. if ((hService = CreateService(hSCManager, GENSRV_SERVICENAME, GENSRV_DISPLAYNAME,
  1301. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  1302. SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, command,
  1303. NULL, NULL, NULL, NULL, "")) == NULL) {
  1304. printf("Failed: CreateService()\n");
  1305. CloseServiceHandle(hSCManager);
  1306. free(command);
  1307. return 0;
  1308. }
  1309. /* Start the service initially, so you don't have to muck with it in the SCM
  1310. */
  1311. /* Set the service's description */
  1312. sdBuff.lpDescription = GENSRV_DESCRIPTION;
  1313. ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &sdBuff);
  1314. /* Start the service, so you don't have to muck with it in the SCM */
  1315. if (StartService(hService, 0, NULL)) {
  1316. /* Loop until the service has finished attempting to start */
  1317. while (QueryServiceStatus(hService, &service_status) &&
  1318. service_status.dwCurrentState == SERVICE_START_PENDING)
  1319. Sleep(500);
  1320. /* Check if it started successfully or not */
  1321. if (service_status.dwCurrentState == SERVICE_RUNNING)
  1322. printf("Service installed and started successfully.\n");
  1323. else
  1324. printf("Service installed, but failed to start.\n");
  1325. } else {
  1326. printf("Service installed, but failed to start.\n");
  1327. }
  1328. CloseServiceHandle(hService);
  1329. CloseServiceHandle(hSCManager);
  1330. tor_free(command);
  1331. return 0;
  1332. }
  1333. int nt_service_remove()
  1334. {
  1335. SC_HANDLE hSCManager = NULL;
  1336. SC_HANDLE hService = NULL;
  1337. SERVICE_STATUS service_status;
  1338. BOOL result = FALSE;
  1339. if ((hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
  1340. printf("Failed: OpenSCManager()\n");
  1341. return 0;
  1342. }
  1343. if ((hService = OpenService(hSCManager, GENSRV_SERVICENAME, SERVICE_ALL_ACCESS)) == NULL) {
  1344. printf("Failed: OpenService()\n");
  1345. CloseServiceHandle(hSCManager);
  1346. return 0;
  1347. }
  1348. result = ControlService(hService, SERVICE_CONTROL_STOP, &service_status);
  1349. if (result) {
  1350. while (QueryServiceStatus(hService, &service_status))
  1351. {
  1352. if (service_status.dwCurrentState == SERVICE_STOP_PENDING)
  1353. Sleep(500);
  1354. else
  1355. break;
  1356. }
  1357. if (DeleteService(hService))
  1358. printf("Removed service successfully\n");
  1359. else
  1360. printf("Failed: DeleteService()\n");
  1361. } else {
  1362. result = DeleteService(hService);
  1363. if (result)
  1364. printf("Removed service successfully\n");
  1365. else
  1366. printf("Failed: DeleteService()\n");
  1367. }
  1368. CloseServiceHandle(hService);
  1369. CloseServiceHandle(hSCManager);
  1370. return 0;
  1371. }
  1372. #endif
  1373. int tor_main(int argc, char *argv[]) {
  1374. #ifdef MS_WINDOWS_SERVICE
  1375. backup_argv = argv;
  1376. backup_argc = argc;
  1377. if ((argc >= 2) && !strcmp(argv[1], "-install"))
  1378. return nt_service_install();
  1379. if ((argc >= 2) && !strcmp(argv[1], "-remove"))
  1380. return nt_service_remove();
  1381. if ((argc >= 2) && !strcmp(argv[1], "--nt-service")) {
  1382. nt_service_main();
  1383. return 0;
  1384. }
  1385. #endif
  1386. if (tor_init(argc, argv)<0)
  1387. return -1;
  1388. switch (get_options()->command) {
  1389. case CMD_RUN_TOR:
  1390. #ifdef MS_WINDOWS_SERVICE
  1391. service_status.dwCurrentState = SERVICE_RUNNING;
  1392. #endif
  1393. do_main_loop();
  1394. break;
  1395. case CMD_LIST_FINGERPRINT:
  1396. do_list_fingerprint();
  1397. break;
  1398. case CMD_HASH_PASSWORD:
  1399. do_hash_password();
  1400. break;
  1401. default:
  1402. log_fn(LOG_ERR, "Illegal command number %d: internal error.",
  1403. get_options()->command);
  1404. }
  1405. tor_cleanup();
  1406. return -1;
  1407. }