main.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004 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 Tor main loop and startup functions.
  10. **/
  11. #include "or.h"
  12. /********* PROTOTYPES **********/
  13. static void dumpstats(int severity); /* log stats */
  14. /********* START VARIABLES **********/
  15. int global_read_bucket; /**< Max number of bytes I can read this second. */
  16. int global_write_bucket; /**< Max number of bytes I can write this second. */
  17. /** What was the read bucket before the last call to prepare_for_pool?
  18. * (used to determine how many bytes we've read). */
  19. static int stats_prev_global_read_bucket;
  20. /** What was the write bucket before the last call to prepare_for_pool?
  21. * (used to determine how many bytes we've written). */
  22. static int stats_prev_global_write_bucket;
  23. /** How many bytes have we read/written since we started the process? */
  24. static uint64_t stats_n_bytes_read = 0;
  25. static uint64_t stats_n_bytes_written = 0;
  26. /** How many seconds have we been running? */
  27. long stats_n_seconds_uptime = 0;
  28. /** When do we next download a directory? */
  29. static time_t time_to_fetch_directory = 0;
  30. /** When do we next upload our descriptor? */
  31. static time_t time_to_force_upload_descriptor = 0;
  32. /** When do we next download a running-routers summary? */
  33. static time_t time_to_fetch_running_routers = 0;
  34. /** Array of all open connections; each element corresponds to the element of
  35. * poll_array in the same position. The first nfds elements are valid. */
  36. static connection_t *connection_array[MAXCONNECTIONS] =
  37. { NULL };
  38. /** Array of pollfd objects for calls to poll(). */
  39. static struct pollfd poll_array[MAXCONNECTIONS];
  40. static int nfds=0; /**< Number of connections currently active. */
  41. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  42. static int please_dumpstats=0; /**< Whether we should dump stats during the loop. */
  43. static int please_debug=0; /**< Whether we should switch all logs to -l debug. */
  44. static int please_reset=0; /**< Whether we just got a sighup. */
  45. static int please_reap_children=0; /**< Whether we should waitpid for exited children. */
  46. static int please_sigpipe=0; /**< Whether we've caught a sigpipe lately. */
  47. static int please_shutdown=0; /**< Whether we should shut down Tor. */
  48. #endif /* signal stuff */
  49. /** We set this to 1 when we've fetched a dir, to know whether to complain
  50. * yet about unrecognized nicknames in entrynodes, exitnodes, etc.
  51. * Also, we don't try building circuits unless this is 1. */
  52. int has_fetched_directory=0;
  53. /** We set this to 1 when we've opened a circuit, so we can print a log
  54. * entry to inform the user that Tor is working. */
  55. int has_completed_circuit=0;
  56. /* #define MS_WINDOWS_SERVICE */
  57. #ifdef MS_WINDOWS_SERVICE
  58. #include <tchar.h>
  59. #define GENSRV_SERVICENAME TEXT("tor-"VERSION)
  60. #define GENSRV_DISPLAYNAME TEXT("Tor "VERSION" Win32 Service")
  61. SERVICE_STATUS service_status;
  62. SERVICE_STATUS_HANDLE hStatus;
  63. static char **backup_argv;
  64. static int backup_argc;
  65. #endif
  66. #define CHECK_DESCRIPTOR_INTERVAL 60
  67. /********* END VARIABLES ************/
  68. /****************************************************************************
  69. *
  70. * This section contains accessors and other methods on the connection_array
  71. * and poll_array variables (which are global within this file and unavailable
  72. * outside it).
  73. *
  74. ****************************************************************************/
  75. /** Add <b>conn</b> to the array of connections that we can poll on. The
  76. * connection's socket must be set; the connection starts out
  77. * non-reading and non-writing.
  78. */
  79. int connection_add(connection_t *conn) {
  80. tor_assert(conn);
  81. tor_assert(conn->s >= 0);
  82. if (nfds >= get_options()->MaxConn-1) {
  83. log_fn(LOG_WARN,"failing because nfds is too high.");
  84. return -1;
  85. }
  86. tor_assert(conn->poll_index == -1); /* can only connection_add once */
  87. conn->poll_index = nfds;
  88. connection_array[nfds] = conn;
  89. poll_array[nfds].fd = conn->s;
  90. /* zero these out here, because otherwise we'll inherit values from the previously freed one */
  91. poll_array[nfds].events = 0;
  92. poll_array[nfds].revents = 0;
  93. nfds++;
  94. log_fn(LOG_INFO,"new conn type %s, socket %d, nfds %d.",
  95. CONN_TYPE_TO_STRING(conn->type), conn->s, nfds);
  96. return 0;
  97. }
  98. /** Remove the connection from the global list, and remove the
  99. * corresponding poll entry. Calling this function will shift the last
  100. * connection (if any) into the position occupied by conn.
  101. */
  102. int connection_remove(connection_t *conn) {
  103. int current_index;
  104. tor_assert(conn);
  105. tor_assert(nfds>0);
  106. log_fn(LOG_INFO,"removing socket %d (type %s), nfds now %d",
  107. conn->s, CONN_TYPE_TO_STRING(conn->type), nfds-1);
  108. tor_assert(conn->poll_index >= 0);
  109. current_index = conn->poll_index;
  110. if (current_index == nfds-1) { /* this is the end */
  111. nfds--;
  112. return 0;
  113. }
  114. /* replace this one with the one at the end */
  115. nfds--;
  116. poll_array[current_index].fd = poll_array[nfds].fd;
  117. poll_array[current_index].events = poll_array[nfds].events;
  118. poll_array[current_index].revents = poll_array[nfds].revents;
  119. connection_array[current_index] = connection_array[nfds];
  120. connection_array[current_index]->poll_index = current_index;
  121. return 0;
  122. }
  123. /** Return true iff conn is in the current poll array. */
  124. int connection_in_array(connection_t *conn) {
  125. int i;
  126. for (i=0; i<nfds; ++i) {
  127. if (conn==connection_array[i])
  128. return 1;
  129. }
  130. return 0;
  131. }
  132. /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
  133. * to the length of the array. <b>*array</b> and <b>*n</b> must not
  134. * be modified.
  135. */
  136. void get_connection_array(connection_t ***array, int *n) {
  137. *array = connection_array;
  138. *n = nfds;
  139. }
  140. /** Set the event mask on <b>conn</b> to <b>events</b>. (The form of
  141. * the event mask is as for poll().)
  142. */
  143. void connection_watch_events(connection_t *conn, short events) {
  144. tor_assert(conn);
  145. tor_assert(conn->poll_index >= 0);
  146. tor_assert(conn->poll_index < nfds);
  147. poll_array[conn->poll_index].events = events;
  148. }
  149. /** Return true iff <b>conn</b> is listening for read events. */
  150. int connection_is_reading(connection_t *conn) {
  151. tor_assert(conn);
  152. tor_assert(conn->poll_index >= 0);
  153. return poll_array[conn->poll_index].events & POLLIN;
  154. }
  155. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  156. void connection_stop_reading(connection_t *conn) {
  157. tor_assert(conn);
  158. tor_assert(conn->poll_index >= 0);
  159. tor_assert(conn->poll_index < nfds);
  160. log(LOG_DEBUG,"connection_stop_reading() called.");
  161. poll_array[conn->poll_index].events &= ~POLLIN;
  162. }
  163. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  164. void connection_start_reading(connection_t *conn) {
  165. tor_assert(conn);
  166. tor_assert(conn->poll_index >= 0);
  167. tor_assert(conn->poll_index < nfds);
  168. poll_array[conn->poll_index].events |= POLLIN;
  169. }
  170. /** Return true iff <b>conn</b> is listening for write events. */
  171. int connection_is_writing(connection_t *conn) {
  172. return poll_array[conn->poll_index].events & POLLOUT;
  173. }
  174. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  175. void connection_stop_writing(connection_t *conn) {
  176. tor_assert(conn);
  177. tor_assert(conn->poll_index >= 0);
  178. tor_assert(conn->poll_index < nfds);
  179. poll_array[conn->poll_index].events &= ~POLLOUT;
  180. }
  181. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  182. void connection_start_writing(connection_t *conn) {
  183. tor_assert(conn);
  184. tor_assert(conn->poll_index >= 0);
  185. tor_assert(conn->poll_index < nfds);
  186. poll_array[conn->poll_index].events |= POLLOUT;
  187. }
  188. /** Called when the connection at connection_array[i] has a read event,
  189. * or it has pending tls data waiting to be read: checks for validity,
  190. * catches numerous errors, and dispatches to connection_handle_read.
  191. */
  192. static void conn_read(int i) {
  193. connection_t *conn = connection_array[i];
  194. if (conn->marked_for_close)
  195. return;
  196. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
  197. * discussion of POLLIN vs POLLHUP */
  198. if (!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
  199. /* Sometimes read events get triggered for things that didn't ask
  200. * for them (XXX due to unknown poll wonkiness) and sometime we
  201. * want to read even though there was no read event (due to
  202. * pending TLS data).
  203. */
  204. /* XXX Post 0.0.9, we should rewrite this whole if statement;
  205. * something sane may result. Nick suspects that the || below
  206. * should be a &&.
  207. */
  208. if (!connection_is_reading(conn) ||
  209. !connection_has_pending_tls_data(conn))
  210. return; /* this conn should not read */
  211. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  212. assert_connection_ok(conn, time(NULL));
  213. assert_all_pending_dns_resolves_ok();
  214. if (
  215. /* XXX does POLLHUP also mean it's definitely broken? */
  216. #ifdef MS_WINDOWS
  217. (poll_array[i].revents & POLLERR) ||
  218. #endif
  219. connection_handle_read(conn) < 0) {
  220. if (!conn->marked_for_close) {
  221. /* this connection is broken. remove it */
  222. log_fn(LOG_WARN,"Unhandled error on read for %s connection (fd %d); removing",
  223. CONN_TYPE_TO_STRING(conn->type), conn->s);
  224. connection_mark_for_close(conn);
  225. }
  226. }
  227. assert_connection_ok(conn, time(NULL));
  228. assert_all_pending_dns_resolves_ok();
  229. }
  230. /** Called when the connection at connection_array[i] has a write event:
  231. * checks for validity, catches numerous errors, and dispatches to
  232. * connection_handle_write.
  233. */
  234. static void conn_write(int i) {
  235. connection_t *conn;
  236. if (!(poll_array[i].revents & POLLOUT))
  237. return; /* this conn doesn't want to write */
  238. conn = connection_array[i];
  239. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  240. if (conn->marked_for_close)
  241. return;
  242. assert_connection_ok(conn, time(NULL));
  243. assert_all_pending_dns_resolves_ok();
  244. if (connection_handle_write(conn) < 0) {
  245. if (!conn->marked_for_close) {
  246. /* this connection is broken. remove it. */
  247. log_fn(LOG_WARN,"Unhandled error on write for %s connection (fd %d); removing",
  248. CONN_TYPE_TO_STRING(conn->type), conn->s);
  249. conn->has_sent_end = 1; /* otherwise we cry wolf about duplicate close */
  250. /* XXX do we need a close-immediate here, so we don't try to flush? */
  251. connection_mark_for_close(conn);
  252. }
  253. }
  254. assert_connection_ok(conn, time(NULL));
  255. assert_all_pending_dns_resolves_ok();
  256. }
  257. /** If the connection at connection_array[i] is marked for close, then:
  258. * - If it has data that it wants to flush, try to flush it.
  259. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  260. * true, then leave the connection open and return.
  261. * - Otherwise, remove the connection from connection_array and from
  262. * all other lists, close it, and free it.
  263. * If we remove the connection, then call conn_closed_if_marked at the new
  264. * connection at position i.
  265. */
  266. static void conn_close_if_marked(int i) {
  267. connection_t *conn;
  268. int retval;
  269. conn = connection_array[i];
  270. assert_connection_ok(conn, time(NULL));
  271. assert_all_pending_dns_resolves_ok();
  272. if (!conn->marked_for_close)
  273. return; /* nothing to see here, move along */
  274. log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
  275. if (conn->s >= 0 && connection_wants_to_flush(conn)) {
  276. /* -1 means it's an incomplete edge connection, or that the socket
  277. * has already been closed as unflushable. */
  278. if (!conn->hold_open_until_flushed)
  279. log_fn(LOG_INFO,
  280. "Conn (addr %s, fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
  281. "(Marked at %s:%d)",
  282. conn->address, conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  283. (int)conn->outbuf_flushlen, conn->marked_for_close_file, conn->marked_for_close);
  284. if (connection_speaks_cells(conn)) {
  285. if (conn->state == OR_CONN_STATE_OPEN) {
  286. retval = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  287. } else
  288. retval = -1; /* never flush non-open broken tls connections */
  289. } else {
  290. retval = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  291. }
  292. if (retval >= 0 &&
  293. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  294. log_fn(LOG_INFO,"Holding conn (fd %d) open for more flushing.",conn->s);
  295. /* XXX should we reset timestamp_lastwritten here? */
  296. return;
  297. }
  298. if (connection_wants_to_flush(conn)) {
  299. log_fn(LOG_WARN,"Conn (addr %s, fd %d, type %s, state %d) still wants to flush. Losing %d bytes! (Marked at %s:%d)",
  300. conn->address, conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  301. (int)buf_datalen(conn->outbuf), conn->marked_for_close_file,
  302. conn->marked_for_close);
  303. }
  304. }
  305. /* if it's an edge conn, remove it from the list
  306. * of conn's on this circuit. If it's not on an edge,
  307. * flush and send destroys for all circuits on this conn
  308. */
  309. circuit_about_to_close_connection(conn);
  310. connection_about_to_close_connection(conn);
  311. connection_remove(conn);
  312. if (conn->type == CONN_TYPE_EXIT) {
  313. assert_connection_edge_not_dns_pending(conn);
  314. }
  315. connection_free(conn);
  316. if (i<nfds) { /* we just replaced the one at i with a new one.
  317. process it too. */
  318. conn_close_if_marked(i);
  319. }
  320. }
  321. /** This function is called whenever we successfully pull down a directory */
  322. void directory_has_arrived(time_t now) {
  323. or_options_t *options = get_options();
  324. log_fn(LOG_INFO, "A directory has arrived.");
  325. has_fetched_directory=1;
  326. /* Don't try to upload or download anything for a while
  327. * after the directory we had when we started.
  328. */
  329. if (!time_to_fetch_directory)
  330. time_to_fetch_directory = now + options->DirFetchPeriod;
  331. if (!time_to_force_upload_descriptor)
  332. time_to_force_upload_descriptor = now + options->DirPostPeriod;
  333. if (!time_to_fetch_running_routers)
  334. time_to_fetch_running_routers = now + options->StatusFetchPeriod;
  335. if (server_mode(options) &&
  336. !we_are_hibernating()) { /* connect to the appropriate routers */
  337. router_retry_connections();
  338. }
  339. }
  340. /** Perform regular maintenance tasks for a single connection. This
  341. * function gets run once per second per connection by run_housekeeping.
  342. */
  343. static void run_connection_housekeeping(int i, time_t now) {
  344. cell_t cell;
  345. connection_t *conn = connection_array[i];
  346. or_options_t *options = get_options();
  347. /* Expire any directory connections that haven't sent anything for 5 min */
  348. if (conn->type == CONN_TYPE_DIR &&
  349. !conn->marked_for_close &&
  350. conn->timestamp_lastwritten + 5*60 < now) {
  351. log_fn(LOG_INFO,"Expiring wedged directory conn (fd %d, purpose %d)", conn->s, conn->purpose);
  352. connection_mark_for_close(conn);
  353. return;
  354. }
  355. /* If we haven't written to an OR connection for a while, then either nuke
  356. the connection or send a keepalive, depending. */
  357. if (connection_speaks_cells(conn) &&
  358. now >= conn->timestamp_lastwritten + options->KeepalivePeriod) {
  359. routerinfo_t *router = router_get_by_digest(conn->identity_digest);
  360. if ((!connection_state_is_open(conn)) ||
  361. (we_are_hibernating() && !circuit_get_by_conn(conn)) ||
  362. (!clique_mode(options) && !circuit_get_by_conn(conn) &&
  363. (!router || !server_mode(options) || !router_is_clique_mode(router)))) {
  364. /* our handshake has expired; we're hibernating;
  365. * or we have no circuits and we're both either OPs or normal ORs,
  366. * then kill it. */
  367. log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
  368. i,conn->address, conn->port);
  369. /* flush anything waiting, e.g. a destroy for a just-expired circ */
  370. connection_mark_for_close(conn);
  371. conn->hold_open_until_flushed = 1;
  372. } else {
  373. /* either in clique mode, or we've got a circuit. send a padding cell. */
  374. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  375. conn->address, conn->port);
  376. memset(&cell,0,sizeof(cell_t));
  377. cell.command = CELL_PADDING;
  378. connection_or_write_cell_to_buf(&cell, conn);
  379. }
  380. }
  381. }
  382. #define MIN_BW_TO_PUBLISH_DESC 5000 /* 5000 bytes/s sustained */
  383. #define MIN_UPTIME_TO_PUBLISH_DESC (30*60) /* half an hour */
  384. /** Decide if we're a publishable server or just a client. We are a server if:
  385. * - We have the AuthoritativeDirectory option set.
  386. * or
  387. * - We don't have the ClientOnly option set; and
  388. * - We have ORPort set; and
  389. * - We have been up for at least MIN_UPTIME_TO_PUBLISH_DESC seconds; and
  390. * - We have processed some suitable minimum bandwidth recently; and
  391. * - We believe we are reachable from the outside.
  392. */
  393. static int decide_if_publishable_server(time_t now) {
  394. int bw;
  395. or_options_t *options = get_options();
  396. bw = rep_hist_bandwidth_assess();
  397. router_set_bandwidth_capacity(bw);
  398. if (options->ClientOnly)
  399. return 0;
  400. if (!options->ORPort)
  401. return 0;
  402. /* XXX for now, you're only a server if you're a server */
  403. return server_mode(options);
  404. /* here, determine if we're reachable */
  405. if (0) { /* we've recently failed to reach our IP/ORPort from the outside */
  406. return 0;
  407. }
  408. if (bw < MIN_BW_TO_PUBLISH_DESC)
  409. return 0;
  410. if (options->AuthoritativeDir)
  411. return 1;
  412. if (stats_n_seconds_uptime < MIN_UPTIME_TO_PUBLISH_DESC)
  413. return 0;
  414. return 1;
  415. }
  416. /** Return true iff we believe ourselves to be an authoritative
  417. * directory server.
  418. */
  419. int authdir_mode(or_options_t *options) {
  420. return options->AuthoritativeDir != 0;
  421. }
  422. /** Return true iff we try to stay connected to all ORs at once.
  423. */
  424. int clique_mode(or_options_t *options) {
  425. return authdir_mode(options);
  426. }
  427. /** Return true iff we are trying to be a server.
  428. */
  429. int server_mode(or_options_t *options) {
  430. return (options->ORPort != 0 || options->ORBindAddress);
  431. }
  432. /** Remember if we've advertised ourselves to the dirservers. */
  433. static int server_is_advertised=0;
  434. /** Return true iff we have published our descriptor lately.
  435. */
  436. int advertised_server_mode(void) {
  437. return server_is_advertised;
  438. }
  439. /** Return true iff we are trying to be a socks proxy. */
  440. int proxy_mode(or_options_t *options) {
  441. return (options->SocksPort != 0 || options->SocksBindAddress);
  442. }
  443. /** Perform regular maintenance tasks. This function gets run once per
  444. * second by prepare_for_poll.
  445. */
  446. static void run_scheduled_events(time_t now) {
  447. static time_t last_rotated_certificate = 0;
  448. static time_t time_to_check_listeners = 0;
  449. static time_t time_to_check_descriptor = 0;
  450. or_options_t *options = get_options();
  451. int i;
  452. /** 0. See if we've been asked to shut down and our timeout has
  453. * expired; or if our bandwidth limits are exhausted and we
  454. * should hibernate; or if it's time to wake up from hibernation.
  455. */
  456. consider_hibernation(now);
  457. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  458. * shut down and restart all cpuworkers, and update the directory if
  459. * necessary.
  460. */
  461. if (server_mode(options) &&
  462. get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  463. log_fn(LOG_INFO,"Rotating onion key.");
  464. rotate_onion_key();
  465. cpuworkers_rotate();
  466. if (router_rebuild_descriptor(1)<0) {
  467. log_fn(LOG_WARN, "Couldn't rebuild router descriptor");
  468. }
  469. if (advertised_server_mode())
  470. router_upload_dir_desc_to_dirservers(0);
  471. }
  472. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  473. if (!last_rotated_certificate)
  474. last_rotated_certificate = now;
  475. if (last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
  476. log_fn(LOG_INFO,"Rotating tls context.");
  477. if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
  478. MAX_SSL_KEY_LIFETIME) < 0) {
  479. log_fn(LOG_WARN, "Error reinitializing TLS context");
  480. }
  481. last_rotated_certificate = now;
  482. /* XXXX We should rotate TLS connections as well; this code doesn't change
  483. * XXXX them at all. */
  484. }
  485. /** 1c. If we have to change the accounting interval or record
  486. * bandwidth used in this accounting interval, do so. */
  487. if (accounting_is_enabled(options))
  488. accounting_run_housekeeping(now);
  489. /** 2. Periodically, we consider getting a new directory, getting a
  490. * new running-routers list, and/or force-uploading our descriptor
  491. * (if we've passed our internal checks). */
  492. if (time_to_fetch_directory < now) {
  493. /* purge obsolete entries */
  494. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  495. if (authdir_mode(options)) {
  496. /* We're a directory; dump any old descriptors. */
  497. dirserv_remove_old_servers(ROUTER_MAX_AGE);
  498. }
  499. if (server_mode(options) && !we_are_hibernating()) {
  500. /* dirservers try to reconnect, in case connections have failed;
  501. * and normal servers try to reconnect to dirservers */
  502. router_retry_connections();
  503. }
  504. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL);
  505. time_to_fetch_directory = now + options->DirFetchPeriod;
  506. if (time_to_fetch_running_routers < now + options->StatusFetchPeriod) {
  507. time_to_fetch_running_routers = now + options->StatusFetchPeriod;
  508. }
  509. /* Also, take this chance to remove old information from rephist. */
  510. rep_history_clean(now-24*60*60);
  511. }
  512. if (time_to_fetch_running_routers < now) {
  513. if (!authdir_mode(options)) {
  514. directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST, NULL);
  515. }
  516. time_to_fetch_running_routers = now + options->StatusFetchPeriod;
  517. }
  518. if (time_to_force_upload_descriptor < now) {
  519. if (decide_if_publishable_server(now)) {
  520. server_is_advertised = 1;
  521. router_rebuild_descriptor(1);
  522. router_upload_dir_desc_to_dirservers(1);
  523. } else {
  524. server_is_advertised = 0;
  525. }
  526. rend_cache_clean(); /* this should go elsewhere? */
  527. time_to_force_upload_descriptor = now + options->DirPostPeriod;
  528. }
  529. /* 2b. Once per minute, regenerate and upload the descriptor if the old
  530. * one is inaccurate. */
  531. if (time_to_check_descriptor < now) {
  532. time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
  533. if (decide_if_publishable_server(now)) {
  534. server_is_advertised=1;
  535. router_rebuild_descriptor(0);
  536. router_upload_dir_desc_to_dirservers(0);
  537. } else {
  538. server_is_advertised=0;
  539. }
  540. }
  541. /** 3a. Every second, we examine pending circuits and prune the
  542. * ones which have been pending for more than a few seconds.
  543. * We do this before step 4, so it can try building more if
  544. * it's not comfortable with the number of available circuits.
  545. */
  546. circuit_expire_building(now);
  547. /** 3b. Also look at pending streams and prune the ones that 'began'
  548. * a long time ago but haven't gotten a 'connected' yet.
  549. * Do this before step 4, so we can put them back into pending
  550. * state to be picked up by the new circuit.
  551. */
  552. connection_ap_expire_beginning();
  553. /** 3c. And expire connections that we've held open for too long.
  554. */
  555. connection_expire_held_open();
  556. /** 3d. And every 60 seconds, we relaunch listeners if any died. */
  557. if (!we_are_hibernating() && time_to_check_listeners < now) {
  558. retry_all_listeners(0); /* 0 means "only if some died." */
  559. time_to_check_listeners = now+60;
  560. }
  561. /** 4. Every second, we try a new circuit if there are no valid
  562. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  563. * that became dirty more than NewCircuitPeriod seconds ago,
  564. * and we make a new circ if there are no clean circuits.
  565. */
  566. if (has_fetched_directory && !we_are_hibernating())
  567. circuit_build_needed_circs(now);
  568. /** 5. We do housekeeping for each connection... */
  569. for (i=0;i<nfds;i++) {
  570. run_connection_housekeeping(i, now);
  571. }
  572. /** 6. And remove any marked circuits... */
  573. circuit_close_all_marked();
  574. /** 7. And upload service descriptors if necessary. */
  575. if (!we_are_hibernating())
  576. rend_consider_services_upload(now);
  577. /** 8. and blow away any connections that need to die. have to do this now,
  578. * because if we marked a conn for close and left its socket -1, then
  579. * we'll pass it to poll/select and bad things will happen.
  580. */
  581. for (i=0;i<nfds;i++)
  582. conn_close_if_marked(i);
  583. }
  584. /** Called every time we're about to call tor_poll. Increments statistics,
  585. * and adjusts token buckets. Returns the number of milliseconds to use for
  586. * the poll() timeout.
  587. */
  588. static int prepare_for_poll(void) {
  589. static long current_second = 0; /* from previous calls to gettimeofday */
  590. connection_t *conn;
  591. struct timeval now;
  592. int i;
  593. tor_gettimeofday(&now);
  594. if (now.tv_sec > current_second) {
  595. /* the second has rolled over. check more stuff. */
  596. size_t bytes_written;
  597. size_t bytes_read;
  598. int seconds_elapsed;
  599. bytes_written = stats_prev_global_write_bucket - global_write_bucket;
  600. bytes_read = stats_prev_global_read_bucket - global_read_bucket;
  601. seconds_elapsed = current_second ? (now.tv_sec - current_second) : 0;
  602. stats_n_bytes_read += bytes_read;
  603. stats_n_bytes_written += bytes_written;
  604. if (accounting_is_enabled(get_options()))
  605. accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
  606. control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
  607. connection_bucket_refill(&now);
  608. stats_prev_global_read_bucket = global_read_bucket;
  609. stats_prev_global_write_bucket = global_write_bucket;
  610. stats_n_seconds_uptime += seconds_elapsed;
  611. assert_all_pending_dns_resolves_ok();
  612. run_scheduled_events(now.tv_sec);
  613. assert_all_pending_dns_resolves_ok();
  614. current_second = now.tv_sec; /* remember which second it is, for next time */
  615. }
  616. for (i=0;i<nfds;i++) {
  617. conn = connection_array[i];
  618. if (connection_has_pending_tls_data(conn) &&
  619. connection_is_reading(conn)) {
  620. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  621. return 0; /* has pending bytes to read; don't let poll wait. */
  622. }
  623. }
  624. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  625. }
  626. /** Called when we get a SIGHUP: reload configuration files and keys,
  627. * retry all connections, re-upload all descriptors, and so on. */
  628. static int do_hup(void) {
  629. char keydir[512];
  630. or_options_t *options = get_options();
  631. log_fn(LOG_NOTICE,"Received sighup. Reloading config.");
  632. has_completed_circuit=0;
  633. if (accounting_is_enabled(options))
  634. accounting_record_bandwidth_usage(time(NULL));
  635. /* first, reload config variables, in case they've changed */
  636. /* no need to provide argc/v, they've been cached inside init_from_config */
  637. if (init_from_config(0, NULL) < 0) {
  638. log_fn(LOG_ERR,"Reading config failed--see warnings above. For usage, try -h.");
  639. return -1;
  640. }
  641. options = get_options();
  642. if (authdir_mode(options)) {
  643. /* reload the approved-routers file */
  644. tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", options->DataDirectory);
  645. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  646. if (dirserv_parse_fingerprint_file(keydir) < 0) {
  647. log_fn(LOG_WARN, "Error reloading fingerprints. Continuing with old list.");
  648. }
  649. }
  650. /* Fetch a new directory. Even authdirservers do this. */
  651. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL);
  652. if (server_mode(options)) {
  653. /* Restart cpuworker and dnsworker processes, so they get up-to-date
  654. * configuration options. */
  655. cpuworkers_rotate();
  656. dnsworkers_rotate();
  657. /* Rebuild fresh descriptor. */
  658. router_rebuild_descriptor(1);
  659. tor_snprintf(keydir,sizeof(keydir),"%s/router.desc", options->DataDirectory);
  660. log_fn(LOG_INFO,"Saving descriptor to %s...",keydir);
  661. if (write_str_to_file(keydir, router_get_my_descriptor(), 0)) {
  662. return -1;
  663. }
  664. }
  665. return 0;
  666. }
  667. /** Tor main loop. */
  668. static int do_main_loop(void) {
  669. int i;
  670. int timeout;
  671. int poll_result;
  672. /* load the private keys, if we're supposed to have them, and set up the
  673. * TLS context. */
  674. if (! identity_key_is_set()) {
  675. if (init_keys() < 0) {
  676. log_fn(LOG_ERR,"Error initializing keys; exiting");
  677. return -1;
  678. }
  679. }
  680. /* Set up our buckets */
  681. connection_bucket_init();
  682. stats_prev_global_read_bucket = global_read_bucket;
  683. stats_prev_global_write_bucket = global_write_bucket;
  684. /* load the routers file, or assign the defaults. */
  685. if (router_reload_router_list()) {
  686. return -1;
  687. }
  688. if (authdir_mode(get_options())) {
  689. /* the directory is already here, run startup things */
  690. router_retry_connections();
  691. }
  692. if (server_mode(get_options())) {
  693. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  694. cpu_init();
  695. }
  696. for (;;) {
  697. #ifdef MS_WINDOWS_SERVICE /* Do service stuff only on windows. */
  698. if (service_status.dwCurrentState == SERVICE_STOP_PENDING) {
  699. service_status.dwWin32ExitCode = 0;
  700. service_status.dwCurrentState = SERVICE_STOPPED;
  701. SetServiceStatus(hStatus, &service_status);
  702. return 0;
  703. }
  704. #endif
  705. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  706. if (please_shutdown) {
  707. if (!server_mode(get_options())) { /* do it now */
  708. log(LOG_NOTICE,"Interrupt: exiting cleanly.");
  709. tor_cleanup();
  710. exit(0);
  711. }
  712. hibernate_begin_shutdown();
  713. please_shutdown = 0;
  714. }
  715. if (please_sigpipe) {
  716. log(LOG_NOTICE,"Caught sigpipe. Ignoring.");
  717. please_sigpipe = 0;
  718. }
  719. if (please_dumpstats) {
  720. /* prefer to log it at INFO, but make sure we always see it */
  721. dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
  722. please_dumpstats = 0;
  723. }
  724. if (please_debug) {
  725. switch_logs_debug();
  726. log(LOG_NOTICE,"Caught USR2. Going to loglevel debug.");
  727. please_debug = 0;
  728. }
  729. if (please_reset) {
  730. if (do_hup() < 0) {
  731. log_fn(LOG_WARN,"Restart failed (config error?). Exiting.");
  732. tor_cleanup();
  733. exit(1);
  734. }
  735. please_reset = 0;
  736. }
  737. if (please_reap_children) {
  738. while (waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more zombies */
  739. please_reap_children = 0;
  740. }
  741. #endif /* signal stuff */
  742. timeout = prepare_for_poll();
  743. /* poll until we have an event, or the second ends */
  744. poll_result = tor_poll(poll_array, nfds, timeout);
  745. /* let catch() handle things like ^c, and otherwise don't worry about it */
  746. if (poll_result < 0) {
  747. int e = tor_socket_errno(-1);
  748. /* let the program survive things like ^z */
  749. if (e != EINTR) {
  750. log_fn(LOG_ERR,"poll failed: %s [%d]",
  751. tor_socket_strerror(e), e);
  752. return -1;
  753. } else {
  754. log_fn(LOG_DEBUG,"poll interrupted.");
  755. /* You can't trust the results of this poll(). Go back to the
  756. * top of the big for loop. */
  757. continue;
  758. }
  759. }
  760. /* do all the reads and errors first, so we can detect closed sockets */
  761. for (i=0;i<nfds;i++)
  762. conn_read(i); /* this also marks broken connections */
  763. /* then do the writes */
  764. for (i=0;i<nfds;i++)
  765. conn_write(i);
  766. /* any of the conns need to be closed now? */
  767. for (i=0;i<nfds;i++)
  768. conn_close_if_marked(i);
  769. /* refilling buckets and sending cells happens at the beginning of the
  770. * next iteration of the loop, inside prepare_for_poll()
  771. */
  772. }
  773. }
  774. /** Unix signal handler. */
  775. static void catch(int the_signal) {
  776. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  777. switch (the_signal) {
  778. // case SIGABRT:
  779. case SIGTERM:
  780. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  781. tor_cleanup();
  782. exit(0);
  783. case SIGINT:
  784. please_shutdown = 1;
  785. break;
  786. case SIGPIPE:
  787. /* don't log here, since it's possible you got the sigpipe because
  788. * your log failed! */
  789. please_sigpipe = 1;
  790. break;
  791. case SIGHUP:
  792. please_reset = 1;
  793. break;
  794. case SIGUSR1:
  795. please_dumpstats = 1;
  796. break;
  797. case SIGUSR2:
  798. please_debug = 1;
  799. break;
  800. case SIGCHLD:
  801. please_reap_children = 1;
  802. break;
  803. #ifdef SIGXFSZ
  804. case SIGXFSZ: /* this happens when write fails with etoobig */
  805. break; /* ignore; write will fail and we'll look at errno. */
  806. #endif
  807. default:
  808. log(LOG_WARN,"Caught signal %d that we can't handle??", the_signal);
  809. tor_cleanup();
  810. exit(1);
  811. }
  812. #endif /* signal stuff */
  813. }
  814. /** Write all statistics to the log, with log level 'severity'. Called
  815. * in response to a SIGUSR1. */
  816. static void dumpstats(int severity) {
  817. int i;
  818. connection_t *conn;
  819. time_t now = time(NULL);
  820. log(severity, "Dumping stats:");
  821. for (i=0;i<nfds;i++) {
  822. conn = connection_array[i];
  823. log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  824. i, conn->s, conn->type, CONN_TYPE_TO_STRING(conn->type),
  825. conn->state, conn_state_to_string[conn->type][conn->state], (int)(now - conn->timestamp_created));
  826. if (!connection_is_listener(conn)) {
  827. log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
  828. log(severity,"Conn %d: %d bytes waiting on inbuf (last read %d secs ago)",i,
  829. (int)buf_datalen(conn->inbuf),
  830. (int)(now - conn->timestamp_lastread));
  831. log(severity,"Conn %d: %d bytes waiting on outbuf (last written %d secs ago)",i,
  832. (int)buf_datalen(conn->outbuf), (int)(now - conn->timestamp_lastwritten));
  833. }
  834. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
  835. }
  836. log(severity,
  837. "Cells processed: %10lu padding\n"
  838. " %10lu create\n"
  839. " %10lu created\n"
  840. " %10lu relay\n"
  841. " (%10lu relayed)\n"
  842. " (%10lu delivered)\n"
  843. " %10lu destroy",
  844. stats_n_padding_cells_processed,
  845. stats_n_create_cells_processed,
  846. stats_n_created_cells_processed,
  847. stats_n_relay_cells_processed,
  848. stats_n_relay_cells_relayed,
  849. stats_n_relay_cells_delivered,
  850. stats_n_destroy_cells_processed);
  851. if (stats_n_data_cells_packaged)
  852. log(severity,"Average packaged cell fullness: %2.3f%%",
  853. 100*(((double)stats_n_data_bytes_packaged) /
  854. (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  855. if (stats_n_data_cells_received)
  856. log(severity,"Average delivered cell fullness: %2.3f%%",
  857. 100*(((double)stats_n_data_bytes_received) /
  858. (stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  859. if (stats_n_seconds_uptime)
  860. log(severity,
  861. "Average bandwidth used: "U64_FORMAT"/%ld = %d bytes/sec",
  862. U64_PRINTF_ARG(stats_n_bytes_read),
  863. stats_n_seconds_uptime,
  864. (int) (stats_n_bytes_read/stats_n_seconds_uptime));
  865. rep_hist_dump_stats(now,severity);
  866. rend_service_dump_stats(severity);
  867. }
  868. /** Called before we make any calls to network-related functions.
  869. * (Some operating systems require their network libraries to be
  870. * initialized.) */
  871. static int network_init(void)
  872. {
  873. #ifdef MS_WINDOWS
  874. /* This silly exercise is necessary before windows will allow gethostbyname to work.
  875. */
  876. WSADATA WSAData;
  877. int r;
  878. r = WSAStartup(0x101,&WSAData);
  879. if (r) {
  880. log_fn(LOG_WARN,"Error initializing windows network layer: code was %d",r);
  881. return -1;
  882. }
  883. #endif
  884. return 0;
  885. }
  886. /** Called by exit() as we shut down the process.
  887. */
  888. static void exit_function(void)
  889. {
  890. /* NOTE: If we ever daemonize, this gets called immediately. That's
  891. * okay for now, because we only use this on Windows. */
  892. #ifdef MS_WINDOWS
  893. WSACleanup();
  894. #endif
  895. }
  896. /** Set up the signal handlers for either parent or child. */
  897. void handle_signals(int is_parent)
  898. {
  899. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  900. struct sigaction action;
  901. action.sa_flags = 0;
  902. sigemptyset(&action.sa_mask);
  903. action.sa_handler = is_parent ? catch : SIG_IGN;
  904. sigaction(SIGINT, &action, NULL); /* do a controlled slow shutdown */
  905. sigaction(SIGTERM, &action, NULL); /* to terminate now */
  906. sigaction(SIGPIPE, &action, NULL); /* otherwise sigpipe kills us */
  907. sigaction(SIGUSR1, &action, NULL); /* dump stats */
  908. sigaction(SIGUSR2, &action, NULL); /* go to loglevel debug */
  909. sigaction(SIGHUP, &action, NULL); /* to reload config, retry conns, etc */
  910. #ifdef SIGXFSZ
  911. sigaction(SIGXFSZ, &action, NULL); /* handle file-too-big resource exhaustion */
  912. #endif
  913. if (is_parent)
  914. sigaction(SIGCHLD, &action, NULL); /* handle dns/cpu workers that exit */
  915. #endif /* signal stuff */
  916. }
  917. /** Main entry point for the Tor command-line client.
  918. */
  919. static int tor_init(int argc, char *argv[]) {
  920. /* Initialize the history structures. */
  921. rep_hist_init();
  922. /* Initialize the service cache. */
  923. rend_cache_init();
  924. client_dns_init(); /* Init the client dns cache. Do it always, since it's cheap. */
  925. /* give it somewhere to log to initially */
  926. add_temp_log();
  927. log_fn(LOG_NOTICE,"Tor v%s. This is experimental software. Do not rely on it for strong anonymity.",VERSION);
  928. if (network_init()<0) {
  929. log_fn(LOG_ERR,"Error initializing network; exiting.");
  930. return -1;
  931. }
  932. atexit(exit_function);
  933. if (init_from_config(argc,argv) < 0) {
  934. log_fn(LOG_ERR,"Reading config failed--see warnings above. For usage, try -h.");
  935. return -1;
  936. }
  937. #ifndef MS_WINDOWS
  938. if (geteuid()==0)
  939. log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
  940. #endif
  941. if (server_mode(get_options())) { /* only spawn dns handlers if we're a router */
  942. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  943. }
  944. handle_signals(1);
  945. crypto_global_init();
  946. crypto_seed_rng();
  947. return 0;
  948. }
  949. /** Do whatever cleanup is necessary before shutting Tor down. */
  950. void tor_cleanup(void) {
  951. or_options_t *options = get_options();
  952. /* Remove our pid file. We don't care if there was an error when we
  953. * unlink, nothing we could do about it anyways. */
  954. if (options->PidFile && options->command == CMD_RUN_TOR)
  955. unlink(options->PidFile);
  956. crypto_global_cleanup();
  957. if (accounting_is_enabled(options))
  958. accounting_record_bandwidth_usage(time(NULL));
  959. }
  960. /** Read/create keys as needed, and echo our fingerprint to stdout. */
  961. static void do_list_fingerprint(void)
  962. {
  963. char buf[FINGERPRINT_LEN+1];
  964. crypto_pk_env_t *k;
  965. const char *nickname = get_options()->Nickname;
  966. if (!server_mode(get_options())) {
  967. printf("Clients don't have long-term identity keys. Exiting.\n");
  968. return;
  969. }
  970. tor_assert(nickname);
  971. if (init_keys() < 0) {
  972. log_fn(LOG_ERR,"Error initializing keys; exiting");
  973. return;
  974. }
  975. if (!(k = get_identity_key())) {
  976. log_fn(LOG_ERR,"Error: missing identity key.");
  977. return;
  978. }
  979. if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
  980. log_fn(LOG_ERR, "Error computing fingerprint");
  981. return;
  982. }
  983. printf("%s %s\n", nickname, buf);
  984. }
  985. /** Entry point for password hashing: take the desired password from
  986. * the command line, and print its salted hash to stdout. **/
  987. static void do_hash_password(void)
  988. {
  989. char output[256];
  990. char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
  991. crypto_rand(key, S2K_SPECIFIER_LEN-1);
  992. key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
  993. secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
  994. get_options()->command_arg, strlen(get_options()->command_arg),
  995. key);
  996. if (base64_encode(output, sizeof(output), key, sizeof(key))<0) {
  997. log_fn(LOG_ERR, "Unable to compute base64");
  998. } else {
  999. printf("%s",output);
  1000. }
  1001. }
  1002. #ifdef MS_WINDOWS_SERVICE
  1003. void nt_service_control(DWORD request)
  1004. {
  1005. switch (request) {
  1006. case SERVICE_CONTROL_STOP:
  1007. case SERVICE_CONTROL_SHUTDOWN:
  1008. log(LOG_ERR, "Got stop/shutdown request; shutting down cleanly.");
  1009. service_status.dwCurrentState = SERVICE_STOP_PENDING;
  1010. return;
  1011. }
  1012. SetServiceStatus(hStatus, &service_status);
  1013. }
  1014. void nt_service_body(int argc, char **argv)
  1015. {
  1016. int err;
  1017. FILE *f;
  1018. service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  1019. service_status.dwCurrentState = SERVICE_START_PENDING;
  1020. service_status.dwControlsAccepted =
  1021. SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  1022. service_status.dwWin32ExitCode = 0;
  1023. service_status.dwServiceSpecificExitCode = 0;
  1024. service_status.dwCheckPoint = 0;
  1025. service_status.dwWaitHint = 1000;
  1026. hStatus = RegisterServiceCtrlHandler(GENSRV_SERVICENAME, (LPHANDLER_FUNCTION) nt_service_control);
  1027. if (hStatus == 0) {
  1028. // failed;
  1029. return;
  1030. }
  1031. err = tor_init(backup_argc, backup_argv); // refactor this part out of tor_main and do_main_loop
  1032. if (err) {
  1033. // failed.
  1034. service_status.dwCurrentState = SERVICE_STOPPED;
  1035. service_status.dwWin32ExitCode = -1;
  1036. SetServiceStatus(hStatus, &service_status);
  1037. return;
  1038. }
  1039. service_status.dwCurrentState = SERVICE_RUNNING;
  1040. SetServiceStatus(hStatus, &service_status);
  1041. do_main_loop();
  1042. tor_cleanup();
  1043. return;
  1044. }
  1045. void nt_service_main(void)
  1046. {
  1047. SERVICE_TABLE_ENTRY table[2];
  1048. DWORD result = 0;
  1049. table[0].lpServiceName = GENSRV_SERVICENAME;
  1050. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
  1051. table[1].lpServiceName = NULL;
  1052. table[1].lpServiceProc = NULL;
  1053. if (!StartServiceCtrlDispatcher(table)) {
  1054. result = GetLastError();
  1055. printf("Error was %d\n",result);
  1056. if (result == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
  1057. if (tor_init(backup_argc, backup_argv) < 0)
  1058. return;
  1059. switch (get_options()->command) {
  1060. case CMD_RUN_TOR:
  1061. do_main_loop();
  1062. break;
  1063. case CMD_LIST_FINGERPRINT:
  1064. do_list_fingerprint();
  1065. break;
  1066. case CMD_HASH_PASSWORD:
  1067. do_hash_password();
  1068. break;
  1069. default:
  1070. log_fn(LOG_ERR, "Illegal command number %d: internal error.", get_options()->command);
  1071. }
  1072. tor_cleanup();
  1073. }
  1074. }
  1075. }
  1076. int nt_service_install()
  1077. {
  1078. /* XXXX Problems with NT services:
  1079. * 1. The configuration file needs to be in the same directory as the .exe
  1080. * 2. The exe and the configuration file can't be on any directory path
  1081. * that contains a space.
  1082. * 3. Ideally, there should be one EXE that can either run as a
  1083. * separate process (as now) or that can install and run itself
  1084. * as an NT service. I have no idea how hard this is.
  1085. *
  1086. * Notes about develiping NT services:
  1087. *
  1088. * 1. Don't count on your CWD. If an abolute path is not given, the
  1089. * fopen() function goes wrong.
  1090. * 2. The parameters given to the nt_service_body() function differ
  1091. * from those given to main() function.
  1092. */
  1093. SC_HANDLE hSCManager = NULL;
  1094. SC_HANDLE hService = NULL;
  1095. TCHAR szPath[_MAX_PATH];
  1096. TCHAR szDrive[_MAX_DRIVE];
  1097. TCHAR szDir[_MAX_DIR];
  1098. char cmd1[] = " -f ";
  1099. char cmd2[] = "\\torrc";
  1100. char *command;
  1101. int len = 0;
  1102. if (0 == GetModuleFileName(NULL, szPath, MAX_PATH))
  1103. return 0;
  1104. _tsplitpath(szPath, szDrive, szDir, NULL, NULL);
  1105. len = _MAX_PATH + strlen(cmd1) + _MAX_DRIVE + _MAX_DIR + strlen(cmd2);
  1106. command = tor_malloc(len);
  1107. strlcpy(command, szPath, len);
  1108. strlcat(command, " -f ", len);
  1109. strlcat(command, szDrive, len);
  1110. strlcat(command, szDir, len);
  1111. strlcat(command, "\\torrc", len);
  1112. if ((hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
  1113. printf("Failed: OpenSCManager()\n");
  1114. free(command);
  1115. return 0;
  1116. }
  1117. if ((hService = CreateService(hSCManager, GENSRV_SERVICENAME, GENSRV_DISPLAYNAME,
  1118. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  1119. SERVICE_DEMAND_START, SERVICE_ERROR_IGNORE, command,
  1120. NULL, NULL, NULL, NULL, NULL)) == NULL) {
  1121. printf("Failed: CreateService()\n");
  1122. CloseServiceHandle(hSCManager);
  1123. free(command);
  1124. return 0;
  1125. }
  1126. CloseServiceHandle(hService);
  1127. CloseServiceHandle(hSCManager);
  1128. free(command);
  1129. printf("Install service successfully\n");
  1130. return 0;
  1131. }
  1132. int nt_service_remove()
  1133. {
  1134. SC_HANDLE hSCManager = NULL;
  1135. SC_HANDLE hService = NULL;
  1136. SERVICE_STATUS service_status;
  1137. BOOL result = FALSE;
  1138. if ((hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
  1139. printf("Failed: OpenSCManager()\n");
  1140. return 0;
  1141. }
  1142. if ((hService = OpenService(hSCManager, GENSRV_SERVICENAME, SERVICE_ALL_ACCESS)) == NULL) {
  1143. printf("Failed: OpenService()\n");
  1144. CloseServiceHandle(hSCManager);
  1145. }
  1146. result = ControlService(hService, SERVICE_CONTROL_STOP, &service_status);
  1147. if (result) {
  1148. while (QueryServiceStatus(hService, &service_status))
  1149. {
  1150. if (service_status.dwCurrentState == SERVICE_STOP_PENDING)
  1151. Sleep(500);
  1152. else
  1153. break;
  1154. }
  1155. if (DeleteService(hService))
  1156. printf("Remove service successfully\n");
  1157. else
  1158. printf("Failed: DeleteService()\n");
  1159. } else {
  1160. result = DeleteService(hService);
  1161. if (result)
  1162. printf("Remove service successfully\n");
  1163. else
  1164. printf("Failed: DeleteService()\n");
  1165. }
  1166. CloseServiceHandle(hService);
  1167. CloseServiceHandle(hSCManager);
  1168. return 0;
  1169. }
  1170. #endif
  1171. int tor_main(int argc, char *argv[]) {
  1172. #ifdef MS_WINDOWS_SERVICE
  1173. backup_argv = argv;
  1174. backup_argc = argc;
  1175. if ((argc >= 2) && !strcmp(argv[1], "-install"))
  1176. return nt_service_install();
  1177. if ((argc >= 2) && !strcmp(argv[1], "-remove"))
  1178. return nt_service_remove();
  1179. nt_service_main();
  1180. return 0;
  1181. #else
  1182. if (tor_init(argc, argv)<0)
  1183. return -1;
  1184. switch (get_options()->command) {
  1185. case CMD_RUN_TOR:
  1186. do_main_loop();
  1187. break;
  1188. case CMD_LIST_FINGERPRINT:
  1189. do_list_fingerprint();
  1190. break;
  1191. case CMD_HASH_PASSWORD:
  1192. do_hash_password();
  1193. break;
  1194. default:
  1195. log_fn(LOG_ERR, "Illegal command number %d: internal error.",
  1196. get_options()->command);
  1197. }
  1198. tor_cleanup();
  1199. return -1;
  1200. #endif
  1201. }