main.c 45 KB

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