main.c 60 KB

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