main.c 74 KB

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