main.c 54 KB

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