main.c 53 KB

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