main.c 67 KB

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