main.c 45 KB

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