main.c 59 KB

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