main.c 62 KB

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