main.c 62 KB

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