main.c 74 KB

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