main.c 51 KB

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