main.c 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char main_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file main.c
  10. * \brief Toplevel module. Handles signals, multiplexes between
  11. * connections, implements main loop, and drives scheduled events.
  12. **/
  13. #include "or.h"
  14. #ifdef USE_DMALLOC
  15. #include <dmalloc.h>
  16. #endif
  17. /********* PROTOTYPES **********/
  18. static void dumpmemusage(int severity);
  19. static void dumpstats(int severity); /* log stats */
  20. static void conn_read_callback(int fd, short event, void *_conn);
  21. static void conn_write_callback(int fd, short event, void *_conn);
  22. static void signal_callback(int fd, short events, void *arg);
  23. static void second_elapsed_callback(int fd, short event, void *args);
  24. static int conn_close_if_marked(int i);
  25. /********* START VARIABLES **********/
  26. int global_read_bucket; /**< Max number of bytes I can read this second. */
  27. int global_write_bucket; /**< Max number of bytes I can write this second. */
  28. /** What was the read bucket before the last call to prepare_for_pool?
  29. * (used to determine how many bytes we've read). */
  30. static int stats_prev_global_read_bucket;
  31. /** What was the write bucket before the last call to prepare_for_pool?
  32. * (used to determine how many bytes we've written). */
  33. static int stats_prev_global_write_bucket;
  34. /** How many bytes have we read/written since we started the process? */
  35. static uint64_t stats_n_bytes_read = 0;
  36. static uint64_t stats_n_bytes_written = 0;
  37. /** What time did this process start up? */
  38. long time_of_process_start = 0;
  39. /** How many seconds have we been running? */
  40. long stats_n_seconds_working = 0;
  41. /** When do we next download a directory? */
  42. static time_t time_to_fetch_directory = 0;
  43. /** When do we next download a running-routers summary? */
  44. static time_t time_to_fetch_running_routers = 0;
  45. /** Array of all open connections. The first n_conns elements are valid. */
  46. static connection_t *connection_array[MAXCONNECTIONS+1] =
  47. { NULL };
  48. static smartlist_t *closeable_connection_lst = NULL;
  49. static int n_conns=0; /**< Number of connections currently active. */
  50. /** We set this to 1 when we've opened a circuit, so we can print a log
  51. * entry to inform the user that Tor is working. */
  52. int has_completed_circuit=0;
  53. #ifdef MS_WINDOWS
  54. #define MS_WINDOWS_SERVICE
  55. #endif
  56. #ifdef MS_WINDOWS_SERVICE
  57. #include <tchar.h>
  58. #define GENSRV_SERVICENAME TEXT("tor")
  59. #define GENSRV_DISPLAYNAME TEXT("Tor Win32 Service")
  60. #define GENSRV_DESCRIPTION \
  61. TEXT("Provides an anonymous Internet communication system")
  62. // Cheating: using the pre-defined error codes, tricks Windows into displaying
  63. // a semi-related human-readable error message if startup fails as
  64. // opposed to simply scaring people with Error: 0xffffffff
  65. #define NT_SERVICE_ERROR_NO_TORRC ERROR_FILE_NOT_FOUND
  66. #define NT_SERVICE_ERROR_TORINIT_FAILED ERROR_EXCEPTION_IN_SERVICE
  67. SERVICE_STATUS service_status;
  68. SERVICE_STATUS_HANDLE hStatus;
  69. static char **backup_argv;
  70. static int backup_argc;
  71. static int nt_service_is_stopped(void);
  72. static char* nt_strerror(uint32_t errnum);
  73. #else
  74. #define nt_service_is_stopped() (0)
  75. #endif
  76. /** If our router descriptor ever goes this long without being regenerated
  77. * because something changed, we force an immediate regenerate-and-upload. */
  78. #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
  79. /** How often do we check whether part of our router info has changed in a way
  80. * that would require an upload? */
  81. #define CHECK_DESCRIPTOR_INTERVAL (60)
  82. /** How often do we (as a router) check whether our IP address has changed? */
  83. #define CHECK_IPADDRESS_INTERVAL (15*60)
  84. /** How often do we check buffers for empty space that can be deallocated? */
  85. #define BUF_SHRINK_INTERVAL (60)
  86. /** How often do we check for router descriptors that we should download? */
  87. #define DESCRIPTOR_RETRY_INTERVAL (10)
  88. /** How often do we 'forgive' undownloadable router descriptors and attempt
  89. * to download them again? */
  90. #define DESCRIPTOR_FAILURE_RESET_INTERVAL (60*60)
  91. /** How often do we add more entropy to OpenSSL's RNG pool? */
  92. #define ENTROPY_INTERVAL (60*60)
  93. /** How long do we let a directory connection stall before expiring it? */
  94. #define DIR_CONN_MAX_STALL (5*60)
  95. /** How old do we let a connection to an OR get before deciding it's
  96. * obsolete? */
  97. #define TIME_BEFORE_OR_CONN_IS_OBSOLETE (60*60*24*7)
  98. /** How long do we let OR connections handshake before we decide that
  99. * they are obsolete? */
  100. #define TLS_HANDSHAKE_TIMEOUT (60)
  101. /********* END VARIABLES ************/
  102. /****************************************************************************
  103. *
  104. * This section contains accessors and other methods on the connection_array
  105. * variables (which are global within this file and unavailable outside it).
  106. *
  107. ****************************************************************************/
  108. /** Add <b>conn</b> to the array of connections that we can poll on. The
  109. * connection's socket must be set; the connection starts out
  110. * non-reading and non-writing.
  111. */
  112. int
  113. connection_add(connection_t *conn)
  114. {
  115. tor_assert(conn);
  116. tor_assert(conn->s >= 0);
  117. if (n_conns >= get_options()->_ConnLimit-1) {
  118. log_warn(LD_NET,"Failing because we have %d connections already. Please "
  119. "raise your ulimit -n.", n_conns);
  120. return -1;
  121. }
  122. tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
  123. conn->conn_array_index = n_conns;
  124. connection_array[n_conns] = conn;
  125. conn->read_event = tor_malloc_zero(sizeof(struct event));
  126. conn->write_event = tor_malloc_zero(sizeof(struct event));
  127. event_set(conn->read_event, conn->s, EV_READ|EV_PERSIST,
  128. conn_read_callback, conn);
  129. event_set(conn->write_event, conn->s, EV_WRITE|EV_PERSIST,
  130. conn_write_callback, conn);
  131. n_conns++;
  132. log_debug(LD_NET,"new conn type %s, socket %d, n_conns %d.",
  133. conn_type_to_string(conn->type), conn->s, n_conns);
  134. return 0;
  135. }
  136. /** Remove the connection from the global list, and remove the
  137. * corresponding poll entry. Calling this function will shift the last
  138. * connection (if any) into the position occupied by conn.
  139. */
  140. int
  141. connection_remove(connection_t *conn)
  142. {
  143. int current_index;
  144. tor_assert(conn);
  145. tor_assert(n_conns>0);
  146. log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
  147. conn->s, conn_type_to_string(conn->type), n_conns-1);
  148. tor_assert(conn->conn_array_index >= 0);
  149. current_index = conn->conn_array_index;
  150. if (current_index == n_conns-1) { /* this is the end */
  151. n_conns--;
  152. return 0;
  153. }
  154. connection_unregister(conn);
  155. /* replace this one with the one at the end */
  156. n_conns--;
  157. connection_array[current_index] = connection_array[n_conns];
  158. connection_array[current_index]->conn_array_index = current_index;
  159. return 0;
  160. }
  161. /** If it's an edge conn, remove it from the list
  162. * of conn's on this circuit. If it's not on an edge,
  163. * flush and send destroys for all circuits on this conn.
  164. *
  165. * If <b>remove</b> is non-zero, then remove it from the
  166. * connection_array and closeable_connection_lst.
  167. *
  168. * Then free it.
  169. */
  170. static void
  171. connection_unlink(connection_t *conn, int remove)
  172. {
  173. circuit_about_to_close_connection(conn);
  174. connection_about_to_close_connection(conn);
  175. if (remove) {
  176. connection_remove(conn);
  177. }
  178. smartlist_remove(closeable_connection_lst, conn);
  179. if (conn->type == CONN_TYPE_EXIT) {
  180. assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
  181. }
  182. if (conn->type == CONN_TYPE_OR) {
  183. if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
  184. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  185. }
  186. connection_free(conn);
  187. }
  188. /** Schedule <b>conn</b> to be closed. **/
  189. void
  190. add_connection_to_closeable_list(connection_t *conn)
  191. {
  192. tor_assert(!smartlist_isin(closeable_connection_lst, conn));
  193. tor_assert(conn->marked_for_close);
  194. assert_connection_ok(conn, time(NULL));
  195. smartlist_add(closeable_connection_lst, conn);
  196. }
  197. /** Return 1 if conn is on the closeable list, else return 0. */
  198. int
  199. connection_is_on_closeable_list(connection_t *conn)
  200. {
  201. return smartlist_isin(closeable_connection_lst, conn);
  202. }
  203. /** Return true iff conn is in the current poll array. */
  204. int
  205. connection_in_array(connection_t *conn)
  206. {
  207. int i;
  208. for (i=0; i<n_conns; ++i) {
  209. if (conn==connection_array[i])
  210. return 1;
  211. }
  212. return 0;
  213. }
  214. /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
  215. * to the length of the array. <b>*array</b> and <b>*n</b> must not
  216. * be modified.
  217. */
  218. void
  219. get_connection_array(connection_t ***array, int *n)
  220. {
  221. *array = connection_array;
  222. *n = n_conns;
  223. }
  224. /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
  225. * mask is a bitmask whose bits are EV_READ and EV_WRITE.)
  226. */
  227. void
  228. connection_watch_events(connection_t *conn, short events)
  229. {
  230. int r;
  231. tor_assert(conn);
  232. tor_assert(conn->read_event);
  233. tor_assert(conn->write_event);
  234. if (events & EV_READ) {
  235. r = event_add(conn->read_event, NULL);
  236. } else {
  237. r = event_del(conn->read_event);
  238. }
  239. if (r<0)
  240. log_warn(LD_NET,
  241. "Error from libevent setting read event state for %d to "
  242. "%swatched: %s",
  243. conn->s, (events & EV_READ)?"":"un",
  244. tor_socket_strerror(tor_socket_errno(conn->s)));
  245. if (events & EV_WRITE) {
  246. r = event_add(conn->write_event, NULL);
  247. } else {
  248. r = event_del(conn->write_event);
  249. }
  250. if (r<0)
  251. log_warn(LD_NET,
  252. "Error from libevent setting read event state for %d to "
  253. "%swatched: %s",
  254. conn->s, (events & EV_WRITE)?"":"un",
  255. tor_socket_strerror(tor_socket_errno(conn->s)));
  256. }
  257. /** Return true iff <b>conn</b> is listening for read events. */
  258. int
  259. connection_is_reading(connection_t *conn)
  260. {
  261. tor_assert(conn);
  262. return conn->read_event && event_pending(conn->read_event, EV_READ, NULL);
  263. }
  264. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  265. void
  266. connection_stop_reading(connection_t *conn)
  267. {
  268. tor_assert(conn);
  269. tor_assert(conn->read_event);
  270. log_debug(LD_NET,"connection_stop_reading() called.");
  271. if (event_del(conn->read_event))
  272. log_warn(LD_NET, "Error from libevent setting read event state for %d "
  273. "to unwatched: %s",
  274. conn->s,
  275. tor_socket_strerror(tor_socket_errno(conn->s)));
  276. }
  277. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  278. void
  279. connection_start_reading(connection_t *conn)
  280. {
  281. tor_assert(conn);
  282. tor_assert(conn->read_event);
  283. if (event_add(conn->read_event, NULL))
  284. log_warn(LD_NET, "Error from libevent setting read event state for %d "
  285. "to watched: %s",
  286. conn->s,
  287. tor_socket_strerror(tor_socket_errno(conn->s)));
  288. }
  289. /** Return true iff <b>conn</b> is listening for write events. */
  290. int
  291. connection_is_writing(connection_t *conn)
  292. {
  293. tor_assert(conn);
  294. return conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL);
  295. }
  296. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  297. void
  298. connection_stop_writing(connection_t *conn)
  299. {
  300. tor_assert(conn);
  301. tor_assert(conn->write_event);
  302. if (event_del(conn->write_event))
  303. log_warn(LD_NET, "Error from libevent setting write event state for %d "
  304. "to unwatched: %s",
  305. conn->s,
  306. tor_socket_strerror(tor_socket_errno(conn->s)));
  307. }
  308. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  309. void
  310. connection_start_writing(connection_t *conn)
  311. {
  312. tor_assert(conn);
  313. tor_assert(conn->write_event);
  314. if (event_add(conn->write_event, NULL))
  315. log_warn(LD_NET, "Error from libevent setting write event state for %d "
  316. "to watched: %s",
  317. conn->s,
  318. tor_socket_strerror(tor_socket_errno(conn->s)));
  319. }
  320. /** Close all connections that have been scheduled to get closed */
  321. static void
  322. close_closeable_connections(void)
  323. {
  324. int i;
  325. for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
  326. connection_t *conn = smartlist_get(closeable_connection_lst, i);
  327. if (conn->conn_array_index < 0) {
  328. connection_unlink(conn, 0); /* blow it away right now */
  329. } else {
  330. if (!conn_close_if_marked(conn->conn_array_index))
  331. ++i;
  332. }
  333. }
  334. }
  335. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  336. * some data to read. */
  337. static void
  338. conn_read_callback(int fd, short event, void *_conn)
  339. {
  340. connection_t *conn = _conn;
  341. (void)fd;
  342. (void)event;
  343. log_debug(LD_NET,"socket %d wants to read.",conn->s);
  344. assert_connection_ok(conn, time(NULL));
  345. if (connection_handle_read(conn) < 0) {
  346. if (!conn->marked_for_close) {
  347. #ifndef MS_WINDOWS
  348. log_warn(LD_BUG,"Bug: unhandled error on read for %s connection "
  349. "(fd %d); removing",
  350. conn_type_to_string(conn->type), conn->s);
  351. tor_fragile_assert();
  352. #endif
  353. if (CONN_IS_EDGE(conn))
  354. connection_edge_end_errno(TO_EDGE_CONN(conn),
  355. TO_EDGE_CONN(conn)->cpath_layer);
  356. connection_mark_for_close(conn);
  357. }
  358. }
  359. assert_connection_ok(conn, time(NULL));
  360. if (smartlist_len(closeable_connection_lst))
  361. close_closeable_connections();
  362. }
  363. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  364. * some data to write. */
  365. static void
  366. conn_write_callback(int fd, short events, void *_conn)
  367. {
  368. connection_t *conn = _conn;
  369. (void)fd;
  370. (void)events;
  371. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",conn->s));
  372. assert_connection_ok(conn, time(NULL));
  373. if (connection_handle_write(conn) < 0) {
  374. if (!conn->marked_for_close) {
  375. /* this connection is broken. remove it. */
  376. log_fn(LOG_WARN,LD_BUG,
  377. "Bug: unhandled error on write for %s connection (fd %d); removing",
  378. conn_type_to_string(conn->type), conn->s);
  379. tor_fragile_assert();
  380. if (CONN_IS_EDGE(conn)) {
  381. /* otherwise we cry wolf about duplicate close */
  382. conn->edge_has_sent_end = 1;
  383. }
  384. /* XXX do we need a close-immediate here, so we don't try to flush? */
  385. connection_mark_for_close(conn);
  386. }
  387. }
  388. assert_connection_ok(conn, time(NULL));
  389. if (smartlist_len(closeable_connection_lst))
  390. close_closeable_connections();
  391. }
  392. /** If the connection at connection_array[i] is marked for close, then:
  393. * - If it has data that it wants to flush, try to flush it.
  394. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  395. * true, then leave the connection open and return.
  396. * - Otherwise, remove the connection from connection_array and from
  397. * all other lists, close it, and free it.
  398. * Returns 1 if the connection was closed, 0 otherwise.
  399. */
  400. static int
  401. conn_close_if_marked(int i)
  402. {
  403. connection_t *conn;
  404. int retval;
  405. conn = connection_array[i];
  406. if (!conn->marked_for_close)
  407. return 0; /* nothing to see here, move along */
  408. assert_connection_ok(conn, time(NULL));
  409. assert_all_pending_dns_resolves_ok();
  410. log_debug(LD_NET,"Cleaning up connection (fd %d).",conn->s);
  411. if (conn->s >= 0 && connection_wants_to_flush(conn)) {
  412. /* s == -1 means it's an incomplete edge connection, or that the socket
  413. * has already been closed as unflushable. */
  414. int sz = connection_bucket_write_limit(conn);
  415. if (!conn->hold_open_until_flushed)
  416. log_info(LD_NET,
  417. "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
  418. "to flush %d bytes. (Marked at %s:%d)",
  419. escaped_safe_str(conn->address),
  420. conn->s, conn_type_to_string(conn->type), conn->state,
  421. (int)conn->outbuf_flushlen,
  422. conn->marked_for_close_file, conn->marked_for_close);
  423. if (connection_speaks_cells(conn)) {
  424. if (conn->state == OR_CONN_STATE_OPEN) {
  425. retval = flush_buf_tls(TO_OR_CONN(conn)->tls, conn->outbuf, sz,
  426. &conn->outbuf_flushlen);
  427. } else
  428. retval = -1; /* never flush non-open broken tls connections */
  429. } else {
  430. retval = flush_buf(conn->s, conn->outbuf, sz, &conn->outbuf_flushlen);
  431. }
  432. if (retval >= 0 && /* Technically, we could survive things like
  433. TLS_WANT_WRITE here. But don't bother for now. */
  434. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  435. if (retval > 0)
  436. LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
  437. "Holding conn (fd %d) open for more flushing.",
  438. conn->s));
  439. /* XXX should we reset timestamp_lastwritten here? */
  440. return 0;
  441. }
  442. if (connection_wants_to_flush(conn)) {
  443. int severity;
  444. if (conn->type == CONN_TYPE_EXIT ||
  445. (conn->type == CONN_TYPE_OR && server_mode(get_options())) ||
  446. (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER))
  447. severity = LOG_INFO;
  448. else
  449. severity = LOG_NOTICE;
  450. log_fn(severity, LD_NET, "Something wrong with your network connection? "
  451. "We tried to write %d bytes to addr %s (fd %d, type %s, state %d)"
  452. " but timed out. (Marked at %s:%d)",
  453. (int)buf_datalen(conn->outbuf),
  454. escaped_safe_str(conn->address), conn->s,
  455. conn_type_to_string(conn->type), conn->state,
  456. conn->marked_for_close_file,
  457. conn->marked_for_close);
  458. }
  459. }
  460. connection_unlink(conn, 1); /* unlink, remove, free */
  461. return 1;
  462. }
  463. /** We've just tried every dirserver we know about, and none of
  464. * them were reachable. Assume the network is down. Change state
  465. * so next time an application connection arrives we'll delay it
  466. * and try another directory fetch. Kill off all the circuit_wait
  467. * streams that are waiting now, since they will all timeout anyway.
  468. */
  469. void
  470. directory_all_unreachable(time_t now)
  471. {
  472. connection_t *conn;
  473. (void)now;
  474. stats_n_seconds_working=0; /* reset it */
  475. while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
  476. AP_CONN_STATE_CIRCUIT_WAIT))) {
  477. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  478. log_notice(LD_NET,
  479. "Is your network connection down? "
  480. "Failing connection to '%s:%d'.",
  481. safe_str(edge_conn->socks_request->address),
  482. edge_conn->socks_request->port);
  483. connection_mark_unattached_ap(edge_conn,
  484. END_STREAM_REASON_NET_UNREACHABLE);
  485. }
  486. }
  487. /** This function is called whenever we successfully pull down some new
  488. * network statuses or server descriptors. */
  489. void
  490. directory_info_has_arrived(time_t now, int from_cache)
  491. {
  492. or_options_t *options = get_options();
  493. if (!router_have_minimum_dir_info()) {
  494. log(LOG_NOTICE, LD_DIR,
  495. "I learned some more directory information, but not enough to "
  496. "build a circuit.");
  497. update_router_descriptor_downloads(now);
  498. return;
  499. }
  500. if (server_mode(options) && !we_are_hibernating() && !from_cache &&
  501. (has_completed_circuit || !any_predicted_circuits(now)))
  502. consider_testing_reachability(1, 1);
  503. }
  504. /** Perform regular maintenance tasks for a single connection. This
  505. * function gets run once per second per connection by run_scheduled_events.
  506. */
  507. static void
  508. run_connection_housekeeping(int i, time_t now)
  509. {
  510. cell_t cell;
  511. connection_t *conn = connection_array[i];
  512. or_options_t *options = get_options();
  513. or_connection_t *or_conn;
  514. if (conn->outbuf && !buf_datalen(conn->outbuf) && conn->type == CONN_TYPE_OR)
  515. TO_OR_CONN(conn)->timestamp_lastempty = now;
  516. if (conn->marked_for_close) {
  517. /* nothing to do here */
  518. return;
  519. }
  520. /* Expire any directory connections that haven't been active (sent
  521. * if a server or received if a client) for 5 min */
  522. if (conn->type == CONN_TYPE_DIR &&
  523. ((DIR_CONN_IS_SERVER(conn) &&
  524. conn->timestamp_lastwritten + DIR_CONN_MAX_STALL < now) ||
  525. (!DIR_CONN_IS_SERVER(conn) &&
  526. conn->timestamp_lastread + DIR_CONN_MAX_STALL < now))) {
  527. log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
  528. conn->s, conn->purpose);
  529. /* This check is temporary; it's to let us know whether we should consider
  530. * parsing partial serverdesc responses. */
  531. if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  532. buf_datalen(conn->inbuf)>=1024) {
  533. log_info(LD_DIR,"Trying to extract information from wedged server desc "
  534. "download.");
  535. connection_dir_reached_eof(TO_DIR_CONN(conn));
  536. } else {
  537. connection_mark_for_close(conn);
  538. }
  539. return;
  540. }
  541. if (!connection_speaks_cells(conn))
  542. return; /* we're all done here, the rest is just for OR conns */
  543. or_conn = TO_OR_CONN(conn);
  544. if (!conn->or_is_obsolete) {
  545. if (conn->timestamp_created + TIME_BEFORE_OR_CONN_IS_OBSOLETE < now) {
  546. log_info(LD_OR,
  547. "Marking OR conn to %s:%d obsolete (fd %d, %d secs old).",
  548. conn->address, conn->port, conn->s,
  549. (int)(now - conn->timestamp_created));
  550. conn->or_is_obsolete = 1;
  551. } else {
  552. or_connection_t *best =
  553. connection_or_get_by_identity_digest(or_conn->identity_digest);
  554. if (best && best != or_conn &&
  555. (conn->state == OR_CONN_STATE_OPEN ||
  556. now > conn->timestamp_created + TLS_HANDSHAKE_TIMEOUT)) {
  557. /* We only mark as obsolete connections that already are in
  558. * OR_CONN_STATE_OPEN, i.e. that have finished their TLS handshaking.
  559. * This is necessary because authorities judge whether a router is
  560. * reachable based on whether they were able to TLS handshake with it
  561. * recently. Without this check we would expire connections too
  562. * early for router->last_reachable to be updated.
  563. */
  564. log_info(LD_OR,
  565. "Marking duplicate conn to %s:%d obsolete "
  566. "(fd %d, %d secs old).",
  567. conn->address, conn->port, conn->s,
  568. (int)(now - conn->timestamp_created));
  569. conn->or_is_obsolete = 1;
  570. }
  571. }
  572. }
  573. if (conn->or_is_obsolete && !or_conn->n_circuits) {
  574. /* no unmarked circs -- mark it now */
  575. log_info(LD_OR,
  576. "Expiring non-used OR connection to fd %d (%s:%d) [Obsolete].",
  577. conn->s, conn->address, conn->port);
  578. connection_mark_for_close(conn);
  579. conn->hold_open_until_flushed = 1;
  580. return;
  581. }
  582. /* If we haven't written to an OR connection for a while, then either nuke
  583. the connection or send a keepalive, depending. */
  584. if (now >= conn->timestamp_lastwritten + options->KeepalivePeriod) {
  585. routerinfo_t *router = router_get_by_digest(or_conn->identity_digest);
  586. if (!connection_state_is_open(conn)) {
  587. log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
  588. conn->s,conn->address, conn->port);
  589. connection_mark_for_close(conn);
  590. conn->hold_open_until_flushed = 1;
  591. } else if (we_are_hibernating() && !or_conn->n_circuits &&
  592. !buf_datalen(conn->outbuf)) {
  593. log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
  594. "[Hibernating or exiting].",
  595. conn->s,conn->address, conn->port);
  596. connection_mark_for_close(conn);
  597. conn->hold_open_until_flushed = 1;
  598. } else if (!clique_mode(options) && !or_conn->n_circuits &&
  599. (!router || !server_mode(options) ||
  600. !router_is_clique_mode(router))) {
  601. log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
  602. "[Not in clique mode].",
  603. conn->s,conn->address, conn->port);
  604. connection_mark_for_close(conn);
  605. conn->hold_open_until_flushed = 1;
  606. } else if (
  607. now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
  608. now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
  609. log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
  610. "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
  611. "flush; %d seconds since last write)",
  612. conn->s, conn->address, conn->port,
  613. (int)buf_datalen(conn->outbuf),
  614. (int)(now-conn->timestamp_lastwritten));
  615. connection_mark_for_close(conn);
  616. } else if (!buf_datalen(conn->outbuf)) {
  617. /* either in clique mode, or we've got a circuit. send a padding cell. */
  618. log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
  619. conn->address, conn->port);
  620. memset(&cell,0,sizeof(cell_t));
  621. cell.command = CELL_PADDING;
  622. connection_or_write_cell_to_buf(&cell, or_conn);
  623. }
  624. }
  625. }
  626. /** Perform regular maintenance tasks. This function gets run once per
  627. * second by prepare_for_poll.
  628. */
  629. static void
  630. run_scheduled_events(time_t now)
  631. {
  632. static time_t last_rotated_certificate = 0;
  633. static time_t time_to_check_listeners = 0;
  634. static time_t time_to_check_descriptor = 0;
  635. static time_t time_to_check_ipaddress = 0;
  636. static time_t time_to_shrink_buffers = 0;
  637. static time_t time_to_try_getting_descriptors = 0;
  638. static time_t time_to_reset_descriptor_failures = 0;
  639. static time_t time_to_add_entropy = 0;
  640. or_options_t *options = get_options();
  641. int i;
  642. int have_dir_info;
  643. /** 0. See if we've been asked to shut down and our timeout has
  644. * expired; or if our bandwidth limits are exhausted and we
  645. * should hibernate; or if it's time to wake up from hibernation.
  646. */
  647. consider_hibernation(now);
  648. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  649. * shut down and restart all cpuworkers, and update the directory if
  650. * necessary.
  651. */
  652. if (server_mode(options) &&
  653. get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  654. log_info(LD_GENERAL,"Rotating onion key.");
  655. rotate_onion_key();
  656. cpuworkers_rotate();
  657. if (router_rebuild_descriptor(1)<0) {
  658. log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
  659. }
  660. if (advertised_server_mode())
  661. router_upload_dir_desc_to_dirservers(0);
  662. }
  663. if (time_to_try_getting_descriptors < now) {
  664. /* XXXX Maybe we should do this every 10sec when not enough info,
  665. * and every 60sec when we have enough info -NM */
  666. update_router_descriptor_downloads(now);
  667. time_to_try_getting_descriptors = now + DESCRIPTOR_RETRY_INTERVAL;
  668. }
  669. if (time_to_reset_descriptor_failures < now) {
  670. router_reset_descriptor_download_failures();
  671. time_to_reset_descriptor_failures =
  672. now + DESCRIPTOR_FAILURE_RESET_INTERVAL;
  673. }
  674. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  675. if (!last_rotated_certificate)
  676. last_rotated_certificate = now;
  677. if (last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
  678. log_info(LD_GENERAL,"Rotating tls context.");
  679. if (tor_tls_context_new(get_identity_key(), options->Nickname,
  680. MAX_SSL_KEY_LIFETIME) < 0) {
  681. log_warn(LD_BUG, "Error reinitializing TLS context");
  682. /* XXX is it a bug here, that we just keep going? */
  683. }
  684. last_rotated_certificate = now;
  685. /* XXXX We should rotate TLS connections as well; this code doesn't change
  686. * them at all. */
  687. }
  688. if (time_to_add_entropy == 0)
  689. time_to_add_entropy = now + ENTROPY_INTERVAL;
  690. if (time_to_add_entropy < now) {
  691. /* We already seeded once, so don't die on failure. */
  692. crypto_seed_rng();
  693. time_to_add_entropy = now + ENTROPY_INTERVAL;
  694. }
  695. /** 1c. If we have to change the accounting interval or record
  696. * bandwidth used in this accounting interval, do so. */
  697. if (accounting_is_enabled(options))
  698. accounting_run_housekeeping(now);
  699. if (now % 10 == 0 && authdir_mode(options) && !we_are_hibernating()) {
  700. /* try to determine reachability */
  701. dirserv_test_reachability(0);
  702. }
  703. /** 2. Periodically, we consider getting a new directory, getting a
  704. * new running-routers list, and/or force-uploading our descriptor
  705. * (if we've passed our internal checks). */
  706. if (time_to_fetch_directory < now) {
  707. /* purge obsolete entries */
  708. routerlist_remove_old_routers();
  709. networkstatus_list_clean(now);
  710. /* Only caches actually need to fetch directories now. */
  711. if (options->DirPort && !options->V1AuthoritativeDir) {
  712. /* XXX actually, we should only do this if we want to advertise
  713. * our dirport. not simply if we configured one. -RD */
  714. if (any_trusted_dir_is_v1_authority())
  715. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
  716. }
  717. #define V1_DIR_FETCH_PERIOD (60*60)
  718. time_to_fetch_directory = now + V1_DIR_FETCH_PERIOD;
  719. /* Also, take this chance to remove old information from rephist
  720. * and the rend cache. */
  721. rep_history_clean(now - options->RephistTrackTime);
  722. rend_cache_clean();
  723. /* And while we are at it, save the state with bandwidth history
  724. * and more. */
  725. or_state_save();
  726. }
  727. /* Caches need to fetch running_routers; directory clients don't. */
  728. if (options->DirPort && time_to_fetch_running_routers < now) {
  729. if (!authdir_mode(options) || !options->V1AuthoritativeDir) {
  730. directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST, NULL, 1);
  731. }
  732. #define V1_RUNNINGROUTERS_FETCH_PERIOD (20*60)
  733. time_to_fetch_running_routers = now + V1_RUNNINGROUTERS_FETCH_PERIOD;
  734. }
  735. /* 2b. Once per minute, regenerate and upload the descriptor if the old
  736. * one is inaccurate. */
  737. if (time_to_check_descriptor < now) {
  738. time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
  739. check_descriptor_bandwidth_changed(now);
  740. if (time_to_check_ipaddress < now) {
  741. time_to_check_ipaddress = now + CHECK_IPADDRESS_INTERVAL;
  742. check_descriptor_ipaddress_changed(now);
  743. }
  744. mark_my_descriptor_dirty_if_older_than(
  745. now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL);
  746. consider_publishable_server(0);
  747. /* also, check religiously for reachability, if it's within the first
  748. * 20 minutes of our uptime. */
  749. if (server_mode(options) &&
  750. (has_completed_circuit || !any_predicted_circuits(now)) &&
  751. stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT &&
  752. !we_are_hibernating())
  753. consider_testing_reachability(1, 1);
  754. /* If any networkstatus documents are no longer recent, we need to
  755. * update all the descriptors' running status. */
  756. networkstatus_list_update_recent(now);
  757. routers_update_all_from_networkstatus();
  758. /* Also, once per minute, check whether we want to download any
  759. * networkstatus documents.
  760. */
  761. update_networkstatus_downloads(now);
  762. }
  763. /** 3a. Every second, we examine pending circuits and prune the
  764. * ones which have been pending for more than a few seconds.
  765. * We do this before step 4, so it can try building more if
  766. * it's not comfortable with the number of available circuits.
  767. */
  768. circuit_expire_building(now);
  769. /** 3b. Also look at pending streams and prune the ones that 'began'
  770. * a long time ago but haven't gotten a 'connected' yet.
  771. * Do this before step 4, so we can put them back into pending
  772. * state to be picked up by the new circuit.
  773. */
  774. connection_ap_expire_beginning();
  775. /** 3c. And expire connections that we've held open for too long.
  776. */
  777. connection_expire_held_open();
  778. /** 3d. And every 60 seconds, we relaunch listeners if any died. */
  779. if (!we_are_hibernating() && time_to_check_listeners < now) {
  780. /* 0 means "only launch the ones that died." */
  781. retry_all_listeners(0, NULL, NULL);
  782. time_to_check_listeners = now+60;
  783. }
  784. /** 4. Every second, we try a new circuit if there are no valid
  785. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  786. * that became dirty more than MaxCircuitDirtiness seconds ago,
  787. * and we make a new circ if there are no clean circuits.
  788. */
  789. have_dir_info = router_have_minimum_dir_info();
  790. if (have_dir_info && !we_are_hibernating())
  791. circuit_build_needed_circs(now);
  792. /** 5. We do housekeeping for each connection... */
  793. for (i=0;i<n_conns;i++) {
  794. run_connection_housekeeping(i, now);
  795. }
  796. if (time_to_shrink_buffers < now) {
  797. for (i=0;i<n_conns;i++) {
  798. connection_t *conn = connection_array[i];
  799. if (conn->outbuf)
  800. buf_shrink(conn->outbuf);
  801. if (conn->inbuf)
  802. buf_shrink(conn->inbuf);
  803. }
  804. time_to_shrink_buffers = now + BUF_SHRINK_INTERVAL;
  805. }
  806. /** 6. And remove any marked circuits... */
  807. circuit_close_all_marked();
  808. /** 7. And upload service descriptors if necessary. */
  809. if (has_completed_circuit && !we_are_hibernating())
  810. rend_consider_services_upload(now);
  811. /** 8. and blow away any connections that need to die. have to do this now,
  812. * because if we marked a conn for close and left its socket -1, then
  813. * we'll pass it to poll/select and bad things will happen.
  814. */
  815. close_closeable_connections();
  816. }
  817. static struct event *timeout_event = NULL;
  818. static int n_libevent_errors = 0;
  819. /** Libevent callback: invoked once every second. */
  820. static void
  821. second_elapsed_callback(int fd, short event, void *args)
  822. {
  823. static struct timeval one_second;
  824. static long current_second = 0;
  825. struct timeval now;
  826. size_t bytes_written;
  827. size_t bytes_read;
  828. int seconds_elapsed;
  829. or_options_t *options = get_options();
  830. (void)fd;
  831. (void)event;
  832. (void)args;
  833. if (!timeout_event) {
  834. timeout_event = tor_malloc_zero(sizeof(struct event));
  835. evtimer_set(timeout_event, second_elapsed_callback, NULL);
  836. one_second.tv_sec = 1;
  837. one_second.tv_usec = 0;
  838. }
  839. n_libevent_errors = 0;
  840. /* log_fn(LOG_NOTICE, "Tick."); */
  841. tor_gettimeofday(&now);
  842. /* the second has rolled over. check more stuff. */
  843. bytes_written = stats_prev_global_write_bucket - global_write_bucket;
  844. bytes_read = stats_prev_global_read_bucket - global_read_bucket;
  845. /* XXX below we get suspicious if time jumps forward more than 10
  846. * seconds, but we never notice if it jumps *back* more than 10 seconds.
  847. * This could be useful for detecting that we just NTP'ed to three
  848. * weeks ago and it will be 3 weeks and 15 minutes until any of our
  849. * events trigger.
  850. */
  851. seconds_elapsed = current_second ? (now.tv_sec - current_second) : 0;
  852. stats_n_bytes_read += bytes_read;
  853. stats_n_bytes_written += bytes_written;
  854. if (accounting_is_enabled(options))
  855. accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
  856. control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
  857. connection_bucket_refill(&now);
  858. stats_prev_global_read_bucket = global_read_bucket;
  859. stats_prev_global_write_bucket = global_write_bucket;
  860. if (server_mode(options) &&
  861. !we_are_hibernating() &&
  862. stats_n_seconds_working / TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT !=
  863. (stats_n_seconds_working+seconds_elapsed) /
  864. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
  865. /* every 20 minutes, check and complain if necessary */
  866. routerinfo_t *me = router_get_my_routerinfo();
  867. if (me && !check_whether_orport_reachable())
  868. log_warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that "
  869. "its ORPort is reachable. Please check your firewalls, ports, "
  870. "address, /etc/hosts file, etc.",
  871. me->address, me->or_port);
  872. if (me && !check_whether_dirport_reachable())
  873. log_warn(LD_CONFIG,
  874. "Your server (%s:%d) has not managed to confirm that its "
  875. "DirPort is reachable. Please check your firewalls, ports, "
  876. "address, /etc/hosts file, etc.",
  877. me->address, me->dir_port);
  878. }
  879. /** If more than this many seconds have elapsed, probably the clock
  880. * jumped: doesn't count. */
  881. #define NUM_JUMPED_SECONDS_BEFORE_WARN 10
  882. /* This used to be 100, but I cranked it down for Mike Chiussi -RD */
  883. if (seconds_elapsed < NUM_JUMPED_SECONDS_BEFORE_WARN)
  884. stats_n_seconds_working += seconds_elapsed;
  885. else
  886. circuit_note_clock_jumped(seconds_elapsed);
  887. run_scheduled_events(now.tv_sec);
  888. current_second = now.tv_sec; /* remember which second it is, for next time */
  889. #if 0
  890. if (current_second % 300 == 0) {
  891. rep_history_clean(current_second - options->RephistTrackTime);
  892. dumpmemusage(get_min_log_level()<LOG_INFO ?
  893. get_min_log_level() : LOG_INFO);
  894. }
  895. #endif
  896. if (evtimer_add(timeout_event, &one_second))
  897. log_err(LD_NET,
  898. "Error from libevent when setting one-second timeout event");
  899. }
  900. /** Called when a possibly ignorable libevent error occurs; ensures that we
  901. * don't get into an infinite loop by ignoring too many errors from
  902. * libevent. */
  903. static int
  904. got_libevent_error(void)
  905. {
  906. if (++n_libevent_errors > 8) {
  907. log_err(LD_NET, "Too many libevent errors in one second; dying");
  908. return -1;
  909. }
  910. return 0;
  911. }
  912. /** Called when we get a SIGHUP: reload configuration files and keys,
  913. * retry all connections, re-upload all descriptors, and so on. */
  914. static int
  915. do_hup(void)
  916. {
  917. or_options_t *options = get_options();
  918. log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config.");
  919. if (accounting_is_enabled(options))
  920. accounting_record_bandwidth_usage(time(NULL));
  921. router_reset_warnings();
  922. routerlist_reset_warnings();
  923. addressmap_clear_transient();
  924. /* first, reload config variables, in case they've changed */
  925. /* no need to provide argc/v, they've been cached inside init_from_config */
  926. if (options_init_from_torrc(0, NULL) < 0) {
  927. log_err(LD_CONFIG,"Reading config failed--see warnings above. "
  928. "For usage, try -h.");
  929. return -1;
  930. }
  931. options = get_options(); /* they have changed now */
  932. if (authdir_mode(options)) {
  933. /* reload the approved-routers file */
  934. if (dirserv_load_fingerprint_file() < 0) {
  935. /* warnings are logged from dirserv_load_fingerprint_file() directly */
  936. log_info(LD_GENERAL, "Error reloading fingerprints. "
  937. "Continuing with old list.");
  938. }
  939. }
  940. /* Rotate away from the old dirty circuits. This has to be done
  941. * after we've read the new options, but before we start using
  942. * circuits for directory fetches. */
  943. circuit_expire_all_dirty_circs();
  944. /* retry appropriate downloads */
  945. router_reset_status_download_failures();
  946. router_reset_descriptor_download_failures();
  947. update_networkstatus_downloads(time(NULL));
  948. /* We'll retry routerstatus downloads in about 10 seconds; no need to
  949. * force a retry there. */
  950. if (server_mode(options)) {
  951. // const char *descriptor;
  952. mark_my_descriptor_dirty();
  953. /* Restart cpuworker and dnsworker processes, so they get up-to-date
  954. * configuration options. */
  955. cpuworkers_rotate();
  956. dns_reset();
  957. #if 0
  958. const char *descriptor;
  959. char keydir[512];
  960. /* Write out a fresh descriptor, but leave old one on failure. */
  961. router_rebuild_descriptor(1);
  962. descriptor = router_get_my_descriptor();
  963. if (descriptor) {
  964. tor_snprintf(keydir,sizeof(keydir),"%s/router.desc",
  965. options->DataDirectory);
  966. log_info(LD_OR,"Saving descriptor to \"%s\"...",keydir);
  967. if (write_str_to_file(keydir, descriptor, 0)) {
  968. return 0;
  969. }
  970. }
  971. #endif
  972. }
  973. return 0;
  974. }
  975. /** Tor main loop. */
  976. static int
  977. do_main_loop(void)
  978. {
  979. int loop_result;
  980. /* initialize dns resolve map, spawn workers if needed */
  981. if (dns_init() < 0) {
  982. log_err(LD_GENERAL,"Error initializing dns subsystem; exiting");
  983. return -1;
  984. }
  985. handle_signals(1);
  986. /* load the private keys, if we're supposed to have them, and set up the
  987. * TLS context. */
  988. if (! identity_key_is_set()) {
  989. if (init_keys() < 0) {
  990. log_err(LD_GENERAL,"Error initializing keys; exiting");
  991. return -1;
  992. }
  993. }
  994. /* Set up our buckets */
  995. connection_bucket_init();
  996. stats_prev_global_read_bucket = global_read_bucket;
  997. stats_prev_global_write_bucket = global_write_bucket;
  998. /* load the routers file, or assign the defaults. */
  999. if (router_reload_router_list()) {
  1000. return -1;
  1001. }
  1002. /* load the networkstatuses. (This launches a download for new routers as
  1003. * appropriate.)
  1004. */
  1005. if (router_reload_networkstatus()) {
  1006. return -1;
  1007. }
  1008. directory_info_has_arrived(time(NULL),1);
  1009. if (authdir_mode(get_options())) {
  1010. /* the directory is already here, run startup things */
  1011. dirserv_test_reachability(1);
  1012. }
  1013. if (server_mode(get_options())) {
  1014. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  1015. cpu_init();
  1016. }
  1017. /* set up once-a-second callback. */
  1018. second_elapsed_callback(0,0,NULL);
  1019. for (;;) {
  1020. if (nt_service_is_stopped())
  1021. return 0;
  1022. #ifndef MS_WINDOWS
  1023. /* Make it easier to tell whether libevent failure is our fault or not. */
  1024. errno = 0;
  1025. #endif
  1026. /* poll until we have an event, or the second ends */
  1027. loop_result = event_dispatch();
  1028. /* let catch() handle things like ^c, and otherwise don't worry about it */
  1029. if (loop_result < 0) {
  1030. int e = tor_socket_errno(-1);
  1031. /* let the program survive things like ^z */
  1032. if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
  1033. #ifdef HAVE_EVENT_GET_METHOD
  1034. log_err(LD_NET,"libevent call with %s failed: %s [%d]",
  1035. event_get_method(), tor_socket_strerror(e), e);
  1036. #else
  1037. log_err(LD_NET,"libevent call failed: %s [%d]",
  1038. tor_socket_strerror(e), e);
  1039. #endif
  1040. return -1;
  1041. #ifndef MS_WINDOWS
  1042. } else if (e == EINVAL) {
  1043. log_warn(LD_NET, "EINVAL from libevent: should you upgrade libevent?");
  1044. if (got_libevent_error())
  1045. return -1;
  1046. #endif
  1047. } else {
  1048. if (ERRNO_IS_EINPROGRESS(e))
  1049. log_warn(LD_BUG,
  1050. "libevent call returned EINPROGRESS? Please report.");
  1051. log_debug(LD_NET,"libevent call interrupted.");
  1052. /* You can't trust the results of this poll(). Go back to the
  1053. * top of the big for loop. */
  1054. continue;
  1055. }
  1056. }
  1057. /* refilling buckets and sending cells happens at the beginning of the
  1058. * next iteration of the loop, inside prepare_for_poll()
  1059. * XXXX No longer so.
  1060. */
  1061. }
  1062. }
  1063. /* DOCDOC */
  1064. int
  1065. control_signal_check(int the_signal)
  1066. {
  1067. switch (the_signal)
  1068. {
  1069. case 1:
  1070. case 2:
  1071. case 10:
  1072. case 12:
  1073. case 15:
  1074. case SIGNEWNYM:
  1075. return 1;
  1076. default:
  1077. return 0;
  1078. }
  1079. }
  1080. /** Used to implement the SIGNAL control command: if we accept
  1081. * <b>the_signal</b> as a remote pseudo-signal, act on it. */
  1082. /* We don't re-use catch() here because:
  1083. * 1. We handle a different set of signals than those allowed in catch.
  1084. * 2. Platforms without signal() are unlikely to define SIGfoo.
  1085. * 3. The control spec is defined to use fixed numeric signal values
  1086. * which just happen to match the unix values.
  1087. */
  1088. void
  1089. control_signal_act(int the_signal)
  1090. {
  1091. switch (the_signal)
  1092. {
  1093. case 1:
  1094. signal_callback(0,0,(void*)(uintptr_t)SIGHUP);
  1095. break;
  1096. case 2:
  1097. signal_callback(0,0,(void*)(uintptr_t)SIGINT);
  1098. break;
  1099. case 10:
  1100. signal_callback(0,0,(void*)(uintptr_t)SIGUSR1);
  1101. break;
  1102. case 12:
  1103. signal_callback(0,0,(void*)(uintptr_t)SIGUSR2);
  1104. break;
  1105. case 15:
  1106. signal_callback(0,0,(void*)(uintptr_t)SIGTERM);
  1107. break;
  1108. case SIGNEWNYM:
  1109. signal_callback(0,0,(void*)(uintptr_t)SIGNEWNYM);
  1110. break;
  1111. default:
  1112. log_warn(LD_BUG, "Unrecognized signal number %d.", the_signal);
  1113. break;
  1114. }
  1115. }
  1116. /** Libevent callback: invoked when we get a signal.
  1117. */
  1118. static void
  1119. signal_callback(int fd, short events, void *arg)
  1120. {
  1121. uintptr_t sig = (uintptr_t)arg;
  1122. (void)fd;
  1123. (void)events;
  1124. switch (sig)
  1125. {
  1126. case SIGTERM:
  1127. log_err(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
  1128. tor_cleanup();
  1129. exit(0);
  1130. break;
  1131. case SIGINT:
  1132. if (!server_mode(get_options())) { /* do it now */
  1133. log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
  1134. tor_cleanup();
  1135. exit(0);
  1136. }
  1137. hibernate_begin_shutdown();
  1138. break;
  1139. #ifdef SIGPIPE
  1140. case SIGPIPE:
  1141. log_debug(LD_GENERAL,"Caught sigpipe. Ignoring.");
  1142. break;
  1143. #endif
  1144. case SIGUSR1:
  1145. /* prefer to log it at INFO, but make sure we always see it */
  1146. dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
  1147. break;
  1148. case SIGUSR2:
  1149. switch_logs_debug();
  1150. log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
  1151. "Send HUP to change back.");
  1152. break;
  1153. case SIGHUP:
  1154. if (do_hup() < 0) {
  1155. log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
  1156. tor_cleanup();
  1157. exit(1);
  1158. }
  1159. break;
  1160. #ifdef SIGCHLD
  1161. case SIGCHLD:
  1162. while (waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more
  1163. zombies */
  1164. break;
  1165. #endif
  1166. case SIGNEWNYM:
  1167. circuit_expire_all_dirty_circs();
  1168. break;
  1169. }
  1170. }
  1171. extern uint64_t buf_total_used;
  1172. extern uint64_t buf_total_alloc;
  1173. extern uint64_t rephist_total_alloc;
  1174. extern uint32_t rephist_total_num;
  1175. /**
  1176. * Write current memory usage information to the log.
  1177. */
  1178. static void
  1179. dumpmemusage(int severity)
  1180. {
  1181. log(severity, LD_GENERAL,
  1182. "In buffers: "U64_FORMAT" used/"U64_FORMAT" allocated (%d conns).",
  1183. U64_PRINTF_ARG(buf_total_used), U64_PRINTF_ARG(buf_total_alloc),
  1184. n_conns);
  1185. log(severity, LD_GENERAL, "In rephist: "U64_FORMAT" used by %d Tors.",
  1186. U64_PRINTF_ARG(rephist_total_alloc), rephist_total_num);
  1187. dump_routerlist_mem_usage(severity);
  1188. }
  1189. /** Write all statistics to the log, with log level 'severity'. Called
  1190. * in response to a SIGUSR1. */
  1191. static void
  1192. dumpstats(int severity)
  1193. {
  1194. int i;
  1195. connection_t *conn;
  1196. time_t now = time(NULL);
  1197. time_t elapsed;
  1198. log(severity, LD_GENERAL, "Dumping stats:");
  1199. for (i=0;i<n_conns;i++) {
  1200. conn = connection_array[i];
  1201. log(severity, LD_GENERAL,
  1202. "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  1203. i, conn->s, conn->type, conn_type_to_string(conn->type),
  1204. conn->state, conn_state_to_string(conn->type, conn->state),
  1205. (int)(now - conn->timestamp_created));
  1206. if (!connection_is_listener(conn)) {
  1207. log(severity,LD_GENERAL,
  1208. "Conn %d is to %s:%d.", i,
  1209. safe_str(conn->address), conn->port);
  1210. log(severity,LD_GENERAL,
  1211. "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
  1212. i,
  1213. (int)buf_datalen(conn->inbuf),
  1214. (int)buf_capacity(conn->inbuf),
  1215. (int)(now - conn->timestamp_lastread));
  1216. log(severity,LD_GENERAL,
  1217. "Conn %d: %d bytes waiting on outbuf "
  1218. "(len %d, last written %d secs ago)",i,
  1219. (int)buf_datalen(conn->outbuf),
  1220. (int)buf_capacity(conn->outbuf),
  1221. (int)(now - conn->timestamp_lastwritten));
  1222. }
  1223. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits
  1224. * using this conn */
  1225. }
  1226. log(severity, LD_NET,
  1227. "Cells processed: "U64_FORMAT" padding\n"
  1228. " "U64_FORMAT" create\n"
  1229. " "U64_FORMAT" created\n"
  1230. " "U64_FORMAT" relay\n"
  1231. " ("U64_FORMAT" relayed)\n"
  1232. " ("U64_FORMAT" delivered)\n"
  1233. " "U64_FORMAT" destroy",
  1234. U64_PRINTF_ARG(stats_n_padding_cells_processed),
  1235. U64_PRINTF_ARG(stats_n_create_cells_processed),
  1236. U64_PRINTF_ARG(stats_n_created_cells_processed),
  1237. U64_PRINTF_ARG(stats_n_relay_cells_processed),
  1238. U64_PRINTF_ARG(stats_n_relay_cells_relayed),
  1239. U64_PRINTF_ARG(stats_n_relay_cells_delivered),
  1240. U64_PRINTF_ARG(stats_n_destroy_cells_processed));
  1241. if (stats_n_data_cells_packaged)
  1242. log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
  1243. 100*(U64_TO_DBL(stats_n_data_bytes_packaged) /
  1244. U64_TO_DBL(stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  1245. if (stats_n_data_cells_received)
  1246. log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
  1247. 100*(U64_TO_DBL(stats_n_data_bytes_received) /
  1248. U64_TO_DBL(stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  1249. if (now - time_of_process_start >= 0)
  1250. elapsed = now - time_of_process_start;
  1251. else
  1252. elapsed = 0;
  1253. if (elapsed) {
  1254. log(severity, LD_NET,
  1255. "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
  1256. U64_PRINTF_ARG(stats_n_bytes_read),
  1257. (int)elapsed,
  1258. (int) (stats_n_bytes_read/elapsed));
  1259. log(severity, LD_NET,
  1260. "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
  1261. U64_PRINTF_ARG(stats_n_bytes_written),
  1262. (int)elapsed,
  1263. (int) (stats_n_bytes_written/elapsed));
  1264. }
  1265. log(severity, LD_NET, "--------------- Dumping memory information:");
  1266. dumpmemusage(severity);
  1267. rep_hist_dump_stats(now,severity);
  1268. rend_service_dump_stats(severity);
  1269. }
  1270. /** Called by exit() as we shut down the process.
  1271. */
  1272. static void
  1273. exit_function(void)
  1274. {
  1275. /* NOTE: If we ever daemonize, this gets called immediately. That's
  1276. * okay for now, because we only use this on Windows. */
  1277. #ifdef MS_WINDOWS
  1278. WSACleanup();
  1279. #endif
  1280. }
  1281. /** Set up the signal handlers for either parent or child. */
  1282. void
  1283. handle_signals(int is_parent)
  1284. {
  1285. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  1286. int i;
  1287. static int signals[] = {
  1288. SIGINT, /* do a controlled slow shutdown */
  1289. SIGTERM, /* to terminate now */
  1290. SIGPIPE, /* otherwise sigpipe kills us */
  1291. SIGUSR1, /* dump stats */
  1292. SIGUSR2, /* go to loglevel debug */
  1293. SIGHUP, /* to reload config, retry conns, etc */
  1294. #ifdef SIGXFSZ
  1295. SIGXFSZ, /* handle file-too-big resource exhaustion */
  1296. #endif
  1297. SIGCHLD, /* handle dns/cpu workers that exit */
  1298. -1 };
  1299. static struct event signal_events[16]; /* bigger than it has to be. */
  1300. if (is_parent) {
  1301. for (i = 0; signals[i] >= 0; ++i) {
  1302. signal_set(&signal_events[i], signals[i], signal_callback,
  1303. (void*)(uintptr_t)signals[i]);
  1304. if (signal_add(&signal_events[i], NULL))
  1305. log_warn(LD_BUG, "Error from libevent when adding event for signal %d",
  1306. signals[i]);
  1307. }
  1308. } else {
  1309. struct sigaction action;
  1310. action.sa_flags = 0;
  1311. sigemptyset(&action.sa_mask);
  1312. action.sa_handler = SIG_IGN;
  1313. sigaction(SIGINT, &action, NULL);
  1314. sigaction(SIGTERM, &action, NULL);
  1315. sigaction(SIGPIPE, &action, NULL);
  1316. sigaction(SIGUSR1, &action, NULL);
  1317. sigaction(SIGUSR2, &action, NULL);
  1318. sigaction(SIGHUP, &action, NULL);
  1319. #ifdef SIGXFSZ
  1320. sigaction(SIGXFSZ, &action, NULL);
  1321. #endif
  1322. }
  1323. #endif /* signal stuff */
  1324. }
  1325. /** Main entry point for the Tor command-line client.
  1326. */
  1327. static int
  1328. tor_init(int argc, char *argv[])
  1329. {
  1330. time_of_process_start = time(NULL);
  1331. if (!closeable_connection_lst)
  1332. closeable_connection_lst = smartlist_create();
  1333. /* Initialize the history structures. */
  1334. rep_hist_init();
  1335. /* Initialize the service cache. */
  1336. rend_cache_init();
  1337. addressmap_init(); /* Init the client dns cache. Do it always, since it's
  1338. * cheap. */
  1339. /* give it somewhere to log to initially */
  1340. add_temp_log();
  1341. log(LOG_NOTICE, LD_GENERAL, "Tor v%s. This is experimental software. "
  1342. "Do not rely on it for strong anonymity.",VERSION);
  1343. if (network_init()<0) {
  1344. log_err(LD_NET,"Error initializing network; exiting.");
  1345. return -1;
  1346. }
  1347. atexit(exit_function);
  1348. if (options_init_from_torrc(argc,argv) < 0) {
  1349. log_err(LD_CONFIG,"Reading config failed--see warnings above.");
  1350. return -1;
  1351. }
  1352. #ifndef MS_WINDOWS
  1353. if (geteuid()==0)
  1354. log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
  1355. "and you probably shouldn't.");
  1356. #endif
  1357. crypto_global_init(get_options()->HardwareAccel);
  1358. if (crypto_seed_rng()) {
  1359. log_err(LD_BUG, "Unable to seed random number generator. Exiting.");
  1360. return -1;
  1361. }
  1362. return 0;
  1363. }
  1364. /** Free all memory that we might have allocated somewhere.
  1365. * Helps us find the real leaks with dmalloc and the like.
  1366. *
  1367. * Also valgrind should then report 0 reachable in its
  1368. * leak report */
  1369. void
  1370. tor_free_all(int postfork)
  1371. {
  1372. routerlist_free_all();
  1373. addressmap_free_all();
  1374. set_exit_redirects(NULL); /* free the registered exit redirects */
  1375. dirserv_free_all();
  1376. rend_service_free_all();
  1377. rend_cache_free_all();
  1378. rep_hist_free_all();
  1379. dns_free_all();
  1380. clear_pending_onions();
  1381. circuit_free_all();
  1382. entry_guards_free_all();
  1383. connection_free_all();
  1384. policies_free_all();
  1385. if (!postfork) {
  1386. config_free_all();
  1387. router_free_all();
  1388. }
  1389. tor_tls_free_all();
  1390. /* stuff in main.c */
  1391. smartlist_free(closeable_connection_lst);
  1392. tor_free(timeout_event);
  1393. if (!postfork) {
  1394. close_logs(); /* free log strings. do this last so logs keep working. */
  1395. }
  1396. }
  1397. /** Do whatever cleanup is necessary before shutting Tor down. */
  1398. void
  1399. tor_cleanup(void)
  1400. {
  1401. or_options_t *options = get_options();
  1402. /* Remove our pid file. We don't care if there was an error when we
  1403. * unlink, nothing we could do about it anyways. */
  1404. if (options->command == CMD_RUN_TOR) {
  1405. if (options->PidFile)
  1406. unlink(options->PidFile);
  1407. if (accounting_is_enabled(options))
  1408. accounting_record_bandwidth_usage(time(NULL));
  1409. or_state_save();
  1410. }
  1411. tor_free_all(0); /* move tor_free_all back into the ifdef below later. XXX*/
  1412. crypto_global_cleanup();
  1413. #ifdef USE_DMALLOC
  1414. dmalloc_log_unfreed();
  1415. dmalloc_shutdown();
  1416. #endif
  1417. }
  1418. /** Read/create keys as needed, and echo our fingerprint to stdout. */
  1419. static int
  1420. do_list_fingerprint(void)
  1421. {
  1422. char buf[FINGERPRINT_LEN+1];
  1423. crypto_pk_env_t *k;
  1424. const char *nickname = get_options()->Nickname;
  1425. if (!server_mode(get_options())) {
  1426. log_err(LD_GENERAL,
  1427. "Clients don't have long-term identity keys. Exiting.\n");
  1428. return -1;
  1429. }
  1430. tor_assert(nickname);
  1431. if (init_keys() < 0) {
  1432. log_err(LD_BUG,"Error initializing keys; exiting");
  1433. return -1;
  1434. }
  1435. if (!(k = get_identity_key())) {
  1436. log_err(LD_GENERAL,"Error: missing identity key.");
  1437. return -1;
  1438. }
  1439. if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
  1440. log_err(LD_BUG, "Error computing fingerprint");
  1441. return -1;
  1442. }
  1443. printf("%s %s\n", nickname, buf);
  1444. return 0;
  1445. }
  1446. /** Entry point for password hashing: take the desired password from
  1447. * the command line, and print its salted hash to stdout. **/
  1448. static void
  1449. do_hash_password(void)
  1450. {
  1451. char output[256];
  1452. char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
  1453. crypto_rand(key, S2K_SPECIFIER_LEN-1);
  1454. key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
  1455. secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
  1456. get_options()->command_arg, strlen(get_options()->command_arg),
  1457. key);
  1458. base16_encode(output, sizeof(output), key, sizeof(key));
  1459. printf("16:%s\n",output);
  1460. }
  1461. #ifdef MS_WINDOWS_SERVICE
  1462. /** Checks if torrc is present in the same directory
  1463. * as the service executable.
  1464. * Return 1 if it is, 0 if it is not present. */
  1465. static int
  1466. nt_torrc_is_present()
  1467. {
  1468. HANDLE hFile;
  1469. TCHAR szPath[_MAX_PATH];
  1470. TCHAR szDrive[_MAX_DRIVE];
  1471. TCHAR szDir[_MAX_DIR];
  1472. char torrc[] = "torrc";
  1473. char *path_to_torrc;
  1474. int len = 0;
  1475. /* Get the service executable path */
  1476. if (0 == GetModuleFileName(NULL, szPath, MAX_PATH))
  1477. return 0;
  1478. _tsplitpath(szPath, szDrive, szDir, NULL, NULL);
  1479. /* Build the path to the torrc file */
  1480. len = _MAX_PATH + _MAX_DRIVE + _MAX_DIR + strlen(torrc) + 1;
  1481. path_to_torrc = tor_malloc(len);
  1482. if (tor_snprintf(path_to_torrc, len, "%s%s%s", szDrive, szDir, torrc)<0) {
  1483. printf("Failed: tor_snprinf()\n");
  1484. tor_free(path_to_torrc);
  1485. return 0;
  1486. }
  1487. /* See if torrc is present */
  1488. hFile = CreateFile(TEXT(path_to_torrc),
  1489. GENERIC_READ, FILE_SHARE_READ, NULL,
  1490. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
  1491. NULL);
  1492. tor_free(path_to_torrc);
  1493. if (hFile == INVALID_HANDLE_VALUE) {
  1494. return 0;
  1495. }
  1496. CloseHandle(hFile);
  1497. return 1;
  1498. }
  1499. /** If we're compile to run as an NT service, and the service has been
  1500. * shut down, then change our current status and return 1. Else
  1501. * return 0.
  1502. */
  1503. static int
  1504. nt_service_is_stopped(void)
  1505. {
  1506. if (service_status.dwCurrentState == SERVICE_STOP_PENDING) {
  1507. service_status.dwWin32ExitCode = 0;
  1508. service_status.dwCurrentState = SERVICE_STOPPED;
  1509. SetServiceStatus(hStatus, &service_status);
  1510. return 1;
  1511. } else if (service_status.dwCurrentState == SERVICE_STOPPED) {
  1512. return 1;
  1513. }
  1514. return 0;
  1515. }
  1516. /** DOCDOC */
  1517. void
  1518. nt_service_control(DWORD request)
  1519. {
  1520. static struct timeval exit_now;
  1521. exit_now.tv_sec = 0;
  1522. exit_now.tv_usec = 0;
  1523. switch (request) {
  1524. case SERVICE_CONTROL_STOP:
  1525. case SERVICE_CONTROL_SHUTDOWN:
  1526. log_err(LD_GENERAL,
  1527. "Got stop/shutdown request; shutting down cleanly.");
  1528. service_status.dwCurrentState = SERVICE_STOP_PENDING;
  1529. event_loopexit(&exit_now);
  1530. return;
  1531. }
  1532. SetServiceStatus(hStatus, &service_status);
  1533. }
  1534. /** DOCDOC */
  1535. void
  1536. nt_service_body(int argc, char **argv)
  1537. {
  1538. int r;
  1539. service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  1540. service_status.dwCurrentState = SERVICE_START_PENDING;
  1541. service_status.dwControlsAccepted =
  1542. SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  1543. service_status.dwWin32ExitCode = 0;
  1544. service_status.dwServiceSpecificExitCode = 0;
  1545. service_status.dwCheckPoint = 0;
  1546. service_status.dwWaitHint = 1000;
  1547. hStatus = RegisterServiceCtrlHandler(GENSRV_SERVICENAME,
  1548. (LPHANDLER_FUNCTION) nt_service_control);
  1549. if (hStatus == 0) {
  1550. // failed;
  1551. return;
  1552. }
  1553. // check for torrc
  1554. if (nt_torrc_is_present()) {
  1555. r = tor_init(backup_argc, backup_argv);
  1556. // refactor this part out of tor_main and do_main_loop
  1557. if (r) {
  1558. r = NT_SERVICE_ERROR_TORINIT_FAILED;
  1559. }
  1560. }
  1561. else {
  1562. log_err(LD_CONFIG, "torrc is not in the current working directory. "
  1563. "The Tor service will not start.");
  1564. r = NT_SERVICE_ERROR_NO_TORRC;
  1565. }
  1566. if (r) {
  1567. // failed.
  1568. service_status.dwCurrentState = SERVICE_STOPPED;
  1569. service_status.dwWin32ExitCode = r;
  1570. service_status.dwServiceSpecificExitCode = r;
  1571. SetServiceStatus(hStatus, &service_status);
  1572. return;
  1573. }
  1574. service_status.dwCurrentState = SERVICE_RUNNING;
  1575. SetServiceStatus(hStatus, &service_status);
  1576. do_main_loop();
  1577. tor_cleanup();
  1578. return;
  1579. }
  1580. /** DOCDOC */
  1581. void
  1582. nt_service_main(void)
  1583. {
  1584. SERVICE_TABLE_ENTRY table[2];
  1585. DWORD result = 0;
  1586. char *errmsg;
  1587. table[0].lpServiceName = GENSRV_SERVICENAME;
  1588. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
  1589. table[1].lpServiceName = NULL;
  1590. table[1].lpServiceProc = NULL;
  1591. if (!StartServiceCtrlDispatcher(table)) {
  1592. result = GetLastError();
  1593. errmsg = nt_strerror(result);
  1594. printf("Service error %d : %s\n", (int) result, errmsg);
  1595. LocalFree(errmsg);
  1596. if (result == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
  1597. if (tor_init(backup_argc, backup_argv) < 0)
  1598. return;
  1599. switch (get_options()->command) {
  1600. case CMD_RUN_TOR:
  1601. do_main_loop();
  1602. break;
  1603. case CMD_LIST_FINGERPRINT:
  1604. do_list_fingerprint();
  1605. break;
  1606. case CMD_HASH_PASSWORD:
  1607. do_hash_password();
  1608. break;
  1609. case CMD_VERIFY_CONFIG:
  1610. printf("Configuration was valid\n");
  1611. break;
  1612. default:
  1613. log_err(LD_CONFIG, "Illegal command number %d: internal error.",
  1614. get_options()->command);
  1615. }
  1616. tor_cleanup();
  1617. }
  1618. }
  1619. }
  1620. /** DOCDOC */
  1621. SC_HANDLE
  1622. nt_service_open_scm(void)
  1623. {
  1624. SC_HANDLE hSCManager;
  1625. char *errmsg = NULL;
  1626. if ((hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE))
  1627. == NULL) {
  1628. errmsg = nt_strerror(GetLastError());
  1629. printf("OpenSCManager() failed : %s\n", errmsg);
  1630. LocalFree(errmsg);
  1631. }
  1632. return hSCManager;
  1633. }
  1634. /** DOCDOC */
  1635. SC_HANDLE
  1636. nt_service_open(SC_HANDLE hSCManager)
  1637. {
  1638. SC_HANDLE hService;
  1639. char *errmsg = NULL;
  1640. if ((hService = OpenService(hSCManager, GENSRV_SERVICENAME,
  1641. SERVICE_ALL_ACCESS)) == NULL) {
  1642. errmsg = nt_strerror(GetLastError());
  1643. printf("OpenService() failed : %s\n", errmsg);
  1644. LocalFree(errmsg);
  1645. }
  1646. return hService;
  1647. }
  1648. /** DOCDOC */
  1649. int
  1650. nt_service_start(SC_HANDLE hService)
  1651. {
  1652. char *errmsg = NULL;
  1653. QueryServiceStatus(hService, &service_status);
  1654. if (service_status.dwCurrentState == SERVICE_RUNNING) {
  1655. printf("Service is already running\n");
  1656. return 1;
  1657. }
  1658. if (StartService(hService, 0, NULL)) {
  1659. /* Loop until the service has finished attempting to start */
  1660. while (QueryServiceStatus(hService, &service_status)) {
  1661. if (service_status.dwCurrentState == SERVICE_START_PENDING)
  1662. Sleep(500);
  1663. else
  1664. break;
  1665. }
  1666. /* Check if it started successfully or not */
  1667. if (service_status.dwCurrentState == SERVICE_RUNNING) {
  1668. printf("Service started successfully\n");
  1669. return 1;
  1670. }
  1671. else {
  1672. errmsg = nt_strerror(service_status.dwWin32ExitCode);
  1673. printf("Service failed to start : %s\n", errmsg);
  1674. LocalFree(errmsg);
  1675. }
  1676. }
  1677. else {
  1678. errmsg = nt_strerror(GetLastError());
  1679. printf("StartService() failed : %s\n", errmsg);
  1680. LocalFree(errmsg);
  1681. }
  1682. return 0;
  1683. }
  1684. /** DOCDOC */
  1685. int
  1686. nt_service_stop(SC_HANDLE hService)
  1687. {
  1688. char *errmsg = NULL;
  1689. QueryServiceStatus(hService, &service_status);
  1690. if (service_status.dwCurrentState == SERVICE_STOPPED) {
  1691. printf("Service is already stopped\n");
  1692. return 1;
  1693. }
  1694. if (ControlService(hService, SERVICE_CONTROL_STOP, &service_status)) {
  1695. while (QueryServiceStatus(hService, &service_status)) {
  1696. if (service_status.dwCurrentState == SERVICE_STOP_PENDING)
  1697. Sleep(500);
  1698. else
  1699. break;
  1700. }
  1701. if (service_status.dwCurrentState == SERVICE_STOPPED) {
  1702. printf("Service stopped successfully\n");
  1703. return 1;
  1704. }
  1705. else {
  1706. errmsg = nt_strerror(GetLastError());
  1707. printf("Service failed to stop : %s\n",errmsg);
  1708. LocalFree(errmsg);
  1709. }
  1710. }
  1711. else {
  1712. errmsg = nt_strerror(GetLastError());
  1713. printf("ControlService() failed : %s\n", errmsg);
  1714. LocalFree(errmsg);
  1715. }
  1716. return 0;
  1717. }
  1718. /** DOCDOC */
  1719. int
  1720. nt_service_install(void)
  1721. {
  1722. /* XXXX Problems with NT services:
  1723. * 1. The configuration file needs to be in the same directory as the .exe
  1724. *
  1725. * 2. The exe and the configuration file can't be on any directory path
  1726. * that contains a space.
  1727. * mje - you can quote the string (i.e., "c:\program files")
  1728. *
  1729. * 3. Ideally, there should be one EXE that can either run as a
  1730. * separate process (as now) or that can install and run itself
  1731. * as an NT service. I have no idea how hard this is.
  1732. * mje - should be done. It can install and run itself as a service
  1733. *
  1734. * Notes about developing NT services:
  1735. *
  1736. * 1. Don't count on your CWD. If an absolute path is not given, the
  1737. * fopen() function goes wrong.
  1738. * 2. The parameters given to the nt_service_body() function differ
  1739. * from those given to main() function.
  1740. */
  1741. SC_HANDLE hSCManager = NULL;
  1742. SC_HANDLE hService = NULL;
  1743. SERVICE_DESCRIPTION sdBuff;
  1744. TCHAR szPath[_MAX_PATH];
  1745. TCHAR szDrive[_MAX_DRIVE];
  1746. TCHAR szDir[_MAX_DIR];
  1747. char cmd1[] = " -f ";
  1748. char cmd2[] = "\\torrc";
  1749. char *command;
  1750. char *errmsg;
  1751. int len = 0;
  1752. if (0 == GetModuleFileName(NULL, szPath, MAX_PATH))
  1753. return 0;
  1754. _tsplitpath(szPath, szDrive, szDir, NULL, NULL);
  1755. /* Account for the extra quotes */
  1756. //len = _MAX_PATH + strlen(cmd1) + _MAX_DRIVE + _MAX_DIR + strlen(cmd2);
  1757. len = _MAX_PATH + strlen(cmd1) + _MAX_DRIVE + _MAX_DIR + strlen(cmd2) + 64;
  1758. command = tor_malloc(len);
  1759. /* Create a quoted command line, like "c:\with spaces\tor.exe" -f
  1760. * "c:\with spaces\tor.exe"
  1761. */
  1762. if (tor_snprintf(command, len, "\"%s\" --nt-service -f \"%s%storrc\"",
  1763. szPath, szDrive, szDir)<0) {
  1764. printf("Failed: tor_snprinf()\n");
  1765. tor_free(command);
  1766. return 0;
  1767. }
  1768. if ((hSCManager = nt_service_open_scm()) == NULL) {
  1769. tor_free(command);
  1770. return 0;
  1771. }
  1772. /* 1/26/2005 mje
  1773. * - changed the service start type to auto
  1774. * - and changed the lpPassword param to "" instead of NULL as per an
  1775. * MSDN article.
  1776. */
  1777. if ((hService = CreateService(hSCManager, GENSRV_SERVICENAME,
  1778. GENSRV_DISPLAYNAME,
  1779. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  1780. SERVICE_AUTO_START, SERVICE_ERROR_IGNORE,
  1781. command,
  1782. NULL, NULL, NULL, NULL, "")) == NULL) {
  1783. errmsg = nt_strerror(GetLastError());
  1784. printf("CreateService() failed : %s\n", errmsg);
  1785. CloseServiceHandle(hSCManager);
  1786. LocalFree(errmsg);
  1787. tor_free(command);
  1788. return 0;
  1789. }
  1790. /* Set the service's description */
  1791. sdBuff.lpDescription = GENSRV_DESCRIPTION;
  1792. ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &sdBuff);
  1793. printf("Service installed successfully\n");
  1794. /* Start the service initially */
  1795. nt_service_start(hService);
  1796. CloseServiceHandle(hService);
  1797. CloseServiceHandle(hSCManager);
  1798. tor_free(command);
  1799. return 0;
  1800. }
  1801. /** DOCDOC */
  1802. int
  1803. nt_service_remove(void)
  1804. {
  1805. SC_HANDLE hSCManager = NULL;
  1806. SC_HANDLE hService = NULL;
  1807. char *errmsg;
  1808. if ((hSCManager = nt_service_open_scm()) == NULL) {
  1809. return 0;
  1810. }
  1811. if ((hService = nt_service_open(hSCManager)) == NULL) {
  1812. CloseServiceHandle(hSCManager);
  1813. return 0;
  1814. }
  1815. if (nt_service_stop(hService)) {
  1816. if (DeleteService(hService)) {
  1817. printf("Removed service successfully\n");
  1818. }
  1819. else {
  1820. errmsg = nt_strerror(GetLastError());
  1821. printf("DeleteService() failed : %s\n", errmsg);
  1822. LocalFree(errmsg);
  1823. }
  1824. }
  1825. else {
  1826. printf("Service could not be removed\n");
  1827. }
  1828. CloseServiceHandle(hService);
  1829. CloseServiceHandle(hSCManager);
  1830. return 0;
  1831. }
  1832. /** DOCDOC */
  1833. int
  1834. nt_service_cmd_start(void)
  1835. {
  1836. SC_HANDLE hSCManager;
  1837. SC_HANDLE hService;
  1838. int start;
  1839. if ((hSCManager = nt_service_open_scm()) == NULL)
  1840. return -1;
  1841. if ((hService = nt_service_open(hSCManager)) == NULL) {
  1842. CloseHandle(hSCManager);
  1843. return -1;
  1844. }
  1845. start = nt_service_start(hService);
  1846. CloseHandle(hService);
  1847. CloseHandle(hSCManager);
  1848. return start;
  1849. }
  1850. /** DOCDOC */
  1851. int
  1852. nt_service_cmd_stop(void)
  1853. {
  1854. SC_HANDLE hSCManager;
  1855. SC_HANDLE hService;
  1856. int stop;
  1857. if ((hSCManager = nt_service_open_scm()) == NULL)
  1858. return -1;
  1859. if ((hService = nt_service_open(hSCManager)) == NULL) {
  1860. CloseHandle(hSCManager);
  1861. return -1;
  1862. }
  1863. stop = nt_service_stop(hService);
  1864. CloseHandle(hService);
  1865. CloseHandle(hSCManager);
  1866. return stop;
  1867. }
  1868. /** Given a Win32 error code, this attempts to make Windows
  1869. * return a human-readable error message. The char* returned
  1870. * is allocated by Windows, but should be freed with LocalFree()
  1871. * when finished with it. */
  1872. static char*
  1873. nt_strerror(uint32_t errnum)
  1874. {
  1875. char *msgbuf;
  1876. FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  1877. NULL, errnum, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1878. (LPSTR)&msgbuf, 0, NULL);
  1879. return msgbuf;
  1880. }
  1881. #endif
  1882. #ifdef USE_DMALLOC
  1883. #include <openssl/crypto.h>
  1884. static void
  1885. _tor_dmalloc_free(void *p)
  1886. {
  1887. tor_free(p);
  1888. }
  1889. #endif
  1890. /** DOCDOC */
  1891. int
  1892. tor_main(int argc, char *argv[])
  1893. {
  1894. int result = 0;
  1895. #ifdef USE_DMALLOC
  1896. int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc,
  1897. _tor_dmalloc_free);
  1898. log_notice(LD_CONFIG, "Set up dmalloc; returned %d", r);
  1899. #endif
  1900. #ifdef MS_WINDOWS_SERVICE
  1901. backup_argv = argv;
  1902. backup_argc = argc;
  1903. if ((argc >= 3) &&
  1904. (!strcmp(argv[1], "-service") || !strcmp(argv[1], "--service"))) {
  1905. if (!strcmp(argv[2], "install"))
  1906. return nt_service_install();
  1907. if (!strcmp(argv[2], "remove"))
  1908. return nt_service_remove();
  1909. if (!strcmp(argv[2], "start"))
  1910. return nt_service_cmd_start();
  1911. if (!strcmp(argv[2], "stop"))
  1912. return nt_service_cmd_stop();
  1913. printf("Unrecognized service command '%s'\n", argv[2]);
  1914. return -1;
  1915. }
  1916. // These are left so as not to confuse people who are used to these options
  1917. if (argc >= 2) {
  1918. if (!strcmp(argv[1], "-install") || !strcmp(argv[1], "--install"))
  1919. return nt_service_install();
  1920. if (!strcmp(argv[1], "-remove") || !strcmp(argv[1], "--remove"))
  1921. return nt_service_remove();
  1922. if (!strcmp(argv[1], "-nt-service") || !strcmp(argv[1], "--nt-service")) {
  1923. nt_service_main();
  1924. return 0;
  1925. }
  1926. }
  1927. #endif
  1928. if (tor_init(argc, argv)<0)
  1929. return -1;
  1930. switch (get_options()->command) {
  1931. case CMD_RUN_TOR:
  1932. #ifdef MS_WINDOWS_SERVICE
  1933. service_status.dwCurrentState = SERVICE_RUNNING;
  1934. #endif
  1935. result = do_main_loop();
  1936. break;
  1937. case CMD_LIST_FINGERPRINT:
  1938. result = do_list_fingerprint();
  1939. break;
  1940. case CMD_HASH_PASSWORD:
  1941. do_hash_password();
  1942. result = 0;
  1943. break;
  1944. case CMD_VERIFY_CONFIG:
  1945. printf("Configuration was valid\n");
  1946. result = 0;
  1947. break;
  1948. case CMD_RUN_UNITTESTS: /* only set by test.c */
  1949. default:
  1950. log_warn(LD_BUG,"Illegal command number %d: internal error.",
  1951. get_options()->command);
  1952. result = -1;
  1953. }
  1954. tor_cleanup();
  1955. return result;
  1956. }