main.c 64 KB

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