main.c 39 KB

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