main.c 40 KB

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