main.c 45 KB

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