main.c 59 KB

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