main.c 68 KB

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