main.c 64 KB

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