main.c 63 KB

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