main.c 60 KB

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