main.c 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004-2005 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 Toplevel module. Handles signals, multiplexes between
  10. * connections, implements main loop, and drives scheduled events.
  11. **/
  12. #include "or.h"
  13. #ifdef USE_DMALLOC
  14. #include <dmalloc.h>
  15. #endif
  16. /********* PROTOTYPES **********/
  17. static void dumpmemusage(int severity);
  18. static void dumpstats(int severity); /* log stats */
  19. static void conn_read_callback(int fd, short event, void *_conn);
  20. static void conn_write_callback(int fd, short event, void *_conn);
  21. static void signal_callback(int fd, short events, void *arg);
  22. static void second_elapsed_callback(int fd, short event, void *args);
  23. static int conn_close_if_marked(int i);
  24. /********* START VARIABLES **********/
  25. int global_read_bucket; /**< Max number of bytes I can read this second. */
  26. int global_write_bucket; /**< Max number of bytes I can write this second. */
  27. /** What was the read bucket before the last call to prepare_for_pool?
  28. * (used to determine how many bytes we've read). */
  29. static int stats_prev_global_read_bucket;
  30. /** What was the write bucket before the last call to prepare_for_pool?
  31. * (used to determine how many bytes we've written). */
  32. static int stats_prev_global_write_bucket;
  33. /** How many bytes have we read/written since we started the process? */
  34. static uint64_t stats_n_bytes_read = 0;
  35. static uint64_t stats_n_bytes_written = 0;
  36. /** What time did this process start up? */
  37. long time_of_process_start = 0;
  38. /** How many seconds have we been running? */
  39. long stats_n_seconds_working = 0;
  40. /** When do we next download a directory? */
  41. static time_t time_to_fetch_directory = 0;
  42. /** When do we next download a running-routers summary? */
  43. static time_t time_to_fetch_running_routers = 0;
  44. /** Array of all open connections; each element corresponds to the element of
  45. * poll_array in the same position. The first nfds elements are valid. */
  46. static connection_t *connection_array[MAXCONNECTIONS+1] =
  47. { NULL };
  48. static smartlist_t *closeable_connection_lst = NULL;
  49. static int nfds=0; /**< Number of connections currently active. */
  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. #ifdef MS_WINDOWS
  58. #define MS_WINDOWS_SERVICE
  59. #endif
  60. #ifdef MS_WINDOWS_SERVICE
  61. #include <tchar.h>
  62. #define GENSRV_SERVICENAME TEXT("tor")
  63. #define GENSRV_DISPLAYNAME TEXT("Tor Win32 Service")
  64. #define GENSRV_DESCRIPTION TEXT("Provides an anonymous Internet communication system")
  65. // Cheating: using the pre-defined error codes, tricks Windows into displaying
  66. // a semi-related human-readable error message if startup fails as
  67. // opposed to simply scaring people with Error: 0xffffffff
  68. #define NT_SERVICE_ERROR_NO_TORRC ERROR_FILE_NOT_FOUND
  69. #define NT_SERVICE_ERROR_TORINIT_FAILED ERROR_EXCEPTION_IN_SERVICE
  70. SERVICE_STATUS service_status;
  71. SERVICE_STATUS_HANDLE hStatus;
  72. static char **backup_argv;
  73. static int backup_argc;
  74. static int nt_service_is_stopped(void);
  75. static char* nt_strerror(uint32_t errnum);
  76. #else
  77. #define nt_service_is_stopped() (0)
  78. #endif
  79. #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL 18*60*60 /* 18 hours */
  80. #define CHECK_DESCRIPTOR_INTERVAL 60 /* one minute */
  81. #define BUF_SHRINK_INTERVAL 60 /* one minute */
  82. #define DESCRIPTOR_RETRY_INTERVAL 10
  83. #define DESCRIPTOR_FAILURE_RESET_INTERVAL 60*60
  84. #define TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT (20*60) /* 20 minutes */
  85. /********* END VARIABLES ************/
  86. /****************************************************************************
  87. *
  88. * This section contains accessors and other methods on the connection_array
  89. * and poll_array variables (which are global within this file and unavailable
  90. * outside it).
  91. *
  92. ****************************************************************************/
  93. /** Add <b>conn</b> to the array of connections that we can poll on. The
  94. * connection's socket must be set; the connection starts out
  95. * non-reading and non-writing.
  96. */
  97. int
  98. connection_add(connection_t *conn)
  99. {
  100. tor_assert(conn);
  101. tor_assert(conn->s >= 0);
  102. if (nfds >= get_options()->_ConnLimit-1) {
  103. log_fn(LOG_WARN,"Failing because we have %d connections already. Please raise your ulimit -n.", nfds);
  104. return -1;
  105. }
  106. tor_assert(conn->poll_index == -1); /* can only connection_add once */
  107. conn->poll_index = nfds;
  108. connection_array[nfds] = conn;
  109. conn->read_event = tor_malloc_zero(sizeof(struct event));
  110. conn->write_event = tor_malloc_zero(sizeof(struct event));
  111. event_set(conn->read_event, conn->s, EV_READ|EV_PERSIST,
  112. conn_read_callback, conn);
  113. event_set(conn->write_event, conn->s, EV_WRITE|EV_PERSIST,
  114. conn_write_callback, conn);
  115. nfds++;
  116. log_fn(LOG_INFO,"new conn type %s, socket %d, nfds %d.",
  117. conn_type_to_string(conn->type), conn->s, nfds);
  118. return 0;
  119. }
  120. /** Remove the connection from the global list, and remove the
  121. * corresponding poll entry. Calling this function will shift the last
  122. * connection (if any) into the position occupied by conn.
  123. */
  124. int
  125. connection_remove(connection_t *conn)
  126. {
  127. int current_index;
  128. tor_assert(conn);
  129. tor_assert(nfds>0);
  130. log_fn(LOG_INFO,"removing socket %d (type %s), nfds now %d",
  131. conn->s, conn_type_to_string(conn->type), nfds-1);
  132. tor_assert(conn->poll_index >= 0);
  133. current_index = conn->poll_index;
  134. if (current_index == nfds-1) { /* this is the end */
  135. nfds--;
  136. return 0;
  137. }
  138. connection_unregister(conn);
  139. /* replace this one with the one at the end */
  140. nfds--;
  141. connection_array[current_index] = connection_array[nfds];
  142. connection_array[current_index]->poll_index = current_index;
  143. return 0;
  144. }
  145. /** If it's an edge conn, remove it from the list
  146. * of conn's on this circuit. If it's not on an edge,
  147. * flush and send destroys for all circuits on this conn.
  148. *
  149. * If <b>remove</b> is non-zero, then remove it from the
  150. * connection_array and closeable_connection_lst.
  151. *
  152. * Then free it.
  153. */
  154. static void
  155. connection_unlink(connection_t *conn, int remove)
  156. {
  157. circuit_about_to_close_connection(conn);
  158. connection_about_to_close_connection(conn);
  159. if (remove) {
  160. connection_remove(conn);
  161. }
  162. smartlist_remove(closeable_connection_lst, conn);
  163. if (conn->type == CONN_TYPE_EXIT) {
  164. assert_connection_edge_not_dns_pending(conn);
  165. }
  166. connection_free(conn);
  167. }
  168. /** Schedule <b>conn</b> to be closed. **/
  169. void
  170. add_connection_to_closeable_list(connection_t *conn)
  171. {
  172. tor_assert(!smartlist_isin(closeable_connection_lst, conn));
  173. tor_assert(conn->marked_for_close);
  174. assert_connection_ok(conn, time(NULL));
  175. smartlist_add(closeable_connection_lst, conn);
  176. }
  177. /** Return 1 if conn is on the closeable list, else return 0. */
  178. int
  179. connection_is_on_closeable_list(connection_t *conn)
  180. {
  181. return smartlist_isin(closeable_connection_lst, conn);
  182. }
  183. /** Return true iff conn is in the current poll array. */
  184. int
  185. connection_in_array(connection_t *conn)
  186. {
  187. int i;
  188. for (i=0; i<nfds; ++i) {
  189. if (conn==connection_array[i])
  190. return 1;
  191. }
  192. return 0;
  193. }
  194. /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
  195. * to the length of the array. <b>*array</b> and <b>*n</b> must not
  196. * be modified.
  197. */
  198. void
  199. get_connection_array(connection_t ***array, int *n)
  200. {
  201. *array = connection_array;
  202. *n = nfds;
  203. }
  204. /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
  205. * mask is a bitmask whose bits are EV_READ and EV_WRITE.)
  206. */
  207. void
  208. connection_watch_events(connection_t *conn, short events)
  209. {
  210. int r;
  211. tor_assert(conn);
  212. tor_assert(conn->read_event);
  213. tor_assert(conn->write_event);
  214. if (events & EV_READ) {
  215. r = event_add(conn->read_event, NULL);
  216. } else {
  217. r = event_del(conn->read_event);
  218. }
  219. if (r<0)
  220. log_fn(LOG_WARN,
  221. "Error from libevent setting read event state for %d to %swatched.",
  222. conn->s, (events & EV_READ)?"":"un");
  223. if (events & EV_WRITE) {
  224. r = event_add(conn->write_event, NULL);
  225. } else {
  226. r = event_del(conn->write_event);
  227. }
  228. if (r<0)
  229. log_fn(LOG_WARN,
  230. "Error from libevent setting read event state for %d to %swatched.",
  231. conn->s, (events & EV_WRITE)?"":"un");
  232. }
  233. /** Return true iff <b>conn</b> is listening for read events. */
  234. int
  235. connection_is_reading(connection_t *conn)
  236. {
  237. tor_assert(conn);
  238. return conn->read_event && event_pending(conn->read_event, EV_READ, NULL);
  239. }
  240. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  241. void
  242. connection_stop_reading(connection_t *conn)
  243. {
  244. tor_assert(conn);
  245. tor_assert(conn->read_event);
  246. log(LOG_DEBUG,"connection_stop_reading() called.");
  247. if (event_del(conn->read_event))
  248. log_fn(LOG_WARN, "Error from libevent setting read event state for %d to unwatched.",
  249. conn->s);
  250. }
  251. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  252. void
  253. connection_start_reading(connection_t *conn)
  254. {
  255. tor_assert(conn);
  256. tor_assert(conn->read_event);
  257. if (event_add(conn->read_event, NULL))
  258. log_fn(LOG_WARN, "Error from libevent setting read event state for %d to watched.",
  259. conn->s);
  260. }
  261. /** Return true iff <b>conn</b> is listening for write events. */
  262. int
  263. connection_is_writing(connection_t *conn)
  264. {
  265. tor_assert(conn);
  266. return conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL);
  267. }
  268. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  269. void
  270. connection_stop_writing(connection_t *conn)
  271. {
  272. tor_assert(conn);
  273. tor_assert(conn->write_event);
  274. if (event_del(conn->write_event))
  275. log_fn(LOG_WARN, "Error from libevent setting write event state for %d to unwatched.",
  276. conn->s);
  277. }
  278. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  279. void
  280. connection_start_writing(connection_t *conn)
  281. {
  282. tor_assert(conn);
  283. tor_assert(conn->write_event);
  284. if (event_add(conn->write_event, NULL))
  285. log_fn(LOG_WARN, "Error from libevent setting write event state for %d to watched.",
  286. conn->s);
  287. }
  288. /** Close all connections that have been scheduled to get closed */
  289. static void
  290. close_closeable_connections(void)
  291. {
  292. int i;
  293. for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
  294. connection_t *conn = smartlist_get(closeable_connection_lst, i);
  295. if (conn->poll_index < 0) {
  296. connection_unlink(conn, 0); /* blow it away right now */
  297. } else {
  298. if (!conn_close_if_marked(conn->poll_index))
  299. ++i;
  300. }
  301. }
  302. }
  303. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  304. * some data to read. */
  305. static void
  306. conn_read_callback(int fd, short event, void *_conn)
  307. {
  308. connection_t *conn = _conn;
  309. LOG_FN_CONN(conn, (LOG_DEBUG,"socket %d wants to read.",conn->s));
  310. assert_connection_ok(conn, time(NULL));
  311. if (connection_handle_read(conn) < 0) {
  312. if (!conn->marked_for_close) {
  313. #ifndef MS_WINDOWS
  314. log_fn(LOG_WARN,"Bug: unhandled error on read for %s connection (fd %d); removing",
  315. conn_type_to_string(conn->type), conn->s);
  316. tor_fragile_assert();
  317. #endif
  318. if (CONN_IS_EDGE(conn))
  319. connection_edge_end_errno(conn, conn->cpath_layer);
  320. connection_mark_for_close(conn);
  321. }
  322. }
  323. assert_connection_ok(conn, time(NULL));
  324. if (smartlist_len(closeable_connection_lst))
  325. close_closeable_connections();
  326. }
  327. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  328. * some data to write. */
  329. static void
  330. conn_write_callback(int fd, short events, void *_conn)
  331. {
  332. connection_t *conn = _conn;
  333. LOG_FN_CONN(conn, (LOG_DEBUG,"socket %d wants to write.",conn->s));
  334. assert_connection_ok(conn, time(NULL));
  335. if (connection_handle_write(conn) < 0) {
  336. if (!conn->marked_for_close) {
  337. /* this connection is broken. remove it. */
  338. log_fn(LOG_WARN,"Bug: unhandled error on write for %s connection (fd %d); removing",
  339. conn_type_to_string(conn->type), conn->s);
  340. tor_fragile_assert();
  341. conn->has_sent_end = 1; /* otherwise we cry wolf about duplicate close */
  342. /* XXX do we need a close-immediate here, so we don't try to flush? */
  343. connection_mark_for_close(conn);
  344. }
  345. }
  346. assert_connection_ok(conn, time(NULL));
  347. if (smartlist_len(closeable_connection_lst))
  348. close_closeable_connections();
  349. }
  350. /** If the connection at connection_array[i] is marked for close, then:
  351. * - If it has data that it wants to flush, try to flush it.
  352. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  353. * true, then leave the connection open and return.
  354. * - Otherwise, remove the connection from connection_array and from
  355. * all other lists, close it, and free it.
  356. * Returns 1 if the connection was closed, 0 otherwise.
  357. */
  358. static int
  359. conn_close_if_marked(int i)
  360. {
  361. connection_t *conn;
  362. int retval;
  363. conn = connection_array[i];
  364. if (!conn->marked_for_close)
  365. return 0; /* nothing to see here, move along */
  366. assert_connection_ok(conn, time(NULL));
  367. assert_all_pending_dns_resolves_ok();
  368. log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
  369. if (conn->s >= 0 && connection_wants_to_flush(conn)) {
  370. /* -1 means it's an incomplete edge connection, or that the socket
  371. * has already been closed as unflushable. */
  372. if (!conn->hold_open_until_flushed)
  373. log_fn(LOG_INFO,
  374. "Conn (addr %s, fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
  375. "(Marked at %s:%d)",
  376. conn->address, conn->s, conn_type_to_string(conn->type), conn->state,
  377. (int)conn->outbuf_flushlen, conn->marked_for_close_file, conn->marked_for_close);
  378. if (connection_speaks_cells(conn)) {
  379. if (conn->state == OR_CONN_STATE_OPEN) {
  380. retval = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  381. } else
  382. retval = -1; /* never flush non-open broken tls connections */
  383. } else {
  384. retval = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  385. }
  386. if (retval >= 0 &&
  387. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  388. LOG_FN_CONN(conn,
  389. (LOG_INFO,"Holding conn (fd %d) open for more flushing.",conn->s));
  390. /* XXX should we reset timestamp_lastwritten here? */
  391. return 0;
  392. }
  393. if (connection_wants_to_flush(conn)) {
  394. log_fn(LOG_NOTICE,"Something wrong with your network connection? Conn (addr %s, fd %d, type %s, state %d) tried to write %d bytes but timed out. (Marked at %s:%d)",
  395. safe_str(conn->address), conn->s, conn_type_to_string(conn->type),
  396. conn->state,
  397. (int)buf_datalen(conn->outbuf), conn->marked_for_close_file,
  398. conn->marked_for_close);
  399. }
  400. }
  401. connection_unlink(conn, 1); /* unlink, remove, free */
  402. return 1;
  403. }
  404. /** We've just tried every dirserver we know about, and none of
  405. * them were reachable. Assume the network is down. Change state
  406. * so next time an application connection arrives we'll delay it
  407. * and try another directory fetch. Kill off all the circuit_wait
  408. * streams that are waiting now, since they will all timeout anyway.
  409. */
  410. void
  411. directory_all_unreachable(time_t now)
  412. {
  413. connection_t *conn;
  414. /* XXXX011 NM Update this to reflect new directories? */
  415. has_fetched_directory=0;
  416. stats_n_seconds_working=0; /* reset it */
  417. while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
  418. AP_CONN_STATE_CIRCUIT_WAIT))) {
  419. log_fn(LOG_NOTICE,"Network down? Failing connection to '%s:%d'.",
  420. safe_str(conn->socks_request->address), conn->socks_request->port);
  421. connection_mark_unattached_ap(conn, END_STREAM_REASON_NET_UNREACHABLE);
  422. }
  423. }
  424. /**
  425. * Return the interval to wait betweeen directory downloads, in seconds.
  426. */
  427. static INLINE int
  428. get_dir_fetch_period(or_options_t *options)
  429. {
  430. if (options->DirFetchPeriod)
  431. /* Value from config file. */
  432. return options->DirFetchPeriod;
  433. else if (options->DirPort)
  434. /* Default for directory server */
  435. return 20*60;
  436. else
  437. /* Default for average user. */
  438. return 40*60;
  439. }
  440. /**
  441. * Return the interval to wait betweeen router status downloads, in seconds.
  442. */
  443. static INLINE int
  444. get_status_fetch_period(or_options_t *options)
  445. {
  446. if (options->StatusFetchPeriod)
  447. /* Value from config file. */
  448. return options->StatusFetchPeriod;
  449. else if (options->DirPort)
  450. /* Default for directory server */
  451. return 15*60;
  452. else
  453. /* Default for average user. */
  454. return 30*60;
  455. }
  456. /** This function is called whenever we successfully pull down some new
  457. * network statuses or server descriptors. */
  458. void
  459. directory_info_has_arrived(time_t now, int from_cache)
  460. {
  461. or_options_t *options = get_options();
  462. if (!router_have_minimum_dir_info()) {
  463. log_fn(LOG_NOTICE, "I learned some more directory information, but not enough to build a circuit.");
  464. return;
  465. }
  466. if (!has_fetched_directory) {
  467. log_fn(LOG_NOTICE, "We have enough directory information to build circuits.");
  468. }
  469. has_fetched_directory=1;
  470. if (server_mode(options) &&
  471. !we_are_hibernating()) { /* connect to the appropriate routers */
  472. if (!authdir_mode(options))
  473. router_retry_connections(0);
  474. if (!from_cache)
  475. consider_testing_reachability();
  476. }
  477. }
  478. /** Perform regular maintenance tasks for a single connection. This
  479. * function gets run once per second per connection by run_scheduled_events.
  480. */
  481. static void
  482. run_connection_housekeeping(int i, time_t now)
  483. {
  484. cell_t cell;
  485. connection_t *conn = connection_array[i];
  486. or_options_t *options = get_options();
  487. if (conn->outbuf && !buf_datalen(conn->outbuf))
  488. conn->timestamp_lastempty = now;
  489. /* Expire any directory connections that haven't sent anything for 5 min */
  490. if (conn->type == CONN_TYPE_DIR &&
  491. !conn->marked_for_close &&
  492. conn->timestamp_lastwritten + 5*60 < now) {
  493. log_fn(LOG_INFO,"Expiring wedged directory conn (fd %d, purpose %d)",
  494. conn->s, conn->purpose);
  495. /* This check is temporary; it's to let us know whether we should consider
  496. * parsing partial serverdesc responses. */
  497. if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  498. buf_datalen(conn->inbuf)>=(24*1024)) {
  499. log_fn(LOG_NOTICE, "Expired a wedged directory connection that had already downloaded %d bytes of descriptors. If this happens often, please file a bug report.",
  500. (int)buf_datalen(conn->inbuf));
  501. }
  502. connection_mark_for_close(conn);
  503. return;
  504. }
  505. /* If we haven't written to an OR connection for a while, then either nuke
  506. the connection or send a keepalive, depending. */
  507. if (connection_speaks_cells(conn) &&
  508. now >= conn->timestamp_lastwritten + options->KeepalivePeriod) {
  509. routerinfo_t *router = router_get_by_digest(conn->identity_digest);
  510. if (!connection_state_is_open(conn)) {
  511. log_fn(LOG_INFO,"Expiring non-open OR connection to fd %d (%s:%d).",
  512. conn->s,conn->address, conn->port);
  513. connection_mark_for_close(conn);
  514. conn->hold_open_until_flushed = 1;
  515. } else if (we_are_hibernating() && !circuit_get_by_conn(conn) &&
  516. !buf_datalen(conn->outbuf)) {
  517. log_fn(LOG_INFO,"Expiring non-used OR connection to fd %d (%s:%d) [Hibernating or exiting].",
  518. conn->s,conn->address, conn->port);
  519. connection_mark_for_close(conn);
  520. conn->hold_open_until_flushed = 1;
  521. } else if (!clique_mode(options) && !circuit_get_by_conn(conn) &&
  522. (!router || !server_mode(options) || !router_is_clique_mode(router))) {
  523. log_fn(LOG_INFO,"Expiring non-used OR connection to fd %d (%s:%d) [Not in clique mode].",
  524. conn->s,conn->address, conn->port);
  525. connection_mark_for_close(conn);
  526. conn->hold_open_until_flushed = 1;
  527. } else if (
  528. now >= conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
  529. now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
  530. log_fn(LOG_NOTICE,"Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to flush; %d seconds since last write)",
  531. conn->s, conn->address, conn->port,
  532. (int)buf_datalen(conn->outbuf),
  533. (int)(now-conn->timestamp_lastwritten));
  534. connection_mark_for_close(conn);
  535. } else if (!buf_datalen(conn->outbuf)) {
  536. /* either in clique mode, or we've got a circuit. send a padding cell. */
  537. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  538. conn->address, conn->port);
  539. memset(&cell,0,sizeof(cell_t));
  540. cell.command = CELL_PADDING;
  541. connection_or_write_cell_to_buf(&cell, conn);
  542. }
  543. }
  544. }
  545. /** Perform regular maintenance tasks. This function gets run once per
  546. * second by prepare_for_poll.
  547. */
  548. static void
  549. run_scheduled_events(time_t now)
  550. {
  551. static time_t last_rotated_certificate = 0;
  552. static time_t time_to_check_listeners = 0;
  553. static time_t time_to_check_descriptor = 0;
  554. static time_t time_to_shrink_buffers = 0;
  555. static time_t time_to_try_getting_descriptors = 0;
  556. static time_t time_to_reset_descriptor_failures = 0;
  557. or_options_t *options = get_options();
  558. int i;
  559. /** 0. See if we've been asked to shut down and our timeout has
  560. * expired; or if our bandwidth limits are exhausted and we
  561. * should hibernate; or if it's time to wake up from hibernation.
  562. */
  563. consider_hibernation(now);
  564. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  565. * shut down and restart all cpuworkers, and update the directory if
  566. * necessary.
  567. */
  568. if (server_mode(options) &&
  569. get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  570. log_fn(LOG_INFO,"Rotating onion key.");
  571. rotate_onion_key();
  572. cpuworkers_rotate();
  573. if (router_rebuild_descriptor(1)<0) {
  574. log_fn(LOG_WARN, "Couldn't rebuild router descriptor");
  575. }
  576. if (advertised_server_mode())
  577. router_upload_dir_desc_to_dirservers(0);
  578. }
  579. if (time_to_try_getting_descriptors < now) {
  580. update_router_descriptor_downloads(now);
  581. time_to_try_getting_descriptors = now + DESCRIPTOR_RETRY_INTERVAL;
  582. }
  583. if (time_to_reset_descriptor_failures < now) {
  584. router_reset_descriptor_download_failures();
  585. time_to_reset_descriptor_failures = now + DESCRIPTOR_FAILURE_RESET_INTERVAL;
  586. }
  587. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  588. if (!last_rotated_certificate)
  589. last_rotated_certificate = now;
  590. if (last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
  591. log_fn(LOG_INFO,"Rotating tls context.");
  592. if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
  593. MAX_SSL_KEY_LIFETIME) < 0) {
  594. log_fn(LOG_WARN, "Error reinitializing TLS context");
  595. /* XXX is it a bug here, that we just keep going? */
  596. }
  597. last_rotated_certificate = now;
  598. /* XXXX We should rotate TLS connections as well; this code doesn't change
  599. * them at all. */
  600. }
  601. /** 1c. If we have to change the accounting interval or record
  602. * bandwidth used in this accounting interval, do so. */
  603. if (accounting_is_enabled(options))
  604. accounting_run_housekeeping(now);
  605. /** 2. Periodically, we consider getting a new directory, getting a
  606. * new running-routers list, and/or force-uploading our descriptor
  607. * (if we've passed our internal checks). */
  608. if (time_to_fetch_directory < now) {
  609. /* purge obsolete entries */
  610. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  611. networkstatus_list_clean(now);
  612. if (authdir_mode(options)) {
  613. if (!we_are_hibernating()) { /* try to determine reachability */
  614. router_retry_connections(1);
  615. }
  616. }
  617. /* Only caches actually need to fetch directories now. */
  618. if (options->DirPort && !options->V1AuthoritativeDir) {
  619. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
  620. }
  621. time_to_fetch_directory = now + get_dir_fetch_period(options);
  622. /* Also, take this chance to remove old information from rephist
  623. * and the rend cache. */
  624. rep_history_clean(now - options->RephistTrackTime);
  625. rend_cache_clean();
  626. }
  627. /* Caches need to fetch running_routers; directory clients don't. */
  628. if (options->DirPort && time_to_fetch_running_routers < now) {
  629. if (!authdir_mode(options) || !options->V1AuthoritativeDir) {
  630. directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST, NULL, 1);
  631. }
  632. time_to_fetch_running_routers = now + get_status_fetch_period(options);
  633. }
  634. /* 2b. Once per minute, regenerate and upload the descriptor if the old
  635. * one is inaccurate. */
  636. if (time_to_check_descriptor < now) {
  637. time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
  638. check_descriptor_bandwidth_changed(now);
  639. mark_my_descriptor_dirty_if_older_than(
  640. now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL);
  641. consider_publishable_server(now, 0);
  642. /* also, check religiously for reachability, if it's within the first
  643. * 20 minutes of our uptime. */
  644. if (server_mode(options) &&
  645. stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT &&
  646. !we_are_hibernating())
  647. consider_testing_reachability();
  648. /* If any networkstatus documents are no longer recent, we need to
  649. * update all the descriptors' running status. */
  650. networkstatus_list_update_recent(now);
  651. routers_update_all_from_networkstatus();
  652. /* Also, once per minute, check whether we want to download any
  653. * networkstatus documents.
  654. */
  655. update_networkstatus_downloads(now);
  656. }
  657. /** 3a. Every second, we examine pending circuits and prune the
  658. * ones which have been pending for more than a few seconds.
  659. * We do this before step 4, so it can try building more if
  660. * it's not comfortable with the number of available circuits.
  661. */
  662. circuit_expire_building(now);
  663. /** 3b. Also look at pending streams and prune the ones that 'began'
  664. * a long time ago but haven't gotten a 'connected' yet.
  665. * Do this before step 4, so we can put them back into pending
  666. * state to be picked up by the new circuit.
  667. */
  668. connection_ap_expire_beginning();
  669. /** 3c. And expire connections that we've held open for too long.
  670. */
  671. connection_expire_held_open();
  672. /** 3d. And every 60 seconds, we relaunch listeners if any died. */
  673. if (!we_are_hibernating() && time_to_check_listeners < now) {
  674. /* 0 means "only launch the ones that died." */
  675. retry_all_listeners(0, NULL, NULL);
  676. time_to_check_listeners = now+60;
  677. }
  678. /** 4. Every second, we try a new circuit if there are no valid
  679. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  680. * that became dirty more than MaxCircuitDirtiness seconds ago,
  681. * and we make a new circ if there are no clean circuits.
  682. */
  683. if (has_fetched_directory && !we_are_hibernating())
  684. circuit_build_needed_circs(now);
  685. /** 5. We do housekeeping for each connection... */
  686. for (i=0;i<nfds;i++) {
  687. run_connection_housekeeping(i, now);
  688. }
  689. if (time_to_shrink_buffers < now) {
  690. for (i=0;i<nfds;i++) {
  691. connection_t *conn = connection_array[i];
  692. if (conn->outbuf)
  693. buf_shrink(conn->outbuf);
  694. if (conn->inbuf)
  695. buf_shrink(conn->inbuf);
  696. }
  697. time_to_shrink_buffers = now + BUF_SHRINK_INTERVAL;
  698. }
  699. /** 6. And remove any marked circuits... */
  700. circuit_close_all_marked();
  701. /** 7. And upload service descriptors if necessary. */
  702. if (has_fetched_directory && !we_are_hibernating())
  703. rend_consider_services_upload(now);
  704. /** 8. and blow away any connections that need to die. have to do this now,
  705. * because if we marked a conn for close and left its socket -1, then
  706. * we'll pass it to poll/select and bad things will happen.
  707. */
  708. close_closeable_connections();
  709. }
  710. static struct event *timeout_event = NULL;
  711. static int n_libevent_errors = 0;
  712. /** Libevent callback: invoked once every second. */
  713. static void
  714. second_elapsed_callback(int fd, short event, void *args)
  715. {
  716. static struct timeval one_second;
  717. static long current_second = 0;
  718. struct timeval now;
  719. size_t bytes_written;
  720. size_t bytes_read;
  721. int seconds_elapsed;
  722. or_options_t *options = get_options();
  723. if (!timeout_event) {
  724. timeout_event = tor_malloc_zero(sizeof(struct event));
  725. evtimer_set(timeout_event, second_elapsed_callback, NULL);
  726. one_second.tv_sec = 1;
  727. one_second.tv_usec = 0;
  728. }
  729. n_libevent_errors = 0;
  730. /* log_fn(LOG_NOTICE, "Tick."); */
  731. tor_gettimeofday(&now);
  732. /* the second has rolled over. check more stuff. */
  733. bytes_written = stats_prev_global_write_bucket - global_write_bucket;
  734. bytes_read = stats_prev_global_read_bucket - global_read_bucket;
  735. /* XXX below we get suspicious if time jumps forward more than 10
  736. * seconds, but we never notice if it jumps *back* more than 10 seconds.
  737. * This could be useful for detecting that we just NTP'ed to three
  738. * weeks ago and it will be 3 weeks and 15 minutes until any of our
  739. * events trigger.
  740. */
  741. seconds_elapsed = current_second ? (now.tv_sec - current_second) : 0;
  742. stats_n_bytes_read += bytes_read;
  743. stats_n_bytes_written += bytes_written;
  744. if (accounting_is_enabled(options))
  745. accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
  746. control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
  747. connection_bucket_refill(&now);
  748. stats_prev_global_read_bucket = global_read_bucket;
  749. stats_prev_global_write_bucket = global_write_bucket;
  750. if (server_mode(options) &&
  751. !we_are_hibernating() &&
  752. stats_n_seconds_working / TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT !=
  753. (stats_n_seconds_working+seconds_elapsed) /
  754. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
  755. /* every 20 minutes, check and complain if necessary */
  756. routerinfo_t *me = router_get_my_routerinfo();
  757. if (me && !check_whether_orport_reachable())
  758. log(LOG_WARN,"Your server (%s:%d) has not managed to confirm that its ORPort is reachable. Please check your firewalls, ports, address, /etc/hosts file, etc.",
  759. me->address, me->or_port);
  760. if (me && !check_whether_dirport_reachable())
  761. log(LOG_WARN,"Your server (%s:%d) has not managed to confirm that its DirPort is reachable. Please check your firewalls, ports, address, /etc/hosts file, etc.",
  762. me->address, me->dir_port);
  763. }
  764. /* if more than 100s have elapsed, probably the clock jumped: doesn't count. */
  765. if (seconds_elapsed < 100)
  766. stats_n_seconds_working += seconds_elapsed;
  767. else
  768. circuit_note_clock_jumped(seconds_elapsed);
  769. run_scheduled_events(now.tv_sec);
  770. current_second = now.tv_sec; /* remember which second it is, for next time */
  771. #if 0
  772. if (current_second % 300 == 0) {
  773. rep_history_clean(current_second - options->RephistTrackTime);
  774. dumpmemusage(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
  775. }
  776. #endif
  777. if (evtimer_add(timeout_event, &one_second))
  778. log_fn(LOG_ERR,
  779. "Error from libevent when setting one-second timeout event");
  780. }
  781. /** Called when a possibly ignorable libevent error occurs; ensures that we
  782. * don't get into an infinite loop by ignoring too many errors from
  783. * libevent. */
  784. static int
  785. got_libevent_error(void)
  786. {
  787. if (++n_libevent_errors > 8) {
  788. log_fn(LOG_ERR, "Too many libevent errors in one second; dying");
  789. return -1;
  790. }
  791. return 0;
  792. }
  793. /** Called when we get a SIGHUP: reload configuration files and keys,
  794. * retry all connections, re-upload all descriptors, and so on. */
  795. static int
  796. do_hup(void)
  797. {
  798. char keydir[512];
  799. or_options_t *options = get_options();
  800. log(LOG_NOTICE,"Received sighup. Reloading config.");
  801. has_completed_circuit=0;
  802. if (accounting_is_enabled(options))
  803. accounting_record_bandwidth_usage(time(NULL));
  804. router_reset_warnings();
  805. routerlist_reset_warnings();
  806. addressmap_clear_transient();
  807. /* first, reload config variables, in case they've changed */
  808. /* no need to provide argc/v, they've been cached inside init_from_config */
  809. if (options_init_from_torrc(0, NULL) < 0) {
  810. log_fn(LOG_ERR,"Reading config failed--see warnings above. For usage, try -h.");
  811. return -1;
  812. }
  813. options = get_options(); /* they have changed now */
  814. if (authdir_mode(options)) {
  815. /* reload the approved-routers file */
  816. tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", options->DataDirectory);
  817. log_fn(LOG_INFO,"Reloading approved fingerprints from \"%s\"...",keydir);
  818. if (dirserv_parse_fingerprint_file(keydir) < 0) {
  819. log_fn(LOG_NOTICE, "Error reloading fingerprints. Continuing with old list.");
  820. }
  821. }
  822. /* Rotate away from the old dirty circuits. This has to be done
  823. * after we've read the new options, but before we start using
  824. * circuits for directory fetches. */
  825. circuit_expire_all_dirty_circs();
  826. /* retry appropriate downloads */
  827. router_reset_status_download_failures();
  828. router_reset_descriptor_download_failures();
  829. update_networkstatus_downloads(time(NULL));
  830. /* We'll retry routerstatus downloads in about 10 seconds; no need to
  831. * force a retry there. */
  832. if (server_mode(options)) {
  833. const char *descriptor;
  834. /* Restart cpuworker and dnsworker processes, so they get up-to-date
  835. * configuration options. */
  836. cpuworkers_rotate();
  837. dnsworkers_rotate();
  838. /* Write out a fresh descriptor, but leave old one on failure. */
  839. router_rebuild_descriptor(1);
  840. descriptor = router_get_my_descriptor();
  841. if (!descriptor) {
  842. log_fn(LOG_WARN,"No descriptor to save.");
  843. return 0;
  844. }
  845. tor_snprintf(keydir,sizeof(keydir),"%s/router.desc",
  846. options->DataDirectory);
  847. log_fn(LOG_INFO,"Saving descriptor to \"%s\"...",keydir);
  848. if (write_str_to_file(keydir, descriptor, 0)) {
  849. return 0;
  850. }
  851. }
  852. return 0;
  853. }
  854. /** Tor main loop. */
  855. static int
  856. do_main_loop(void)
  857. {
  858. int loop_result;
  859. dns_init(); /* initialize dns resolve tree, spawn workers if needed */
  860. handle_signals(1);
  861. /* load the private keys, if we're supposed to have them, and set up the
  862. * TLS context. */
  863. if (! identity_key_is_set()) {
  864. if (init_keys() < 0) {
  865. log_fn(LOG_ERR,"Error initializing keys; exiting");
  866. return -1;
  867. }
  868. }
  869. /* Set up our buckets */
  870. connection_bucket_init();
  871. stats_prev_global_read_bucket = global_read_bucket;
  872. stats_prev_global_write_bucket = global_write_bucket;
  873. /* load the routers file, or assign the defaults. */
  874. if (router_reload_router_list()) {
  875. return -1;
  876. }
  877. /* load the networkstatuses. (This launches a download for new routers as
  878. * appropriate.)
  879. */
  880. if (router_reload_networkstatus()) {
  881. return -1;
  882. }
  883. directory_info_has_arrived(time(NULL),1);
  884. if (authdir_mode(get_options())) {
  885. /* the directory is already here, run startup things */
  886. router_retry_connections(1);
  887. }
  888. if (server_mode(get_options())) {
  889. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  890. cpu_init();
  891. }
  892. /* set up once-a-second callback. */
  893. second_elapsed_callback(0,0,NULL);
  894. for (;;) {
  895. if (nt_service_is_stopped())
  896. return 0;
  897. #ifndef MS_WINDOWS
  898. /* Make it easier to tell whether libevent failure is our fault or not. */
  899. errno = 0;
  900. #endif
  901. /* poll until we have an event, or the second ends */
  902. loop_result = event_dispatch();
  903. /* let catch() handle things like ^c, and otherwise don't worry about it */
  904. if (loop_result < 0) {
  905. int e = tor_socket_errno(-1);
  906. /* let the program survive things like ^z */
  907. if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
  908. #ifdef HAVE_EVENT_GET_METHOD
  909. log_fn(LOG_ERR,"libevent poll with %s failed: %s [%d]",
  910. event_get_method(), tor_socket_strerror(e), e);
  911. #else
  912. log_fn(LOG_ERR,"libevent poll failed: %s [%d]",
  913. tor_socket_strerror(e), e);
  914. #endif
  915. return -1;
  916. #ifndef MS_WINDOWS
  917. } else if (e == EINVAL) {
  918. log_fn(LOG_WARN, "EINVAL from libevent: should you upgrade libevent?");
  919. if (got_libevent_error())
  920. return -1;
  921. #endif
  922. } else {
  923. if (ERRNO_IS_EINPROGRESS(e))
  924. log_fn(LOG_WARN,"libevent poll returned EINPROGRESS? Please report.");
  925. log_fn(LOG_DEBUG,"event poll interrupted.");
  926. /* You can't trust the results of this poll(). Go back to the
  927. * top of the big for loop. */
  928. continue;
  929. }
  930. }
  931. /* refilling buckets and sending cells happens at the beginning of the
  932. * next iteration of the loop, inside prepare_for_poll()
  933. * XXXX No longer so.
  934. */
  935. }
  936. }
  937. /** Used to implement the SIGNAL control command: if we accept
  938. * <b>the_signal</b> as a remote pseudo-signal, then act on it and
  939. * return 0. Else return -1. */
  940. /* We don't re-use catch() here because:
  941. * 1. We handle a different set of signals than those allowed in catch.
  942. * 2. Platforms without signal() are unlikely to define SIGfoo.
  943. * 3. The control spec is defined to use fixed numeric signal values
  944. * which just happen to match the unix values.
  945. */
  946. int
  947. control_signal_act(int the_signal)
  948. {
  949. switch (the_signal)
  950. {
  951. case 1:
  952. signal_callback(0,0,(void*)(uintptr_t)SIGHUP);
  953. break;
  954. case 2:
  955. signal_callback(0,0,(void*)(uintptr_t)SIGINT);
  956. break;
  957. case 10:
  958. signal_callback(0,0,(void*)(uintptr_t)SIGUSR1);
  959. break;
  960. case 12:
  961. signal_callback(0,0,(void*)(uintptr_t)SIGUSR2);
  962. break;
  963. case 15:
  964. signal_callback(0,0,(void*)(uintptr_t)SIGTERM);
  965. break;
  966. default:
  967. return -1;
  968. }
  969. return 0;
  970. }
  971. /** Libevent callback: invoked when we get a signal.
  972. */
  973. static void
  974. signal_callback(int fd, short events, void *arg)
  975. {
  976. uintptr_t sig = (uintptr_t)arg;
  977. switch (sig)
  978. {
  979. case SIGTERM:
  980. log(LOG_ERR,"Catching signal TERM, exiting cleanly.");
  981. tor_cleanup();
  982. exit(0);
  983. break;
  984. case SIGINT:
  985. if (!server_mode(get_options())) { /* do it now */
  986. log(LOG_NOTICE,"Interrupt: exiting cleanly.");
  987. tor_cleanup();
  988. exit(0);
  989. }
  990. hibernate_begin_shutdown();
  991. break;
  992. #ifdef SIGPIPE
  993. case SIGPIPE:
  994. log(LOG_DEBUG,"Caught sigpipe. Ignoring.");
  995. break;
  996. #endif
  997. case SIGUSR1:
  998. /* prefer to log it at INFO, but make sure we always see it */
  999. dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
  1000. break;
  1001. case SIGUSR2:
  1002. switch_logs_debug();
  1003. log(LOG_NOTICE,"Caught USR2, going to loglevel debug. Send HUP to change back.");
  1004. break;
  1005. case SIGHUP:
  1006. if (do_hup() < 0) {
  1007. log_fn(LOG_WARN,"Restart failed (config error?). Exiting.");
  1008. tor_cleanup();
  1009. exit(1);
  1010. }
  1011. break;
  1012. #ifdef SIGCHLD
  1013. case SIGCHLD:
  1014. while (waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more zombies */
  1015. break;
  1016. #endif
  1017. }
  1018. }
  1019. /**
  1020. * Write current memory uusage information to the log.
  1021. */
  1022. static void
  1023. dumpmemusage(int severity)
  1024. {
  1025. extern uint64_t buf_total_used;
  1026. extern uint64_t buf_total_alloc;
  1027. extern uint64_t rephist_total_alloc;
  1028. extern uint32_t rephist_total_num;
  1029. log(severity, "In buffers: "U64_FORMAT" used/"U64_FORMAT" allocated (%d conns).",
  1030. U64_PRINTF_ARG(buf_total_used), U64_PRINTF_ARG(buf_total_alloc),
  1031. nfds);
  1032. log(severity, "In rephist: "U64_FORMAT" used by %d Tors.",
  1033. U64_PRINTF_ARG(rephist_total_alloc), rephist_total_num);
  1034. }
  1035. /** Write all statistics to the log, with log level 'severity'. Called
  1036. * in response to a SIGUSR1. */
  1037. static void
  1038. dumpstats(int severity)
  1039. {
  1040. int i;
  1041. connection_t *conn;
  1042. time_t now = time(NULL);
  1043. time_t elapsed;
  1044. log(severity, "Dumping stats:");
  1045. for (i=0;i<nfds;i++) {
  1046. conn = connection_array[i];
  1047. log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  1048. i, conn->s, conn->type, conn_type_to_string(conn->type),
  1049. conn->state, conn_state_to_string(conn->type, conn->state), (int)(now - conn->timestamp_created));
  1050. if (!connection_is_listener(conn)) {
  1051. log(severity,"Conn %d is to '%s:%d'.",i,safe_str(conn->address), conn->port);
  1052. log(severity,"Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",i,
  1053. (int)buf_datalen(conn->inbuf),
  1054. (int)buf_capacity(conn->inbuf),
  1055. (int)(now - conn->timestamp_lastread));
  1056. log(severity,"Conn %d: %d bytes waiting on outbuf (len %d, last written %d secs ago)",i,
  1057. (int)buf_datalen(conn->outbuf),
  1058. (int)buf_capacity(conn->outbuf),
  1059. (int)(now - conn->timestamp_lastwritten));
  1060. }
  1061. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
  1062. }
  1063. log(severity,
  1064. "Cells processed: %10lu padding\n"
  1065. " %10lu create\n"
  1066. " %10lu created\n"
  1067. " %10lu relay\n"
  1068. " (%10lu relayed)\n"
  1069. " (%10lu delivered)\n"
  1070. " %10lu destroy",
  1071. stats_n_padding_cells_processed,
  1072. stats_n_create_cells_processed,
  1073. stats_n_created_cells_processed,
  1074. stats_n_relay_cells_processed,
  1075. stats_n_relay_cells_relayed,
  1076. stats_n_relay_cells_delivered,
  1077. stats_n_destroy_cells_processed);
  1078. if (stats_n_data_cells_packaged)
  1079. log(severity,"Average packaged cell fullness: %2.3f%%",
  1080. 100*(((double)stats_n_data_bytes_packaged) /
  1081. (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  1082. if (stats_n_data_cells_received)
  1083. log(severity,"Average delivered cell fullness: %2.3f%%",
  1084. 100*(((double)stats_n_data_bytes_received) /
  1085. (stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  1086. if (now - time_of_process_start >= 0)
  1087. elapsed = now - time_of_process_start;
  1088. else
  1089. elapsed = 0;
  1090. if (elapsed) {
  1091. log(severity,
  1092. "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
  1093. U64_PRINTF_ARG(stats_n_bytes_read),
  1094. (int)elapsed,
  1095. (int) (stats_n_bytes_read/elapsed));
  1096. log(severity,
  1097. "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
  1098. U64_PRINTF_ARG(stats_n_bytes_written),
  1099. (int)elapsed,
  1100. (int) (stats_n_bytes_written/elapsed));
  1101. }
  1102. log(severity, "--------------- Dumping memory information:");
  1103. dumpmemusage(severity);
  1104. rep_hist_dump_stats(now,severity);
  1105. rend_service_dump_stats(severity);
  1106. }
  1107. /** Called by exit() as we shut down the process.
  1108. */
  1109. static void
  1110. exit_function(void)
  1111. {
  1112. /* NOTE: If we ever daemonize, this gets called immediately. That's
  1113. * okay for now, because we only use this on Windows. */
  1114. #ifdef MS_WINDOWS
  1115. WSACleanup();
  1116. #endif
  1117. }
  1118. /** Set up the signal handlers for either parent or child. */
  1119. void
  1120. handle_signals(int is_parent)
  1121. {
  1122. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  1123. int i;
  1124. static int signals[] = {
  1125. SIGINT, /* do a controlled slow shutdown */
  1126. SIGTERM, /* to terminate now */
  1127. SIGPIPE, /* otherwise sigpipe kills us */
  1128. SIGUSR1, /* dump stats */
  1129. SIGUSR2, /* go to loglevel debug */
  1130. SIGHUP, /* to reload config, retry conns, etc */
  1131. #ifdef SIGXFSZ
  1132. SIGXFSZ, /* handle file-too-big resource exhaustion */
  1133. #endif
  1134. SIGCHLD, /* handle dns/cpu workers that exit */
  1135. -1 };
  1136. static struct event signal_events[16]; /* bigger than it has to be. */
  1137. if (is_parent) {
  1138. for (i = 0; signals[i] >= 0; ++i) {
  1139. signal_set(&signal_events[i], signals[i], signal_callback,
  1140. (void*)(uintptr_t)signals[i]);
  1141. if (signal_add(&signal_events[i], NULL))
  1142. log_fn(LOG_WARN, "Error from libevent when adding event for signal %d",
  1143. signals[i]);
  1144. }
  1145. } else {
  1146. struct sigaction action;
  1147. action.sa_flags = 0;
  1148. sigemptyset(&action.sa_mask);
  1149. action.sa_handler = SIG_IGN;
  1150. sigaction(SIGINT, &action, NULL);
  1151. sigaction(SIGTERM, &action, NULL);
  1152. sigaction(SIGPIPE, &action, NULL);
  1153. sigaction(SIGUSR1, &action, NULL);
  1154. sigaction(SIGUSR2, &action, NULL);
  1155. sigaction(SIGHUP, &action, NULL);
  1156. #ifdef SIGXFSZ
  1157. sigaction(SIGXFSZ, &action, NULL);
  1158. #endif
  1159. }
  1160. #endif /* signal stuff */
  1161. }
  1162. /** Main entry point for the Tor command-line client.
  1163. */
  1164. static int
  1165. tor_init(int argc, char *argv[])
  1166. {
  1167. time_of_process_start = time(NULL);
  1168. if (!closeable_connection_lst)
  1169. closeable_connection_lst = smartlist_create();
  1170. /* Initialize the history structures. */
  1171. rep_hist_init();
  1172. /* Initialize the service cache. */
  1173. rend_cache_init();
  1174. addressmap_init(); /* Init the client dns cache. Do it always, since it's cheap. */
  1175. /* give it somewhere to log to initially */
  1176. add_temp_log();
  1177. log(LOG_NOTICE,"Tor v%s. This is experimental software. Do not rely on it for strong anonymity.",VERSION);
  1178. if (network_init()<0) {
  1179. log_fn(LOG_ERR,"Error initializing network; exiting.");
  1180. return -1;
  1181. }
  1182. atexit(exit_function);
  1183. if (options_init_from_torrc(argc,argv) < 0) {
  1184. log_fn(LOG_ERR,"Reading config failed--see warnings above. For usage, try -h.");
  1185. return -1;
  1186. }
  1187. #ifndef MS_WINDOWS
  1188. if (geteuid()==0)
  1189. log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
  1190. #endif
  1191. crypto_global_init(get_options()->HardwareAccel);
  1192. if (crypto_seed_rng()) {
  1193. log_fn(LOG_ERR, "Unable to seed random number generator. Exiting.");
  1194. return -1;
  1195. }
  1196. return 0;
  1197. }
  1198. /** Free all memory that we might have allocated somewhere.
  1199. * Helps us find the real leaks with dmalloc and the like.
  1200. *
  1201. * Also valgrind should then report 0 reachable in its
  1202. * leak report */
  1203. void
  1204. tor_free_all(int postfork)
  1205. {
  1206. routerlist_free_all();
  1207. addressmap_free_all();
  1208. set_exit_redirects(NULL); /* free the registered exit redirects */
  1209. free_socks_policy();
  1210. free_dir_policy();
  1211. dirserv_free_all();
  1212. rend_service_free_all();
  1213. rend_cache_free_all();
  1214. rep_hist_free_all();
  1215. dns_free_all();
  1216. clear_pending_onions();
  1217. circuit_free_all();
  1218. helper_nodes_free_all();
  1219. connection_free_all();
  1220. if (!postfork) {
  1221. config_free_all();
  1222. router_free_all();
  1223. }
  1224. tor_tls_free_all();
  1225. /* stuff in main.c */
  1226. smartlist_free(closeable_connection_lst);
  1227. tor_free(timeout_event);
  1228. if (!postfork) {
  1229. close_logs(); /* free log strings. do this last so logs keep working. */
  1230. }
  1231. }
  1232. /** Do whatever cleanup is necessary before shutting Tor down. */
  1233. void
  1234. tor_cleanup(void)
  1235. {
  1236. or_options_t *options = get_options();
  1237. /* Remove our pid file. We don't care if there was an error when we
  1238. * unlink, nothing we could do about it anyways. */
  1239. if (options->PidFile && options->command == CMD_RUN_TOR)
  1240. unlink(options->PidFile);
  1241. if (accounting_is_enabled(options))
  1242. accounting_record_bandwidth_usage(time(NULL));
  1243. tor_free_all(0); /* move tor_free_all back into the ifdef below later. XXX*/
  1244. crypto_global_cleanup();
  1245. #ifdef USE_DMALLOC
  1246. dmalloc_log_unfreed();
  1247. dmalloc_shutdown();
  1248. #endif
  1249. }
  1250. /** Read/create keys as needed, and echo our fingerprint to stdout. */
  1251. static void
  1252. do_list_fingerprint(void)
  1253. {
  1254. char buf[FINGERPRINT_LEN+1];
  1255. crypto_pk_env_t *k;
  1256. const char *nickname = get_options()->Nickname;
  1257. if (!server_mode(get_options())) {
  1258. printf("Clients don't have long-term identity keys. Exiting.\n");
  1259. return;
  1260. }
  1261. tor_assert(nickname);
  1262. if (init_keys() < 0) {
  1263. log_fn(LOG_ERR,"Error initializing keys; exiting");
  1264. return;
  1265. }
  1266. if (!(k = get_identity_key())) {
  1267. log_fn(LOG_ERR,"Error: missing identity key.");
  1268. return;
  1269. }
  1270. if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
  1271. log_fn(LOG_ERR, "Error computing fingerprint");
  1272. return;
  1273. }
  1274. printf("%s %s\n", nickname, buf);
  1275. }
  1276. /** Entry point for password hashing: take the desired password from
  1277. * the command line, and print its salted hash to stdout. **/
  1278. static void
  1279. do_hash_password(void)
  1280. {
  1281. char output[256];
  1282. char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
  1283. crypto_rand(key, S2K_SPECIFIER_LEN-1);
  1284. key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
  1285. secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
  1286. get_options()->command_arg, strlen(get_options()->command_arg),
  1287. key);
  1288. base16_encode(output, sizeof(output), key, sizeof(key));
  1289. printf("16:%s\n",output);
  1290. }
  1291. #ifdef MS_WINDOWS_SERVICE
  1292. /** Checks if torrc is present in the same directory
  1293. * as the service executable.
  1294. * Return 1 if it is, 0 if it is not present. */
  1295. static int
  1296. nt_torrc_is_present()
  1297. {
  1298. HANDLE hFile;
  1299. TCHAR szPath[_MAX_PATH];
  1300. TCHAR szDrive[_MAX_DRIVE];
  1301. TCHAR szDir[_MAX_DIR];
  1302. char torrc[] = "torrc";
  1303. char *path_to_torrc;
  1304. int len = 0;
  1305. /* Get the service executable path */
  1306. if (0 == GetModuleFileName(NULL, szPath, MAX_PATH))
  1307. return 0;
  1308. _tsplitpath(szPath, szDrive, szDir, NULL, NULL);
  1309. /* Build the path to the torrc file */
  1310. len = _MAX_PATH + _MAX_DRIVE + _MAX_DIR + strlen(torrc) + 1;
  1311. path_to_torrc = tor_malloc(len);
  1312. if (tor_snprintf(path_to_torrc, len, "%s%s%s", szDrive, szDir, torrc)<0) {
  1313. printf("Failed: tor_snprinf()\n");
  1314. tor_free(path_to_torrc);
  1315. return 0;
  1316. }
  1317. /* See if torrc is present */
  1318. hFile = CreateFile(TEXT(path_to_torrc),
  1319. GENERIC_READ, FILE_SHARE_READ, NULL,
  1320. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
  1321. NULL);
  1322. tor_free(path_to_torrc);
  1323. if (hFile == INVALID_HANDLE_VALUE) {
  1324. return 0;
  1325. }
  1326. CloseHandle(hFile);
  1327. return 1;
  1328. }
  1329. /** If we're compile to run as an NT service, and the service has been
  1330. * shut down, then change our current status and return 1. Else
  1331. * return 0.
  1332. */
  1333. static int
  1334. nt_service_is_stopped(void)
  1335. {
  1336. if (service_status.dwCurrentState == SERVICE_STOP_PENDING) {
  1337. service_status.dwWin32ExitCode = 0;
  1338. service_status.dwCurrentState = SERVICE_STOPPED;
  1339. SetServiceStatus(hStatus, &service_status);
  1340. return 1;
  1341. } else if (service_status.dwCurrentState == SERVICE_STOPPED) {
  1342. return 1;
  1343. }
  1344. return 0;
  1345. }
  1346. /** DOCDOC */
  1347. void
  1348. nt_service_control(DWORD request)
  1349. {
  1350. static struct timeval exit_now;
  1351. exit_now.tv_sec = 0;
  1352. exit_now.tv_usec = 0;
  1353. switch (request) {
  1354. case SERVICE_CONTROL_STOP:
  1355. case SERVICE_CONTROL_SHUTDOWN:
  1356. log(LOG_ERR, "Got stop/shutdown request; shutting down cleanly.");
  1357. service_status.dwCurrentState = SERVICE_STOP_PENDING;
  1358. event_loopexit(&exit_now);
  1359. return;
  1360. }
  1361. SetServiceStatus(hStatus, &service_status);
  1362. }
  1363. /** DOCDOC */
  1364. void
  1365. nt_service_body(int argc, char **argv)
  1366. {
  1367. int err;
  1368. service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  1369. service_status.dwCurrentState = SERVICE_START_PENDING;
  1370. service_status.dwControlsAccepted =
  1371. SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  1372. service_status.dwWin32ExitCode = 0;
  1373. service_status.dwServiceSpecificExitCode = 0;
  1374. service_status.dwCheckPoint = 0;
  1375. service_status.dwWaitHint = 1000;
  1376. hStatus = RegisterServiceCtrlHandler(GENSRV_SERVICENAME, (LPHANDLER_FUNCTION) nt_service_control);
  1377. if (hStatus == 0) {
  1378. // failed;
  1379. return;
  1380. }
  1381. // check for torrc
  1382. if (nt_torrc_is_present()) {
  1383. err = tor_init(backup_argc, backup_argv); // refactor this part out of tor_main and do_main_loop
  1384. if (err) {
  1385. err = NT_SERVICE_ERROR_TORINIT_FAILED;
  1386. }
  1387. }
  1388. else {
  1389. log_fn(LOG_ERR, "torrc is not in the current working directory. The Tor service will not start.");
  1390. err = NT_SERVICE_ERROR_NO_TORRC;
  1391. }
  1392. if (err) {
  1393. // failed.
  1394. service_status.dwCurrentState = SERVICE_STOPPED;
  1395. service_status.dwWin32ExitCode = err;
  1396. service_status.dwServiceSpecificExitCode = err;
  1397. SetServiceStatus(hStatus, &service_status);
  1398. return;
  1399. }
  1400. service_status.dwCurrentState = SERVICE_RUNNING;
  1401. SetServiceStatus(hStatus, &service_status);
  1402. do_main_loop();
  1403. tor_cleanup();
  1404. return;
  1405. }
  1406. /** DOCDOC */
  1407. void
  1408. nt_service_main(void)
  1409. {
  1410. SERVICE_TABLE_ENTRY table[2];
  1411. DWORD result = 0;
  1412. char *errmsg;
  1413. table[0].lpServiceName = GENSRV_SERVICENAME;
  1414. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
  1415. table[1].lpServiceName = NULL;
  1416. table[1].lpServiceProc = NULL;
  1417. if (!StartServiceCtrlDispatcher(table)) {
  1418. result = GetLastError();
  1419. errmsg = nt_strerror(result);
  1420. printf("Service error %d : %s\n", result, errmsg);
  1421. LocalFree(errmsg);
  1422. if (result == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
  1423. if (tor_init(backup_argc, backup_argv) < 0)
  1424. return;
  1425. switch (get_options()->command) {
  1426. case CMD_RUN_TOR:
  1427. do_main_loop();
  1428. break;
  1429. case CMD_LIST_FINGERPRINT:
  1430. do_list_fingerprint();
  1431. break;
  1432. case CMD_HASH_PASSWORD:
  1433. do_hash_password();
  1434. break;
  1435. case CMD_VERIFY_CONFIG:
  1436. printf("Configuration was valid\n");
  1437. break;
  1438. default:
  1439. log_fn(LOG_ERR, "Illegal command number %d: internal error.", get_options()->command);
  1440. }
  1441. tor_cleanup();
  1442. }
  1443. }
  1444. }
  1445. /** DOCDOC */
  1446. SC_HANDLE
  1447. nt_service_open_scm(void)
  1448. {
  1449. SC_HANDLE hSCManager;
  1450. char *errmsg = NULL;
  1451. if ((hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
  1452. errmsg = nt_strerror(GetLastError());
  1453. printf("OpenSCManager() failed : %s\n", errmsg);
  1454. LocalFree(errmsg);
  1455. }
  1456. return hSCManager;
  1457. }
  1458. /** DOCDOC */
  1459. SC_HANDLE
  1460. nt_service_open(SC_HANDLE hSCManager)
  1461. {
  1462. SC_HANDLE hService;
  1463. char *errmsg = NULL;
  1464. if ((hService = OpenService(hSCManager, GENSRV_SERVICENAME, SERVICE_ALL_ACCESS)) == NULL) {
  1465. errmsg = nt_strerror(GetLastError());
  1466. printf("OpenService() failed : %s\n", errmsg);
  1467. LocalFree(errmsg);
  1468. }
  1469. return hService;
  1470. }
  1471. /** DOCDOC */
  1472. int
  1473. nt_service_start(SC_HANDLE hService)
  1474. {
  1475. char *errmsg = NULL;
  1476. QueryServiceStatus(hService, &service_status);
  1477. if (service_status.dwCurrentState == SERVICE_RUNNING) {
  1478. printf("Service is already running\n");
  1479. return 1;
  1480. }
  1481. if (StartService(hService, 0, NULL)) {
  1482. /* Loop until the service has finished attempting to start */
  1483. while (QueryServiceStatus(hService, &service_status)) {
  1484. if (service_status.dwCurrentState == SERVICE_START_PENDING)
  1485. Sleep(500);
  1486. else
  1487. break;
  1488. }
  1489. /* Check if it started successfully or not */
  1490. if (service_status.dwCurrentState == SERVICE_RUNNING) {
  1491. printf("Service started successfully\n");
  1492. return 1;
  1493. }
  1494. else {
  1495. errmsg = nt_strerror(service_status.dwWin32ExitCode);
  1496. printf("Service failed to start : %s\n", errmsg);
  1497. LocalFree(errmsg);
  1498. }
  1499. }
  1500. else {
  1501. errmsg = nt_strerror(GetLastError());
  1502. printf("StartService() failed : %s\n", errmsg);
  1503. LocalFree(errmsg);
  1504. }
  1505. return 0;
  1506. }
  1507. /** DOCDOC */
  1508. int
  1509. nt_service_stop(SC_HANDLE hService)
  1510. {
  1511. char *errmsg = NULL;
  1512. QueryServiceStatus(hService, &service_status);
  1513. if (service_status.dwCurrentState == SERVICE_STOPPED) {
  1514. printf("Service is already stopped\n");
  1515. return 1;
  1516. }
  1517. if (ControlService(hService, SERVICE_CONTROL_STOP, &service_status)) {
  1518. while (QueryServiceStatus(hService, &service_status)) {
  1519. if (service_status.dwCurrentState == SERVICE_STOP_PENDING)
  1520. Sleep(500);
  1521. else
  1522. break;
  1523. }
  1524. if (service_status.dwCurrentState == SERVICE_STOPPED) {
  1525. printf("Service stopped successfully\n");
  1526. return 1;
  1527. }
  1528. else {
  1529. errmsg = nt_strerror(GetLastError());
  1530. printf("Service failed to stop : %s\n");
  1531. LocalFree(errmsg);
  1532. }
  1533. }
  1534. else {
  1535. errmsg = nt_strerror(GetLastError());
  1536. printf("ControlService() failed : %s\n", errmsg);
  1537. LocalFree(errmsg);
  1538. }
  1539. return 0;
  1540. }
  1541. /** DOCDOC */
  1542. int
  1543. nt_service_install(void)
  1544. {
  1545. /* XXXX Problems with NT services:
  1546. * 1. The configuration file needs to be in the same directory as the .exe
  1547. *
  1548. * 2. The exe and the configuration file can't be on any directory path
  1549. * that contains a space.
  1550. * mje - you can quote the string (i.e., "c:\program files")
  1551. *
  1552. * 3. Ideally, there should be one EXE that can either run as a
  1553. * separate process (as now) or that can install and run itself
  1554. * as an NT service. I have no idea how hard this is.
  1555. * mje - should be done. It can install and run itself as a service
  1556. *
  1557. * Notes about developing NT services:
  1558. *
  1559. * 1. Don't count on your CWD. If an absolute path is not given, the
  1560. * fopen() function goes wrong.
  1561. * 2. The parameters given to the nt_service_body() function differ
  1562. * from those given to main() function.
  1563. */
  1564. SC_HANDLE hSCManager = NULL;
  1565. SC_HANDLE hService = NULL;
  1566. SERVICE_DESCRIPTION sdBuff;
  1567. TCHAR szPath[_MAX_PATH];
  1568. TCHAR szDrive[_MAX_DRIVE];
  1569. TCHAR szDir[_MAX_DIR];
  1570. char cmd1[] = " -f ";
  1571. char cmd2[] = "\\torrc";
  1572. char *command;
  1573. char *errmsg;
  1574. int len = 0;
  1575. if (0 == GetModuleFileName(NULL, szPath, MAX_PATH))
  1576. return 0;
  1577. _tsplitpath(szPath, szDrive, szDir, NULL, NULL);
  1578. /* Account for the extra quotes */
  1579. //len = _MAX_PATH + strlen(cmd1) + _MAX_DRIVE + _MAX_DIR + strlen(cmd2);
  1580. len = _MAX_PATH + strlen(cmd1) + _MAX_DRIVE + _MAX_DIR + strlen(cmd2) + 64;
  1581. command = tor_malloc(len);
  1582. /* Create a quoted command line, like "c:\with spaces\tor.exe" -f
  1583. * "c:\with spaces\tor.exe"
  1584. */
  1585. if (tor_snprintf(command, len, "\"%s\" --nt-service -f \"%s%storrc\"",
  1586. szPath, szDrive, szDir)<0) {
  1587. printf("Failed: tor_snprinf()\n");
  1588. tor_free(command);
  1589. return 0;
  1590. }
  1591. if ((hSCManager = nt_service_open_scm()) == NULL) {
  1592. tor_free(command);
  1593. return 0;
  1594. }
  1595. /* 1/26/2005 mje
  1596. * - changed the service start type to auto
  1597. * - and changed the lpPassword param to "" instead of NULL as per an
  1598. * MSDN article.
  1599. */
  1600. if ((hService = CreateService(hSCManager, GENSRV_SERVICENAME, GENSRV_DISPLAYNAME,
  1601. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  1602. SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, command,
  1603. NULL, NULL, NULL, NULL, "")) == NULL) {
  1604. errmsg = nt_strerror(GetLastError());
  1605. printf("CreateService() failed : %s\n", errmsg);
  1606. CloseServiceHandle(hSCManager);
  1607. LocalFree(errmsg);
  1608. tor_free(command);
  1609. return 0;
  1610. }
  1611. /* Set the service's description */
  1612. sdBuff.lpDescription = GENSRV_DESCRIPTION;
  1613. ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &sdBuff);
  1614. printf("Service installed successfully\n");
  1615. /* Start the service initially */
  1616. nt_service_start(hService);
  1617. CloseServiceHandle(hService);
  1618. CloseServiceHandle(hSCManager);
  1619. tor_free(command);
  1620. return 0;
  1621. }
  1622. /** DOCDOC */
  1623. int
  1624. nt_service_remove(void)
  1625. {
  1626. SC_HANDLE hSCManager = NULL;
  1627. SC_HANDLE hService = NULL;
  1628. BOOL result = FALSE;
  1629. char *errmsg;
  1630. if ((hSCManager = nt_service_open_scm()) == NULL) {
  1631. return 0;
  1632. }
  1633. if ((hService = nt_service_open(hSCManager)) == NULL) {
  1634. CloseServiceHandle(hSCManager);
  1635. return 0;
  1636. }
  1637. if (nt_service_stop(hService)) {
  1638. if (DeleteService(hService)) {
  1639. printf("Removed service successfully\n");
  1640. }
  1641. else {
  1642. errmsg = nt_strerror(GetLastError());
  1643. printf("DeleteService() failed : %s\n", errmsg);
  1644. LocalFree(errmsg);
  1645. }
  1646. }
  1647. else {
  1648. printf("Service could not be removed\n");
  1649. }
  1650. CloseServiceHandle(hService);
  1651. CloseServiceHandle(hSCManager);
  1652. return 0;
  1653. }
  1654. /** DOCDOC */
  1655. int
  1656. nt_service_cmd_start(void)
  1657. {
  1658. SC_HANDLE hSCManager;
  1659. SC_HANDLE hService;
  1660. int start;
  1661. if ((hSCManager = nt_service_open_scm()) == NULL)
  1662. return -1;
  1663. if ((hService = nt_service_open(hSCManager)) == NULL) {
  1664. CloseHandle(hSCManager);
  1665. return -1;
  1666. }
  1667. start = nt_service_start(hService);
  1668. CloseHandle(hService);
  1669. CloseHandle(hSCManager);
  1670. return start;
  1671. }
  1672. /** DOCDOC */
  1673. int
  1674. nt_service_cmd_stop(void)
  1675. {
  1676. SC_HANDLE hSCManager;
  1677. SC_HANDLE hService;
  1678. int stop;
  1679. if ((hSCManager = nt_service_open_scm()) == NULL)
  1680. return -1;
  1681. if ((hService = nt_service_open(hSCManager)) == NULL) {
  1682. CloseHandle(hSCManager);
  1683. return -1;
  1684. }
  1685. stop = nt_service_stop(hService);
  1686. CloseHandle(hService);
  1687. CloseHandle(hSCManager);
  1688. return stop;
  1689. }
  1690. /** Given a Win32 error code, this attempts to make Windows
  1691. * return a human-readable error message. The char* returned
  1692. * is allocated by Windows, but should be freed with LocalFree()
  1693. * when finished with it. */
  1694. static char*
  1695. nt_strerror(uint32_t errnum)
  1696. {
  1697. char *msgbuf;
  1698. FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  1699. NULL, errnum, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1700. (LPSTR)&msgbuf, 0, NULL);
  1701. return msgbuf;
  1702. }
  1703. #endif
  1704. #ifdef USE_DMALLOC
  1705. #include <openssl/crypto.h>
  1706. static void
  1707. _tor_dmalloc_free(void *p)
  1708. {
  1709. tor_free(p);
  1710. }
  1711. #endif
  1712. /** DOCDOC */
  1713. int
  1714. tor_main(int argc, char *argv[])
  1715. {
  1716. #ifdef USE_DMALLOC
  1717. int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc, _tor_dmalloc_free);
  1718. log_fn(LOG_NOTICE, "r = %d", r);
  1719. #endif
  1720. #ifdef MS_WINDOWS_SERVICE
  1721. backup_argv = argv;
  1722. backup_argc = argc;
  1723. if ((argc >= 3) && (!strcmp(argv[1], "-service") || !strcmp(argv[1], "--service"))) {
  1724. if (!strcmp(argv[2], "install"))
  1725. return nt_service_install();
  1726. if (!strcmp(argv[2], "remove"))
  1727. return nt_service_remove();
  1728. if (!strcmp(argv[2], "start"))
  1729. return nt_service_cmd_start();
  1730. if (!strcmp(argv[2], "stop"))
  1731. return nt_service_cmd_stop();
  1732. printf("Unrecognized service command '%s'\n", argv[2]);
  1733. return -1;
  1734. }
  1735. // These are left so as not to confuse people who are used to these options
  1736. if (argc >= 2) {
  1737. if (!strcmp(argv[1], "-install") || !strcmp(argv[1], "--install"))
  1738. return nt_service_install();
  1739. if (!strcmp(argv[1], "-remove") || !strcmp(argv[1], "--remove"))
  1740. return nt_service_remove();
  1741. if (!strcmp(argv[1], "-nt-service") || !strcmp(argv[1], "--nt-service")) {
  1742. nt_service_main();
  1743. return 0;
  1744. }
  1745. }
  1746. #endif
  1747. if (tor_init(argc, argv)<0)
  1748. return -1;
  1749. switch (get_options()->command) {
  1750. case CMD_RUN_TOR:
  1751. #ifdef MS_WINDOWS_SERVICE
  1752. service_status.dwCurrentState = SERVICE_RUNNING;
  1753. #endif
  1754. do_main_loop();
  1755. break;
  1756. case CMD_LIST_FINGERPRINT:
  1757. do_list_fingerprint();
  1758. break;
  1759. case CMD_HASH_PASSWORD:
  1760. do_hash_password();
  1761. break;
  1762. case CMD_VERIFY_CONFIG:
  1763. printf("Configuration was valid\n");
  1764. break;
  1765. default:
  1766. log_fn(LOG_ERR, "Illegal command number %d: internal error.",
  1767. get_options()->command);
  1768. }
  1769. tor_cleanup();
  1770. return -1;
  1771. }