main.c 51 KB

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