main.c 64 KB

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