main.c 80 KB

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