main.c 66 KB

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