main.c 74 KB

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