main.c 54 KB

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