main.c 62 KB

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