main.c 44 KB

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