main.c 52 KB

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