main.c 62 KB

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