main.c 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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. /**
  7. * \file main.c
  8. * \brief Tor main loop and startup functions.
  9. **/
  10. #include "or.h"
  11. /********* PROTOTYPES **********/
  12. static void dumpstats(int severity); /* log stats */
  13. /********* START VARIABLES **********/
  14. int global_read_bucket; /**< Max number of bytes I can read this second. */
  15. int global_write_bucket; /**< Max number of bytes I can write this second. */
  16. /** What was the read bucket before the last call to prepare_for_pool?
  17. * (used to determine how many bytes we've read). */
  18. static int stats_prev_global_read_bucket;
  19. /** What was the write bucket before the last call to prepare_for_pool?
  20. * (used to determine how many bytes we've written). */
  21. static int stats_prev_global_write_bucket;
  22. /** How many bytes have we read/written since we started the process? */
  23. static uint64_t stats_n_bytes_read = 0;
  24. static uint64_t stats_n_bytes_written = 0;
  25. /** How many seconds have we been running? */
  26. long stats_n_seconds_uptime = 0;
  27. /** When do we next download a directory? */
  28. static time_t time_to_fetch_directory = 0;
  29. /** Array of all open connections; each element corresponds to the element of
  30. * poll_array in the same position. The first nfds elements are valid. */
  31. static connection_t *connection_array[MAXCONNECTIONS] =
  32. { NULL };
  33. /** Array of pollfd objects for calls to poll(). */
  34. static struct pollfd poll_array[MAXCONNECTIONS];
  35. static int nfds=0; /**< Number of connections currently active. */
  36. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  37. static int please_dumpstats=0; /**< Whether we should dump stats during the loop. */
  38. static int please_reset=0; /**< Whether we just got a sighup. */
  39. static int please_reap_children=0; /**< Whether we should waitpid for exited children. */
  40. static int please_sigpipe=0; /**< Whether we've caught a sigpipe lately. */
  41. static int please_shutdown=0; /**< Whether we should shut down Tor. */
  42. #endif /* signal stuff */
  43. /** We set this to 1 when we've fetched a dir, to know whether to complain
  44. * yet about unrecognized nicknames in entrynodes, exitnodes, etc.
  45. * Also, we don't try building circuits unless this is 1. */
  46. int has_fetched_directory=0;
  47. /** We set this to 1 when we've opened a circuit, so we can print a log
  48. * entry to inform the user that Tor is working. */
  49. int has_completed_circuit=0;
  50. #ifdef MS_WINDOWS_SERVICE
  51. SERVICE_STATUS service_status;
  52. SERVICE_STATUS_HANDLE hStatus;
  53. #endif
  54. /********* END VARIABLES ************/
  55. /****************************************************************************
  56. *
  57. * This section contains accessors and other methods on the connection_array
  58. * and poll_array variables (which are global within this file and unavailable
  59. * outside it).
  60. *
  61. ****************************************************************************/
  62. /** Add <b>conn</b> to the array of connections that we can poll on. The
  63. * connection's socket must be set; the connection starts out
  64. * non-reading and non-writing.
  65. */
  66. int connection_add(connection_t *conn) {
  67. tor_assert(conn);
  68. tor_assert(conn->s >= 0);
  69. if(nfds >= get_options()->MaxConn-1) {
  70. log_fn(LOG_WARN,"failing because nfds is too high.");
  71. return -1;
  72. }
  73. tor_assert(conn->poll_index == -1); /* can only connection_add once */
  74. conn->poll_index = nfds;
  75. connection_array[nfds] = conn;
  76. poll_array[nfds].fd = conn->s;
  77. /* zero these out here, because otherwise we'll inherit values from the previously freed one */
  78. poll_array[nfds].events = 0;
  79. poll_array[nfds].revents = 0;
  80. nfds++;
  81. log_fn(LOG_INFO,"new conn type %s, socket %d, nfds %d.",
  82. CONN_TYPE_TO_STRING(conn->type), conn->s, nfds);
  83. return 0;
  84. }
  85. /** Remove the connection from the global list, and remove the
  86. * corresponding poll entry. Calling this function will shift the last
  87. * connection (if any) into the position occupied by conn.
  88. */
  89. int connection_remove(connection_t *conn) {
  90. int current_index;
  91. tor_assert(conn);
  92. tor_assert(nfds>0);
  93. log_fn(LOG_INFO,"removing socket %d (type %s), nfds now %d",
  94. conn->s, CONN_TYPE_TO_STRING(conn->type), nfds-1);
  95. tor_assert(conn->poll_index >= 0);
  96. current_index = conn->poll_index;
  97. if(current_index == nfds-1) { /* this is the end */
  98. nfds--;
  99. return 0;
  100. }
  101. /* replace this one with the one at the end */
  102. nfds--;
  103. poll_array[current_index].fd = poll_array[nfds].fd;
  104. poll_array[current_index].events = poll_array[nfds].events;
  105. poll_array[current_index].revents = poll_array[nfds].revents;
  106. connection_array[current_index] = connection_array[nfds];
  107. connection_array[current_index]->poll_index = current_index;
  108. return 0;
  109. }
  110. /** Return true iff conn is in the current poll array. */
  111. int connection_in_array(connection_t *conn) {
  112. int i;
  113. for (i=0; i<nfds; ++i) {
  114. if (conn==connection_array[i])
  115. return 1;
  116. }
  117. return 0;
  118. }
  119. /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
  120. * to the length of the array. <b>*array</b> and <b>*n</b> must not
  121. * be modified.
  122. */
  123. void get_connection_array(connection_t ***array, int *n) {
  124. *array = connection_array;
  125. *n = nfds;
  126. }
  127. /** Set the event mask on <b>conn</b> to <b>events</b>. (The form of
  128. * the event mask is as for poll().)
  129. */
  130. void connection_watch_events(connection_t *conn, short events) {
  131. tor_assert(conn);
  132. tor_assert(conn->poll_index >= 0);
  133. tor_assert(conn->poll_index < nfds);
  134. poll_array[conn->poll_index].events = events;
  135. }
  136. /** Return true iff <b>conn</b> is listening for read events. */
  137. int connection_is_reading(connection_t *conn) {
  138. tor_assert(conn);
  139. tor_assert(conn->poll_index >= 0);
  140. return poll_array[conn->poll_index].events & POLLIN;
  141. }
  142. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  143. void connection_stop_reading(connection_t *conn) {
  144. tor_assert(conn);
  145. tor_assert(conn->poll_index >= 0);
  146. tor_assert(conn->poll_index < nfds);
  147. log(LOG_DEBUG,"connection_stop_reading() called.");
  148. poll_array[conn->poll_index].events &= ~POLLIN;
  149. }
  150. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  151. void connection_start_reading(connection_t *conn) {
  152. tor_assert(conn);
  153. tor_assert(conn->poll_index >= 0);
  154. tor_assert(conn->poll_index < nfds);
  155. poll_array[conn->poll_index].events |= POLLIN;
  156. }
  157. /** Return true iff <b>conn</b> is listening for write events. */
  158. int connection_is_writing(connection_t *conn) {
  159. return poll_array[conn->poll_index].events & POLLOUT;
  160. }
  161. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  162. void connection_stop_writing(connection_t *conn) {
  163. tor_assert(conn);
  164. tor_assert(conn->poll_index >= 0);
  165. tor_assert(conn->poll_index < nfds);
  166. poll_array[conn->poll_index].events &= ~POLLOUT;
  167. }
  168. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  169. void connection_start_writing(connection_t *conn) {
  170. tor_assert(conn);
  171. tor_assert(conn->poll_index >= 0);
  172. tor_assert(conn->poll_index < nfds);
  173. poll_array[conn->poll_index].events |= POLLOUT;
  174. }
  175. /** Called when the connection at connection_array[i] has a read event,
  176. * or it has pending tls data waiting to be read: checks for validity,
  177. * catches numerous errors, and dispatches to connection_handle_read.
  178. */
  179. static void conn_read(int i) {
  180. connection_t *conn = connection_array[i];
  181. if (conn->marked_for_close)
  182. return;
  183. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
  184. * discussion of POLLIN vs POLLHUP */
  185. if(!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
  186. if(!connection_is_reading(conn) ||
  187. !connection_has_pending_tls_data(conn))
  188. return; /* this conn should not read */
  189. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  190. assert_connection_ok(conn, time(NULL));
  191. assert_all_pending_dns_resolves_ok();
  192. if(
  193. /* XXX does POLLHUP also mean it's definitely broken? */
  194. #ifdef MS_WINDOWS
  195. (poll_array[i].revents & POLLERR) ||
  196. #endif
  197. connection_handle_read(conn) < 0) {
  198. if (!conn->marked_for_close) {
  199. /* this connection is broken. remove it */
  200. log_fn(LOG_WARN,"Unhandled error on read for %s connection (fd %d); removing",
  201. CONN_TYPE_TO_STRING(conn->type), conn->s);
  202. connection_mark_for_close(conn);
  203. }
  204. }
  205. assert_connection_ok(conn, time(NULL));
  206. assert_all_pending_dns_resolves_ok();
  207. }
  208. /** Called when the connection at connection_array[i] has a write event:
  209. * checks for validity, catches numerous errors, and dispatches to
  210. * connection_handle_write.
  211. */
  212. static void conn_write(int i) {
  213. connection_t *conn;
  214. if(!(poll_array[i].revents & POLLOUT))
  215. return; /* this conn doesn't want to write */
  216. conn = connection_array[i];
  217. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  218. if (conn->marked_for_close)
  219. return;
  220. assert_connection_ok(conn, time(NULL));
  221. assert_all_pending_dns_resolves_ok();
  222. if (connection_handle_write(conn) < 0) {
  223. if (!conn->marked_for_close) {
  224. /* this connection is broken. remove it. */
  225. log_fn(LOG_WARN,"Unhandled error on write for %s connection (fd %d); removing",
  226. CONN_TYPE_TO_STRING(conn->type), conn->s);
  227. conn->has_sent_end = 1; /* otherwise we cry wolf about duplicate close */
  228. /* XXX do we need a close-immediate here, so we don't try to flush? */
  229. connection_mark_for_close(conn);
  230. }
  231. }
  232. assert_connection_ok(conn, time(NULL));
  233. assert_all_pending_dns_resolves_ok();
  234. }
  235. /** If the connection at connection_array[i] is marked for close, then:
  236. * - If it has data that it wants to flush, try to flush it.
  237. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  238. * true, then leave the connection open and return.
  239. * - Otherwise, remove the connection from connection_array and from
  240. * all other lists, close it, and free it.
  241. * If we remove the connection, then call conn_closed_if_marked at the new
  242. * connection at position i.
  243. */
  244. static void conn_close_if_marked(int i) {
  245. connection_t *conn;
  246. int retval;
  247. conn = connection_array[i];
  248. assert_connection_ok(conn, time(NULL));
  249. assert_all_pending_dns_resolves_ok();
  250. if(!conn->marked_for_close)
  251. return; /* nothing to see here, move along */
  252. log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
  253. if(conn->s >= 0 && connection_wants_to_flush(conn)) {
  254. /* -1 means it's an incomplete edge connection, or that the socket
  255. * has already been closed as unflushable. */
  256. if(!conn->hold_open_until_flushed)
  257. log_fn(LOG_INFO,
  258. "Conn (addr %s, fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
  259. "(Marked at %s:%d)",
  260. conn->address, conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  261. (int)conn->outbuf_flushlen, conn->marked_for_close_file, conn->marked_for_close);
  262. if(connection_speaks_cells(conn)) {
  263. if(conn->state == OR_CONN_STATE_OPEN) {
  264. retval = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  265. } else
  266. retval = -1; /* never flush non-open broken tls connections */
  267. } else {
  268. retval = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  269. }
  270. if(retval >= 0 &&
  271. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  272. log_fn(LOG_INFO,"Holding conn (fd %d) open for more flushing.",conn->s);
  273. /* XXX should we reset timestamp_lastwritten here? */
  274. return;
  275. }
  276. if(connection_wants_to_flush(conn)) {
  277. log_fn(LOG_WARN,"Conn (addr %s, fd %d, type %s, state %d) still wants to flush. Losing %d bytes! (Marked at %s:%d)",
  278. conn->address, conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  279. (int)buf_datalen(conn->outbuf), conn->marked_for_close_file,
  280. conn->marked_for_close);
  281. }
  282. }
  283. /* if it's an edge conn, remove it from the list
  284. * of conn's on this circuit. If it's not on an edge,
  285. * flush and send destroys for all circuits on this conn
  286. */
  287. circuit_about_to_close_connection(conn);
  288. connection_about_to_close_connection(conn);
  289. connection_remove(conn);
  290. if(conn->type == CONN_TYPE_EXIT) {
  291. assert_connection_edge_not_dns_pending(conn);
  292. }
  293. connection_free(conn);
  294. if(i<nfds) { /* we just replaced the one at i with a new one.
  295. process it too. */
  296. conn_close_if_marked(i);
  297. }
  298. }
  299. /** This function is called whenever we successfully pull down a directory */
  300. void directory_has_arrived(time_t now) {
  301. or_options_t *options = get_options();
  302. log_fn(LOG_INFO, "A directory has arrived.");
  303. has_fetched_directory=1;
  304. /* Don't try to upload or download anything for DirFetchPostPeriod
  305. * seconds after the directory we had when we started.
  306. */
  307. if (!time_to_fetch_directory)
  308. time_to_fetch_directory = now + options->DirFetchPostPeriod;
  309. if (server_mode(options) &&
  310. !we_are_hibernating()) { /* connect to the appropriate routers */
  311. router_retry_connections();
  312. }
  313. }
  314. /** Perform regular maintenance tasks for a single connection. This
  315. * function gets run once per second per connection by run_housekeeping.
  316. */
  317. static void run_connection_housekeeping(int i, time_t now) {
  318. cell_t cell;
  319. connection_t *conn = connection_array[i];
  320. or_options_t *options = get_options();
  321. /* Expire any directory connections that haven't sent anything for 5 min */
  322. if(conn->type == CONN_TYPE_DIR &&
  323. !conn->marked_for_close &&
  324. conn->timestamp_lastwritten + 5*60 < now) {
  325. log_fn(LOG_INFO,"Expiring wedged directory conn (fd %d, purpose %d)", conn->s, conn->purpose);
  326. connection_mark_for_close(conn);
  327. return;
  328. }
  329. /* If we haven't written to an OR connection for a while, then either nuke
  330. the connection or send a keepalive, depending. */
  331. if(connection_speaks_cells(conn) &&
  332. now >= conn->timestamp_lastwritten + options->KeepalivePeriod) {
  333. routerinfo_t *router = router_get_by_digest(conn->identity_digest);
  334. if((!connection_state_is_open(conn)) ||
  335. (we_are_hibernating() && !circuit_get_by_conn(conn)) ||
  336. (!clique_mode(options) && !circuit_get_by_conn(conn) &&
  337. (!router || !server_mode(options) || !router_is_clique_mode(router)))) {
  338. /* our handshake has expired; we're hibernating;
  339. * or we have no circuits and we're both either OPs or normal ORs,
  340. * then kill it. */
  341. log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
  342. i,conn->address, conn->port);
  343. /* flush anything waiting, e.g. a destroy for a just-expired circ */
  344. connection_mark_for_close(conn);
  345. conn->hold_open_until_flushed = 1;
  346. } else {
  347. /* either in clique mode, or we've got a circuit. send a padding cell. */
  348. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  349. conn->address, conn->port);
  350. memset(&cell,0,sizeof(cell_t));
  351. cell.command = CELL_PADDING;
  352. connection_or_write_cell_to_buf(&cell, conn);
  353. }
  354. }
  355. }
  356. #define MIN_BW_TO_PUBLISH_DESC 5000 /* 5000 bytes/s sustained */
  357. #define MIN_UPTIME_TO_PUBLISH_DESC (30*60) /* half an hour */
  358. /** Decide if we're a publishable server or just a client. We are a server if:
  359. * - We have the AuthoritativeDirectory option set.
  360. * or
  361. * - We don't have the ClientOnly option set; and
  362. * - We have ORPort set; and
  363. * - We have been up for at least MIN_UPTIME_TO_PUBLISH_DESC seconds; and
  364. * - We have processed some suitable minimum bandwidth recently; and
  365. * - We believe we are reachable from the outside.
  366. */
  367. static int decide_if_publishable_server(time_t now) {
  368. int bw;
  369. or_options_t *options = get_options();
  370. bw = rep_hist_bandwidth_assess();
  371. router_set_bandwidth_capacity(bw);
  372. if(options->ClientOnly)
  373. return 0;
  374. if(!options->ORPort)
  375. return 0;
  376. /* XXX008 for now, you're only a server if you're a server */
  377. return server_mode(options);
  378. /* here, determine if we're reachable */
  379. if(0) { /* we've recently failed to reach our IP/ORPort from the outside */
  380. return 0;
  381. }
  382. if(bw < MIN_BW_TO_PUBLISH_DESC)
  383. return 0;
  384. if(options->AuthoritativeDir)
  385. return 1;
  386. if(stats_n_seconds_uptime < MIN_UPTIME_TO_PUBLISH_DESC)
  387. return 0;
  388. return 1;
  389. }
  390. /** Return true iff we believe ourselves to be an authoritative
  391. * directory server.
  392. */
  393. int authdir_mode(or_options_t *options) {
  394. return options->AuthoritativeDir != 0;
  395. }
  396. /** Return true iff we try to stay connected to all ORs at once.
  397. */
  398. int clique_mode(or_options_t *options) {
  399. return authdir_mode(options);
  400. }
  401. /** Return true iff we are trying to be a server.
  402. */
  403. int server_mode(or_options_t *options) {
  404. return (options->ORPort != 0 || options->ORBindAddress);
  405. }
  406. /** Remember if we've advertised ourselves to the dirservers. */
  407. static int server_is_advertised=0;
  408. /** Return true iff we have published our descriptor lately.
  409. */
  410. int advertised_server_mode(void) {
  411. return server_is_advertised;
  412. }
  413. /** Return true iff we are trying to be a socks proxy. */
  414. int proxy_mode(or_options_t *options) {
  415. return (options->SocksPort != 0 || options->SocksBindAddress);
  416. }
  417. /** Perform regular maintenance tasks. This function gets run once per
  418. * second by prepare_for_poll.
  419. */
  420. static void run_scheduled_events(time_t now) {
  421. static time_t last_uploaded_services = 0;
  422. static time_t last_rotated_certificate = 0;
  423. static time_t time_to_check_listeners = 0;
  424. or_options_t *options = get_options();
  425. int i;
  426. /** 0. See if we've been asked to shut down and our timeout has
  427. * expired; or if our bandwidth limits are exhausted and we
  428. * should hibernate; or if it's time to wake up from hibernation.
  429. */
  430. consider_hibernation(now);
  431. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  432. * shut down and restart all cpuworkers, and update the directory if
  433. * necessary.
  434. */
  435. if (server_mode(options) &&
  436. get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  437. log_fn(LOG_INFO,"Rotating onion key.");
  438. rotate_onion_key();
  439. cpuworkers_rotate();
  440. if (router_rebuild_descriptor()<0) {
  441. log_fn(LOG_WARN, "Couldn't rebuild router descriptor");
  442. }
  443. if(advertised_server_mode())
  444. router_upload_dir_desc_to_dirservers();
  445. }
  446. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  447. if (!last_rotated_certificate)
  448. last_rotated_certificate = now;
  449. if (last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
  450. log_fn(LOG_INFO,"Rotating tls context.");
  451. if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
  452. MAX_SSL_KEY_LIFETIME) < 0) {
  453. log_fn(LOG_WARN, "Error reinitializing TLS context");
  454. }
  455. last_rotated_certificate = now;
  456. /* XXXX We should rotate TLS connections as well; this code doesn't change
  457. * XXXX them at all. */
  458. }
  459. /** 1c. If we have to change the accounting interval or record
  460. * bandwidth used in this accounting interval, do so. */
  461. if (options->AccountingMaxKB)
  462. accounting_run_housekeeping(now);
  463. /** 2. Every DirFetchPostPeriod seconds, we get a new directory and upload
  464. * our descriptor (if we've passed our internal checks). */
  465. if(time_to_fetch_directory < now) {
  466. if(decide_if_publishable_server(now)) {
  467. server_is_advertised = 1;
  468. router_rebuild_descriptor();
  469. router_upload_dir_desc_to_dirservers();
  470. } else {
  471. server_is_advertised = 0;
  472. }
  473. /* purge obsolete entries */
  474. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  475. if(authdir_mode(options)) {
  476. /* We're a directory; dump any old descriptors. */
  477. dirserv_remove_old_servers(ROUTER_MAX_AGE);
  478. }
  479. if(server_mode(options) && !we_are_hibernating()) {
  480. /* dirservers try to reconnect, in case connections have failed;
  481. * and normal servers try to reconnect to dirservers */
  482. router_retry_connections();
  483. }
  484. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  485. if(!we_are_hibernating()) {
  486. /* Force an upload of our rend descriptors every DirFetchPostPeriod seconds. */
  487. rend_services_upload(1);
  488. last_uploaded_services = now;
  489. }
  490. rend_cache_clean(); /* should this go elsewhere? */
  491. time_to_fetch_directory = now + options->DirFetchPostPeriod;
  492. }
  493. /** 3a. Every second, we examine pending circuits and prune the
  494. * ones which have been pending for more than a few seconds.
  495. * We do this before step 3, so it can try building more if
  496. * it's not comfortable with the number of available circuits.
  497. */
  498. circuit_expire_building(now);
  499. /** 3b. Also look at pending streams and prune the ones that 'began'
  500. * a long time ago but haven't gotten a 'connected' yet.
  501. * Do this before step 3, so we can put them back into pending
  502. * state to be picked up by the new circuit.
  503. */
  504. connection_ap_expire_beginning();
  505. /** 3c. And expire connections that we've held open for too long.
  506. */
  507. connection_expire_held_open();
  508. /** 3d. And every 60 seconds, we relaunch listeners if any died. */
  509. if (!we_are_hibernating() && time_to_check_listeners < now) {
  510. retry_all_listeners(0); /* 0 means "only if some died." */
  511. time_to_check_listeners = now+60;
  512. }
  513. /** 4. Every second, we try a new circuit if there are no valid
  514. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  515. * that became dirty more than NewCircuitPeriod seconds ago,
  516. * and we make a new circ if there are no clean circuits.
  517. */
  518. if(has_fetched_directory && !we_are_hibernating())
  519. circuit_build_needed_circs(now);
  520. /** 5. We do housekeeping for each connection... */
  521. for(i=0;i<nfds;i++) {
  522. run_connection_housekeeping(i, now);
  523. }
  524. /** 6. And remove any marked circuits... */
  525. circuit_close_all_marked();
  526. /** 7. And upload service descriptors for any services whose intro points
  527. * have changed in the last second. */
  528. if (last_uploaded_services < now-5) {
  529. rend_services_upload(0);
  530. last_uploaded_services = now;
  531. }
  532. /** 8. and blow away any connections that need to die. have to do this now,
  533. * because if we marked a conn for close and left its socket -1, then
  534. * we'll pass it to poll/select and bad things will happen.
  535. */
  536. for(i=0;i<nfds;i++)
  537. conn_close_if_marked(i);
  538. }
  539. /** Called every time we're about to call tor_poll. Increments statistics,
  540. * and adjusts token buckets. Returns the number of milliseconds to use for
  541. * the poll() timeout.
  542. */
  543. static int prepare_for_poll(void) {
  544. static long current_second = 0; /* from previous calls to gettimeofday */
  545. connection_t *conn;
  546. struct timeval now;
  547. int i;
  548. tor_gettimeofday(&now);
  549. if(now.tv_sec > current_second) {
  550. /* the second has rolled over. check more stuff. */
  551. size_t bytes_written;
  552. size_t bytes_read;
  553. int seconds_elapsed;
  554. bytes_written = stats_prev_global_write_bucket - global_write_bucket;
  555. bytes_read = stats_prev_global_read_bucket - global_read_bucket;
  556. seconds_elapsed = current_second ? (now.tv_sec - current_second) : 0;
  557. stats_n_bytes_read += bytes_read;
  558. stats_n_bytes_written += bytes_written;
  559. if (get_options()->AccountingMaxKB)
  560. accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
  561. control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
  562. connection_bucket_refill(&now);
  563. stats_prev_global_read_bucket = global_read_bucket;
  564. stats_prev_global_write_bucket = global_write_bucket;
  565. stats_n_seconds_uptime += seconds_elapsed;
  566. assert_all_pending_dns_resolves_ok();
  567. run_scheduled_events(now.tv_sec);
  568. assert_all_pending_dns_resolves_ok();
  569. current_second = now.tv_sec; /* remember which second it is, for next time */
  570. }
  571. for(i=0;i<nfds;i++) {
  572. conn = connection_array[i];
  573. if(connection_has_pending_tls_data(conn) &&
  574. connection_is_reading(conn)) {
  575. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  576. return 0; /* has pending bytes to read; don't let poll wait. */
  577. }
  578. }
  579. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  580. }
  581. /** Called when we get a SIGHUP: reload configuration files and keys,
  582. * retry all connections, re-upload all descriptors, and so on. */
  583. static int do_hup(void) {
  584. char keydir[512];
  585. or_options_t *options = get_options();
  586. log_fn(LOG_NOTICE,"Received sighup. Reloading config.");
  587. has_completed_circuit=0;
  588. /* first, reload config variables, in case they've changed */
  589. /* no need to provide argc/v, they've been cached inside init_from_config */
  590. if (init_from_config(0, NULL) < 0) {
  591. log_fn(LOG_ERR,"Reading config failed--see warnings above. For usage, try -h.");
  592. return -1;
  593. }
  594. options = get_options();
  595. if(authdir_mode(options)) {
  596. /* reload the approved-routers file */
  597. tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", options->DataDirectory);
  598. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  599. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  600. log_fn(LOG_WARN, "Error reloading fingerprints. Continuing with old list.");
  601. }
  602. }
  603. /* Fetch a new directory. Even authdirservers do this. */
  604. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  605. if(server_mode(options)) {
  606. /* Restart cpuworker and dnsworker processes, so they get up-to-date
  607. * configuration options. */
  608. cpuworkers_rotate();
  609. dnsworkers_rotate();
  610. /* Rebuild fresh descriptor as needed. */
  611. router_rebuild_descriptor();
  612. tor_snprintf(keydir,sizeof(keydir),"%s/router.desc", options->DataDirectory);
  613. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  614. if (write_str_to_file(keydir, router_get_my_descriptor(), 0)) {
  615. return -1;
  616. }
  617. }
  618. return 0;
  619. }
  620. /** Tor main loop. */
  621. static int do_main_loop(void) {
  622. int i;
  623. int timeout;
  624. int poll_result;
  625. /* Initialize the history structures. */
  626. rep_hist_init();
  627. /* Intialize the service cache. */
  628. rend_cache_init();
  629. /* load the private keys, if we're supposed to have them, and set up the
  630. * TLS context. */
  631. if (init_keys() < 0) {
  632. log_fn(LOG_ERR,"Error initializing keys; exiting");
  633. return -1;
  634. }
  635. /* Set up our buckets */
  636. connection_bucket_init();
  637. stats_prev_global_read_bucket = global_read_bucket;
  638. stats_prev_global_write_bucket = global_write_bucket;
  639. /*XXX move to options_act? */
  640. /* Set up accounting */
  641. if (get_options()->AccountingMaxKB)
  642. configure_accounting(time(NULL));
  643. /* load the routers file, or assign the defaults. */
  644. if(router_reload_router_list()) {
  645. return -1;
  646. }
  647. if(authdir_mode(get_options())) {
  648. /* the directory is already here, run startup things */
  649. router_retry_connections();
  650. }
  651. if(server_mode(get_options())) {
  652. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  653. cpu_init();
  654. }
  655. for(;;) {
  656. #ifdef MS_WINDOWS_SERVICE /* Do service stuff only on windows. */
  657. if (service_status.dwCurrentState != SERVICE_RUNNING) {
  658. return 0;
  659. }
  660. #endif
  661. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  662. if(please_shutdown) {
  663. if(!server_mode(get_options())) { /* do it now */
  664. log(LOG_NOTICE,"Interrupt: exiting cleanly.");
  665. tor_cleanup();
  666. exit(0);
  667. }
  668. hibernate_begin_shutdown();
  669. please_shutdown = 0;
  670. }
  671. if(please_sigpipe) {
  672. log(LOG_NOTICE,"Caught sigpipe. Ignoring.");
  673. please_sigpipe = 0;
  674. }
  675. if(please_dumpstats) {
  676. /* prefer to log it at INFO, but make sure we always see it */
  677. dumpstats(get_min_log_level()>LOG_INFO ? get_min_log_level() : LOG_INFO);
  678. please_dumpstats = 0;
  679. }
  680. if(please_reset) {
  681. if (do_hup() < 0) {
  682. log_fn(LOG_WARN,"Restart failed (config error?). Exiting.");
  683. tor_cleanup();
  684. exit(1);
  685. }
  686. please_reset = 0;
  687. }
  688. if(please_reap_children) {
  689. while(waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more zombies */
  690. please_reap_children = 0;
  691. }
  692. #endif /* signal stuff */
  693. timeout = prepare_for_poll();
  694. /* poll until we have an event, or the second ends */
  695. poll_result = tor_poll(poll_array, nfds, timeout);
  696. /* let catch() handle things like ^c, and otherwise don't worry about it */
  697. if(poll_result < 0) {
  698. /* let the program survive things like ^z */
  699. if(tor_socket_errno(-1) != EINTR) {
  700. log_fn(LOG_ERR,"poll failed: %s [%d]",
  701. tor_socket_strerror(tor_socket_errno(-1)),
  702. tor_socket_errno(-1));
  703. return -1;
  704. } else {
  705. log_fn(LOG_DEBUG,"poll interrupted.");
  706. }
  707. }
  708. /* do all the reads and errors first, so we can detect closed sockets */
  709. for(i=0;i<nfds;i++)
  710. conn_read(i); /* this also marks broken connections */
  711. /* then do the writes */
  712. for(i=0;i<nfds;i++)
  713. conn_write(i);
  714. /* any of the conns need to be closed now? */
  715. for(i=0;i<nfds;i++)
  716. conn_close_if_marked(i);
  717. /* refilling buckets and sending cells happens at the beginning of the
  718. * next iteration of the loop, inside prepare_for_poll()
  719. */
  720. }
  721. }
  722. /** Unix signal handler. */
  723. static void catch(int the_signal) {
  724. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  725. switch(the_signal) {
  726. // case SIGABRT:
  727. case SIGTERM:
  728. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  729. tor_cleanup();
  730. exit(0);
  731. case SIGINT:
  732. please_shutdown = 1;
  733. break;
  734. case SIGPIPE:
  735. /* don't log here, since it's possible you got the sigpipe because
  736. * your log failed! */
  737. please_sigpipe = 1;
  738. break;
  739. case SIGHUP:
  740. please_reset = 1;
  741. break;
  742. case SIGUSR1:
  743. please_dumpstats = 1;
  744. break;
  745. case SIGCHLD:
  746. please_reap_children = 1;
  747. break;
  748. default:
  749. log(LOG_WARN,"Caught signal %d that we can't handle??", the_signal);
  750. tor_cleanup();
  751. exit(1);
  752. }
  753. #endif /* signal stuff */
  754. }
  755. /** Write all statistics to the log, with log level 'severity'. Called
  756. * in response to a SIGUSR1. */
  757. static void dumpstats(int severity) {
  758. int i;
  759. connection_t *conn;
  760. time_t now = time(NULL);
  761. log(severity, "Dumping stats:");
  762. for(i=0;i<nfds;i++) {
  763. conn = connection_array[i];
  764. log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  765. i, conn->s, conn->type, CONN_TYPE_TO_STRING(conn->type),
  766. conn->state, conn_state_to_string[conn->type][conn->state], (int)(now - conn->timestamp_created));
  767. if(!connection_is_listener(conn)) {
  768. log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
  769. log(severity,"Conn %d: %d bytes waiting on inbuf (last read %d secs ago)",i,
  770. (int)buf_datalen(conn->inbuf),
  771. (int)(now - conn->timestamp_lastread));
  772. log(severity,"Conn %d: %d bytes waiting on outbuf (last written %d secs ago)",i,
  773. (int)buf_datalen(conn->outbuf), (int)(now - conn->timestamp_lastwritten));
  774. }
  775. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
  776. }
  777. log(severity,
  778. "Cells processed: %10lu padding\n"
  779. " %10lu create\n"
  780. " %10lu created\n"
  781. " %10lu relay\n"
  782. " (%10lu relayed)\n"
  783. " (%10lu delivered)\n"
  784. " %10lu destroy",
  785. stats_n_padding_cells_processed,
  786. stats_n_create_cells_processed,
  787. stats_n_created_cells_processed,
  788. stats_n_relay_cells_processed,
  789. stats_n_relay_cells_relayed,
  790. stats_n_relay_cells_delivered,
  791. stats_n_destroy_cells_processed);
  792. if (stats_n_data_cells_packaged)
  793. log(severity,"Average packaged cell fullness: %2.3f%%",
  794. 100*(((double)stats_n_data_bytes_packaged) /
  795. (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  796. if (stats_n_data_cells_received)
  797. log(severity,"Average delivered cell fullness: %2.3f%%",
  798. 100*(((double)stats_n_data_bytes_received) /
  799. (stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  800. if (stats_n_seconds_uptime)
  801. log(severity,
  802. "Average bandwidth used: "U64_FORMAT"/%ld = %d bytes/sec",
  803. U64_PRINTF_ARG(stats_n_bytes_read),
  804. stats_n_seconds_uptime,
  805. (int) (stats_n_bytes_read/stats_n_seconds_uptime));
  806. rep_hist_dump_stats(now,severity);
  807. rend_service_dump_stats(severity);
  808. }
  809. /** Called before we make any calls to network-related functions.
  810. * (Some operating systems require their network libraries to be
  811. * initialized.) */
  812. static int network_init(void)
  813. {
  814. #ifdef MS_WINDOWS
  815. /* This silly exercise is necessary before windows will allow gethostbyname to work.
  816. */
  817. WSADATA WSAData;
  818. int r;
  819. r = WSAStartup(0x101,&WSAData);
  820. if (r) {
  821. log_fn(LOG_WARN,"Error initializing windows network layer: code was %d",r);
  822. return -1;
  823. }
  824. /* XXXX We should call WSACleanup on exit, I think. */
  825. #endif
  826. return 0;
  827. }
  828. /** Called by exit() as we shut down the process.
  829. */
  830. static void exit_function(void)
  831. {
  832. /* XXX if we ever daemonize, this gets called immediately */
  833. #ifdef MS_WINDOWS
  834. WSACleanup();
  835. #endif
  836. }
  837. /** Set up the signal handlers for either parent or child. */
  838. void handle_signals(int is_parent)
  839. {
  840. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  841. struct sigaction action;
  842. action.sa_flags = 0;
  843. sigemptyset(&action.sa_mask);
  844. action.sa_handler = is_parent ? catch : SIG_IGN;
  845. sigaction(SIGINT, &action, NULL); /* do a controlled slow shutdown */
  846. sigaction(SIGTERM, &action, NULL); /* to terminate now */
  847. sigaction(SIGPIPE, &action, NULL); /* otherwise sigpipe kills us */
  848. sigaction(SIGUSR1, &action, NULL); /* dump stats */
  849. sigaction(SIGHUP, &action, NULL); /* to reload config, retry conns, etc */
  850. if(is_parent)
  851. sigaction(SIGCHLD, &action, NULL); /* handle dns/cpu workers that exit */
  852. #endif /* signal stuff */
  853. }
  854. /** Main entry point for the Tor command-line client.
  855. */
  856. static int tor_init(int argc, char *argv[]) {
  857. /* give it somewhere to log to initially */
  858. add_temp_log();
  859. log_fn(LOG_NOTICE,"Tor v%s. This is experimental software. Do not use it if you need anonymity.",VERSION);
  860. if (network_init()<0) {
  861. log_fn(LOG_ERR,"Error initializing network; exiting.");
  862. return -1;
  863. }
  864. atexit(exit_function);
  865. if (init_from_config(argc,argv) < 0) {
  866. log_fn(LOG_ERR,"Reading config failed--see warnings above. For usage, try -h.");
  867. return -1;
  868. }
  869. #ifndef MS_WINDOWS
  870. if(geteuid()==0)
  871. log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
  872. #endif
  873. if(server_mode(get_options())) { /* only spawn dns handlers if we're a router */
  874. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  875. }
  876. client_dns_init(); /* Init the client dns cache. Do it always, since it's cheap. */
  877. handle_signals(1);
  878. crypto_global_init();
  879. crypto_seed_rng();
  880. return 0;
  881. }
  882. /** Do whatever cleanup is necessary before shutting Tor down. */
  883. void tor_cleanup(void) {
  884. or_options_t *options = get_options();
  885. /* Remove our pid file. We don't care if there was an error when we
  886. * unlink, nothing we could do about it anyways. */
  887. if(options->PidFile && options->command == CMD_RUN_TOR)
  888. unlink(options->PidFile);
  889. crypto_global_cleanup();
  890. }
  891. /** Read/create keys as needed, and echo our fingerprint to stdout. */
  892. static void do_list_fingerprint(void)
  893. {
  894. char buf[FINGERPRINT_LEN+1];
  895. crypto_pk_env_t *k;
  896. const char *nickname = get_options()->Nickname;
  897. if (init_keys() < 0) {
  898. log_fn(LOG_ERR,"Error initializing keys; exiting");
  899. return;
  900. }
  901. if (!(k = get_identity_key())) {
  902. log_fn(LOG_ERR,"Error: missing identity key.");
  903. return;
  904. }
  905. if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
  906. log_fn(LOG_ERR, "Error computing fingerprint");
  907. return;
  908. }
  909. printf("%s %s\n", nickname?nickname:"client", buf);
  910. }
  911. /** Entry point for password hashing: take the desired password from
  912. * the command line, and print its salted hash to stdout. **/
  913. static void do_hash_password(void)
  914. {
  915. char output[256];
  916. char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
  917. crypto_rand(key, S2K_SPECIFIER_LEN-1);
  918. key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
  919. secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
  920. get_options()->command_arg, strlen(get_options()->command_arg),
  921. key);
  922. if (base64_encode(output, sizeof(output), key, sizeof(key))<0) {
  923. log_fn(LOG_ERR, "Unable to compute base64");
  924. } else {
  925. printf("%s",output);
  926. }
  927. }
  928. #ifdef MS_WINDOWS_SERVICE
  929. void nt_service_control(DWORD request)
  930. {
  931. switch (request) {
  932. case SERVICE_CONTROL_STOP:
  933. case SERVICE_CONTROL_SHUTDOWN:
  934. log(LOG_ERR, "Got stop/shutdown request; shutting down cleanly.");
  935. service_status.dwWin32ExitCode = 0;
  936. service_status.dwCurrentState = SERVICE_STOPPED;
  937. return;
  938. }
  939. SetServiceStatus(hStatus, &service_status);
  940. }
  941. void nt_service_body(int argc, char **argv)
  942. {
  943. int err;
  944. FILE *f;
  945. f = fopen("d:\\foo.txt", "w");
  946. fprintf(f, "POINT 1\n");
  947. fclose(f);
  948. service_status.dwServiceType = SERVICE_WIN32;
  949. service_status.dwCurrentState = SERVICE_START_PENDING;
  950. service_status.dwControlsAccepted =
  951. SERVICE_ACCEPT_STOP |
  952. SERVICE_ACCEPT_SHUTDOWN;
  953. service_status.dwWin32ExitCode = 0;
  954. service_status.dwServiceSpecificExitCode = 0;
  955. service_status.dwCheckPoint = 0;
  956. service_status.dwWaitHint = 0;
  957. hStatus = RegisterServiceCtrlHandler("Tor", (LPHANDLER_FUNCTION) nt_service_control);
  958. if (hStatus == 0) {
  959. // failed;
  960. return;
  961. }
  962. err = tor_init(argc, argv); // refactor this part out of tor_main and do_main_loop
  963. if (err) {
  964. // failed.
  965. service_status.dwCurrentState = SERVICE_STOPPED;
  966. service_status.dwWin32ExitCode = -1;
  967. SetServiceStatus(hStatus, &service_status);
  968. return;
  969. }
  970. service_status.dwCurrentState = SERVICE_RUNNING;
  971. SetServiceStatus(hStatus, &service_status);
  972. do_main_loop();
  973. tor_cleanup();
  974. return;
  975. }
  976. void nt_service_main(void)
  977. {
  978. SERVICE_TABLE_ENTRY table[2];
  979. table[0].lpServiceName = "Tor";
  980. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
  981. table[1].lpServiceName = NULL;
  982. table[1].lpServiceProc = NULL;
  983. if (!StartServiceCtrlDispatcher(table))
  984. printf("Error was %d\n",GetLastError());
  985. }
  986. #endif
  987. int tor_main(int argc, char *argv[]) {
  988. #ifdef MS_WINDOWS_SERVICE
  989. nt_service_main();
  990. return 0;
  991. #else
  992. if (tor_init(argc, argv)<0)
  993. return -1;
  994. switch (get_options()->command) {
  995. case CMD_RUN_TOR:
  996. do_main_loop();
  997. break;
  998. case CMD_LIST_FINGERPRINT:
  999. do_list_fingerprint();
  1000. break;
  1001. case CMD_HASH_PASSWORD:
  1002. do_hash_password();
  1003. break;
  1004. default:
  1005. log_fn(LOG_ERR, "Illegal command number %d: internal error.",
  1006. get_options()->command);
  1007. }
  1008. tor_cleanup();
  1009. return -1;
  1010. #endif
  1011. }
  1012. /*
  1013. Local Variables:
  1014. mode:c
  1015. indent-tabs-mode:nil
  1016. c-basic-offset:2
  1017. End:
  1018. */