main.c 53 KB

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