main.c 67 KB

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