main.c 87 KB

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