main.c 75 KB

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