main.c 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * \file main.c
  6. * \brief Tor main loop and startup functions.
  7. **/
  8. #include "or.h"
  9. /********* PROTOTYPES **********/
  10. static void dumpstats(int severity); /* log stats */
  11. static int init_from_config(int argc, char **argv);
  12. /********* START VARIABLES **********/
  13. /* declared in connection.c */
  14. extern char *conn_state_to_string[][_CONN_TYPE_MAX+1];
  15. or_options_t options; /**< Command-line and config-file options. */
  16. int global_read_bucket; /**< Max number of bytes I can read this second. */
  17. /** What was the read bucket before the last call to prepare_for_pool?
  18. * (used to determine how many bytes we've read). */
  19. static int stats_prev_global_read_bucket;
  20. /** How many bytes have we read since we started the process? */
  21. static uint64_t stats_n_bytes_read = 0;
  22. /** How many seconds have we been running? */
  23. long stats_n_seconds_uptime = 0;
  24. /** Array of all open connections; each element corresponds to the element of
  25. * poll_array in the same position. The first nfds elements are valid. */
  26. static connection_t *connection_array[MAXCONNECTIONS] =
  27. { NULL };
  28. /** Array of pollfd objects for calls to poll(). */
  29. static struct pollfd poll_array[MAXCONNECTIONS];
  30. static int nfds=0; /**< Number of connections currently active. */
  31. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  32. static int please_dumpstats=0; /**< Whether we should dump stats during the loop. */
  33. static int please_reset=0; /**< Whether we just got a sighup. */
  34. static int please_reap_children=0; /**< Whether we should waitpid for exited children. */
  35. static int please_shutdown=0; /**< Whether we should shut down Tor. */
  36. #endif /* signal stuff */
  37. /** We should exit if shutting_down != 0 and now <= shutting_down.
  38. * If it's non-zero, don't accept any new circuits or connections.
  39. * This gets assigned when we receive a sig_int, and if we receive a
  40. * second one we exit immediately. */
  41. int shutting_down=0;
  42. #define SHUTDOWN_WAIT_LENGTH 30 /* seconds */
  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
  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 >= 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 && conn->poll_index >= 0 && conn->poll_index < nfds);
  132. poll_array[conn->poll_index].events = events;
  133. }
  134. /** Return true iff <b>conn</b> is listening for read events. */
  135. int connection_is_reading(connection_t *conn) {
  136. tor_assert(conn && conn->poll_index >= 0);
  137. return poll_array[conn->poll_index].events & POLLIN;
  138. }
  139. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  140. void connection_stop_reading(connection_t *conn) {
  141. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  142. log(LOG_DEBUG,"connection_stop_reading() called.");
  143. if(poll_array[conn->poll_index].events & POLLIN)
  144. poll_array[conn->poll_index].events -= POLLIN;
  145. }
  146. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  147. void connection_start_reading(connection_t *conn) {
  148. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  149. poll_array[conn->poll_index].events |= POLLIN;
  150. }
  151. /** Return true iff <b>conn</b> is listening for write events. */
  152. int connection_is_writing(connection_t *conn) {
  153. return poll_array[conn->poll_index].events & POLLOUT;
  154. }
  155. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  156. void connection_stop_writing(connection_t *conn) {
  157. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  158. if(poll_array[conn->poll_index].events & POLLOUT)
  159. poll_array[conn->poll_index].events -= POLLOUT;
  160. }
  161. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  162. void connection_start_writing(connection_t *conn) {
  163. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  164. poll_array[conn->poll_index].events |= POLLOUT;
  165. }
  166. /** Called when the connection at connection_array[i] has a read event,
  167. * or it has pending tls data waiting to be read: checks for validity,
  168. * catches numerous errors, and dispatches to connection_handle_read.
  169. */
  170. static void conn_read(int i) {
  171. connection_t *conn = connection_array[i];
  172. if (conn->marked_for_close)
  173. return;
  174. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
  175. * discussion of POLLIN vs POLLHUP */
  176. if(!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
  177. if(!connection_is_reading(conn) ||
  178. !connection_has_pending_tls_data(conn))
  179. return; /* this conn should not read */
  180. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  181. assert_connection_ok(conn, time(NULL));
  182. assert_all_pending_dns_resolves_ok();
  183. if(
  184. /* XXX does POLLHUP also mean it's definitely broken? */
  185. #ifdef MS_WINDOWS
  186. (poll_array[i].revents & POLLERR) ||
  187. #endif
  188. connection_handle_read(conn) < 0) {
  189. if (!conn->marked_for_close) {
  190. /* this connection is broken. remove it */
  191. log_fn(LOG_WARN,"Unhandled error on read for %s connection (fd %d); removing",
  192. CONN_TYPE_TO_STRING(conn->type), conn->s);
  193. connection_mark_for_close(conn);
  194. }
  195. }
  196. assert_connection_ok(conn, time(NULL));
  197. assert_all_pending_dns_resolves_ok();
  198. }
  199. /** Called when the connection at connection_array[i] has a write event:
  200. * checks for validity, catches numerous errors, and dispatches to
  201. * connection_handle_write.
  202. */
  203. static void conn_write(int i) {
  204. connection_t *conn;
  205. if(!(poll_array[i].revents & POLLOUT))
  206. return; /* this conn doesn't want to write */
  207. conn = connection_array[i];
  208. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  209. if (conn->marked_for_close)
  210. return;
  211. assert_connection_ok(conn, time(NULL));
  212. assert_all_pending_dns_resolves_ok();
  213. if (connection_handle_write(conn) < 0) {
  214. if (!conn->marked_for_close) {
  215. /* this connection is broken. remove it. */
  216. log_fn(LOG_WARN,"Unhandled error on read for %s connection (fd %d); removing",
  217. CONN_TYPE_TO_STRING(conn->type), conn->s);
  218. conn->has_sent_end = 1; /* otherwise we cry wolf about duplicate close */
  219. /* XXX do we need a close-immediate here, so we don't try to flush? */
  220. connection_mark_for_close(conn);
  221. }
  222. }
  223. assert_connection_ok(conn, time(NULL));
  224. assert_all_pending_dns_resolves_ok();
  225. }
  226. /** If the connection at connection_array[i] is marked for close, then:
  227. * - If it has data that it wants to flush, try to flush it.
  228. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  229. * true, then leave the connection open and return.
  230. * - Otherwise, remove the connection from connection_array and from
  231. * all other lists, close it, and free it.
  232. * If we remove the connection, then call conn_closed_if_marked at the new
  233. * connection at position i.
  234. */
  235. static void conn_close_if_marked(int i) {
  236. connection_t *conn;
  237. int retval;
  238. conn = connection_array[i];
  239. assert_connection_ok(conn, time(NULL));
  240. assert_all_pending_dns_resolves_ok();
  241. if(!conn->marked_for_close)
  242. return; /* nothing to see here, move along */
  243. log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
  244. if(conn->s >= 0 && connection_wants_to_flush(conn)) {
  245. /* -1 means it's an incomplete edge connection, or that the socket
  246. * has already been closed as unflushable. */
  247. if(!conn->hold_open_until_flushed)
  248. log_fn(LOG_WARN,
  249. "Conn (fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
  250. "(Marked at %s:%d)",
  251. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  252. conn->outbuf_flushlen, conn->marked_for_close_file, conn->marked_for_close);
  253. if(connection_speaks_cells(conn)) {
  254. if(conn->state == OR_CONN_STATE_OPEN) {
  255. retval = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  256. } else
  257. retval = -1; /* never flush non-open broken tls connections */
  258. } else {
  259. retval = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  260. }
  261. if(retval >= 0 &&
  262. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  263. log_fn(LOG_INFO,"Holding conn (fd %d) open for more flushing.",conn->s);
  264. /* XXX should we reset timestamp_lastwritten here? */
  265. return;
  266. }
  267. if(connection_wants_to_flush(conn)) {
  268. log_fn(LOG_WARN,"Conn (fd %d, type %s, state %d) still wants to flush. Losing %d bytes! (Marked at %s:%d)",
  269. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  270. (int)buf_datalen(conn->outbuf), conn->marked_for_close_file,
  271. conn->marked_for_close);
  272. }
  273. }
  274. /* if it's an edge conn, remove it from the list
  275. * of conn's on this circuit. If it's not on an edge,
  276. * flush and send destroys for all circuits on this conn
  277. */
  278. circuit_about_to_close_connection(conn);
  279. connection_about_to_close_connection(conn);
  280. connection_remove(conn);
  281. if(conn->type == CONN_TYPE_EXIT) {
  282. assert_connection_edge_not_dns_pending(conn);
  283. }
  284. connection_free(conn);
  285. if(i<nfds) { /* we just replaced the one at i with a new one.
  286. process it too. */
  287. conn_close_if_marked(i);
  288. }
  289. }
  290. /** This function is called whenever we successfully pull down a directory */
  291. void directory_has_arrived(void) {
  292. log_fn(LOG_INFO, "A directory has arrived.");
  293. has_fetched_directory=1;
  294. if(clique_mode()) { /* connect to them all */
  295. router_retry_connections();
  296. }
  297. }
  298. /** Perform regular maintenance tasks for a single connection. This
  299. * function gets run once per second per connection by run_housekeeping.
  300. */
  301. static void run_connection_housekeeping(int i, time_t now) {
  302. cell_t cell;
  303. connection_t *conn = connection_array[i];
  304. /* Expire any directory connections that haven't sent anything for 5 min */
  305. if(conn->type == CONN_TYPE_DIR &&
  306. !conn->marked_for_close &&
  307. conn->timestamp_lastwritten + 5*60 < now) {
  308. log_fn(LOG_INFO,"Expiring wedged directory conn (fd %d, purpose %d)", conn->s, conn->purpose);
  309. connection_mark_for_close(conn);
  310. return;
  311. }
  312. /* If we haven't written to an OR connection for a while, then either nuke
  313. the connection or send a keepalive, depending. */
  314. if(connection_speaks_cells(conn) &&
  315. now >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
  316. routerinfo_t *router = router_get_by_digest(conn->identity_digest);
  317. if((!connection_state_is_open(conn)) ||
  318. (!clique_mode() && !circuit_get_by_conn(conn) &&
  319. (!router || !server_mode() || !router_is_clique_mode(router)))) {
  320. /* our handshake has expired;
  321. * or we're not an authdirserver, we have no circuits, and
  322. * either he's an OP, we're an OP, or we're both ORs and he's
  323. * running 0.0.8 and he's not an authdirserver,
  324. * then kill it. */
  325. log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
  326. i,conn->address, conn->port);
  327. /* flush anything waiting, e.g. a destroy for a just-expired circ */
  328. connection_mark_for_close(conn);
  329. conn->hold_open_until_flushed = 1;
  330. } else {
  331. /* either in clique mode, or we've got a circuit. send a padding cell. */
  332. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  333. conn->address, conn->port);
  334. memset(&cell,0,sizeof(cell_t));
  335. cell.command = CELL_PADDING;
  336. connection_or_write_cell_to_buf(&cell, conn);
  337. }
  338. }
  339. }
  340. #define MIN_BW_TO_PUBLISH_DESC 5000 /* 5000 bytes/s sustained */
  341. #define MIN_UPTIME_TO_PUBLISH_DESC (30*60) /* half an hour */
  342. /** Decide if we're a publishable server or just a client. We are a server if:
  343. * - We have the AuthoritativeDirectory option set.
  344. * or
  345. * - We don't have the ClientOnly option set; and
  346. * - We have ORPort set; and
  347. * - We have been up for at least MIN_UPTIME_TO_PUBLISH_DESC seconds; and
  348. * - We have processed some suitable minimum bandwidth recently; and
  349. * - We believe we are reachable from the outside.
  350. */
  351. static int decide_if_publishable_server(time_t now) {
  352. int r;
  353. if(options.ClientOnly)
  354. return 0;
  355. if(!options.ORPort)
  356. return 0;
  357. /* XXX008 for now, you're only a server if you're a server */
  358. return server_mode();
  359. /* here, determine if we're reachable */
  360. if(0) { /* we've recently failed to reach our IP/ORPort from the outside */
  361. return 0;
  362. }
  363. r = rep_hist_bandwidth_assess(now);
  364. // set_advertised_bandwidth(r);
  365. if(r < MIN_BW_TO_PUBLISH_DESC)
  366. return 0;
  367. if(options.AuthoritativeDir)
  368. return 1;
  369. if(stats_n_seconds_uptime < MIN_UPTIME_TO_PUBLISH_DESC)
  370. return 0;
  371. return 1;
  372. }
  373. /** Return true iff we believe ourselves to be an authoritative
  374. * directory server.
  375. */
  376. int authdir_mode(void) {
  377. return (options.AuthoritativeDir != 0);
  378. }
  379. /** Return true iff we try to stay connected to all ORs at once.
  380. */
  381. int clique_mode(void) {
  382. return authdir_mode();
  383. }
  384. /** Return true iff we are trying to be a server.
  385. */
  386. int server_mode(void) {
  387. return (options.ORPort != 0);
  388. }
  389. /** Return true iff we are trying to be an exit server.
  390. */
  391. int exit_server_mode(void) {
  392. return (options.ORPort != 0);
  393. }
  394. /** Return true iff we are trying to be a socks proxy. */
  395. int proxy_mode(void) {
  396. return (options.SocksPort != 0);
  397. }
  398. /** Perform regular maintenance tasks. This function gets run once per
  399. * second by prepare_for_poll.
  400. */
  401. static void run_scheduled_events(time_t now) {
  402. static long time_to_fetch_directory = 0;
  403. static time_t last_uploaded_services = 0;
  404. static time_t last_rotated_certificate = 0;
  405. int i;
  406. /** 0. See if we've been asked to shut down and our timeout has
  407. * expired. If so, exit now.
  408. */
  409. if(shutting_down && shutting_down <= now) {
  410. log(LOG_NOTICE,"Clean shutdown finished. Exiting.");
  411. exit(0);
  412. }
  413. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  414. * shut down and restart all cpuworkers, and update the directory if
  415. * necessary.
  416. */
  417. if (server_mode() && get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  418. log_fn(LOG_INFO,"Rotating onion key.");
  419. rotate_onion_key();
  420. cpuworkers_rotate();
  421. if (router_rebuild_descriptor()<0) {
  422. log_fn(LOG_WARN, "Couldn't rebuild router descriptor");
  423. }
  424. router_upload_dir_desc_to_dirservers();
  425. }
  426. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  427. if (!last_rotated_certificate)
  428. last_rotated_certificate = now;
  429. /*XXXX008 we should remove the server_mode() check once OPs also use
  430. * identity keys (which they can't do until the known-router check in
  431. * connection_or.c is removed. */
  432. if (server_mode() && last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
  433. log_fn(LOG_INFO,"Rotating tls context.");
  434. if (tor_tls_context_new(get_identity_key(), 1, options.Nickname,
  435. MAX_SSL_KEY_LIFETIME) < 0) {
  436. log_fn(LOG_WARN, "Error reinitializing TLS context");
  437. }
  438. last_rotated_certificate = now;
  439. /* XXXX We should rotate TLS connections as well; this code doesn't change
  440. * XXXX them at all. */
  441. }
  442. /** 2. Every DirFetchPostPeriod seconds, we get a new directory and upload
  443. * our descriptor (if we've passed our internal checks). */
  444. if(time_to_fetch_directory < now) {
  445. if(decide_if_publishable_server(now)) {
  446. router_rebuild_descriptor();
  447. router_upload_dir_desc_to_dirservers();
  448. }
  449. routerlist_remove_old_routers(); /* purge obsolete entries */
  450. if(authdir_mode()) {
  451. /* We're a directory; dump any old descriptors. */
  452. dirserv_remove_old_servers();
  453. /* dirservers try to reconnect, in case connections have failed */
  454. router_retry_connections();
  455. }
  456. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  457. /* Force an upload of our rend descriptors every DirFetchPostPeriod seconds. */
  458. rend_services_upload(1);
  459. last_uploaded_services = now;
  460. rend_cache_clean(); /* should this go elsewhere? */
  461. time_to_fetch_directory = now + options.DirFetchPostPeriod;
  462. }
  463. /** 3a. Every second, we examine pending circuits and prune the
  464. * ones which have been pending for more than a few seconds.
  465. * We do this before step 3, so it can try building more if
  466. * it's not comfortable with the number of available circuits.
  467. */
  468. circuit_expire_building(now);
  469. /** 3b. Also look at pending streams and prune the ones that 'began'
  470. * a long time ago but haven't gotten a 'connected' yet.
  471. * Do this before step 3, so we can put them back into pending
  472. * state to be picked up by the new circuit.
  473. */
  474. connection_ap_expire_beginning();
  475. /** 3c. And expire connections that we've held open for too long.
  476. */
  477. connection_expire_held_open();
  478. /** 4. Every second, we try a new circuit if there are no valid
  479. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  480. * that became dirty more than NewCircuitPeriod seconds ago,
  481. * and we make a new circ if there are no clean circuits.
  482. */
  483. if(has_fetched_directory)
  484. circuit_build_needed_circs(now);
  485. /** 5. We do housekeeping for each connection... */
  486. for(i=0;i<nfds;i++) {
  487. run_connection_housekeeping(i, now);
  488. }
  489. /** 6. And remove any marked circuits... */
  490. circuit_close_all_marked();
  491. /** 7. And upload service descriptors for any services whose intro points
  492. * have changed in the last second. */
  493. if (last_uploaded_services < now-5) {
  494. rend_services_upload(0);
  495. last_uploaded_services = now;
  496. }
  497. /** 8. and blow away any connections that need to die. have to do this now,
  498. * because if we marked a conn for close and left its socket -1, then
  499. * we'll pass it to poll/select and bad things will happen.
  500. */
  501. for(i=0;i<nfds;i++)
  502. conn_close_if_marked(i);
  503. }
  504. /** Called every time we're about to call tor_poll. Increments statistics,
  505. * and adjusts token buckets. Returns the number of milliseconds to use for
  506. * the poll() timeout.
  507. */
  508. static int prepare_for_poll(void) {
  509. static long current_second = 0; /* from previous calls to gettimeofday */
  510. connection_t *conn;
  511. struct timeval now;
  512. int i;
  513. tor_gettimeofday(&now);
  514. /* Check how much bandwidth we've consumed, and increment the token
  515. * buckets. */
  516. stats_n_bytes_read += stats_prev_global_read_bucket - global_read_bucket;
  517. connection_bucket_refill(&now);
  518. stats_prev_global_read_bucket = global_read_bucket;
  519. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  520. if(current_second)
  521. stats_n_seconds_uptime += (now.tv_sec - current_second);
  522. assert_all_pending_dns_resolves_ok();
  523. run_scheduled_events(now.tv_sec);
  524. assert_all_pending_dns_resolves_ok();
  525. current_second = now.tv_sec; /* remember which second it is, for next time */
  526. }
  527. for(i=0;i<nfds;i++) {
  528. conn = connection_array[i];
  529. if(connection_has_pending_tls_data(conn) &&
  530. connection_is_reading(conn)) {
  531. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  532. return 0; /* has pending bytes to read; don't let poll wait. */
  533. }
  534. }
  535. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  536. }
  537. /** Configure the Tor process from the command line arguments and from the
  538. * configuration file.
  539. */
  540. static int init_from_config(int argc, char **argv) {
  541. /* read the configuration file. */
  542. if(getconfig(argc,argv,&options)) {
  543. log_fn(LOG_ERR,"Reading config failed. For usage, try -h.");
  544. return -1;
  545. }
  546. /* Setuid/setgid as appropriate */
  547. if(options.User || options.Group) {
  548. if(switch_id(options.User, options.Group) != 0) {
  549. return -1;
  550. }
  551. }
  552. /* Ensure data directory is private; create if possible. */
  553. if (check_private_dir(get_data_directory(&options), 1) != 0) {
  554. log_fn(LOG_ERR, "Couldn't access/create private data directory %s",
  555. get_data_directory(&options));
  556. return -1;
  557. }
  558. /* Start backgrounding the process, if requested. */
  559. if (options.RunAsDaemon) {
  560. start_daemon(get_data_directory(&options));
  561. }
  562. /* Configure the log(s) */
  563. if (config_init_logs(&options)<0)
  564. return -1;
  565. /* Close the temporary log we used while starting up, if it isn't already
  566. * gone. */
  567. close_temp_logs();
  568. /* Set up our buckets */
  569. connection_bucket_init();
  570. stats_prev_global_read_bucket = global_read_bucket;
  571. /* Finish backgrounding the process */
  572. if(options.RunAsDaemon) {
  573. /* XXXX Can we delay this any more? */
  574. finish_daemon();
  575. }
  576. /* Write our pid to the pid file. If we do not have write permissions we
  577. * will log a warning */
  578. if(options.PidFile)
  579. write_pidfile(options.PidFile);
  580. return 0;
  581. }
  582. /** Called when we get a SIGHUP: reload configuration files and keys,
  583. * retry all connections, re-upload all descriptors, and so on. */
  584. static int do_hup(void) {
  585. char keydir[512];
  586. log_fn(LOG_NOTICE,"Received sighup. Reloading config.");
  587. has_completed_circuit=0;
  588. mark_logs_temp(); /* Close current logs once new logs are open. */
  589. /* first, reload config variables, in case they've changed */
  590. /* no need to provide argc/v, they've been cached inside init_from_config */
  591. if (init_from_config(0, NULL) < 0) {
  592. exit(1);
  593. }
  594. /* reload keys as needed for rendezvous services. */
  595. if (rend_service_load_keys()<0) {
  596. log_fn(LOG_ERR,"Error reloading rendezvous service keys");
  597. exit(1);
  598. }
  599. if(retry_all_listeners() < 0) {
  600. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  601. return -1;
  602. }
  603. if(authdir_mode()) {
  604. /* reload the approved-routers file */
  605. sprintf(keydir,"%s/approved-routers", get_data_directory(&options));
  606. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  607. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  608. log_fn(LOG_WARN, "Error reloading fingerprints. Continuing with old list.");
  609. }
  610. /* Since we aren't fetching a directory, we won't retry rendezvous points
  611. * when it gets in. Try again now. */
  612. rend_services_introduce();
  613. }
  614. /* Fetch a new directory. Even authdirservers do this. */
  615. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  616. if(server_mode()) {
  617. /* Restart cpuworker and dnsworker processes, so they get up-to-date
  618. * configuration options. */
  619. cpuworkers_rotate();
  620. if (exit_server_mode())
  621. dnsworkers_rotate();
  622. /* Rebuild fresh descriptor as needed. */
  623. router_rebuild_descriptor();
  624. sprintf(keydir,"%s/router.desc", get_data_directory(&options));
  625. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  626. if (write_str_to_file(keydir, router_get_my_descriptor())) {
  627. return -1;
  628. }
  629. }
  630. return 0;
  631. }
  632. /** Tor main loop. */
  633. static int do_main_loop(void) {
  634. int i;
  635. int timeout;
  636. int poll_result;
  637. /* Initialize the history structures. */
  638. rep_hist_init();
  639. /* Intialize the service cache. */
  640. rend_cache_init();
  641. /* load the private keys, if we're supposed to have them, and set up the
  642. * TLS context. */
  643. if (init_keys() < 0 || rend_service_load_keys() < 0) {
  644. log_fn(LOG_ERR,"Error initializing keys; exiting");
  645. return -1;
  646. }
  647. /* load the routers file */
  648. if(options.RouterFile) {
  649. routerlist_clear_trusted_directories();
  650. if (router_load_routerlist_from_file(options.RouterFile, 1) < 0) {
  651. log_fn(LOG_ERR,"Error loading router list.");
  652. return -1;
  653. }
  654. }
  655. if(authdir_mode()) {
  656. /* the directory is already here, run startup things */
  657. directory_has_arrived();
  658. }
  659. if(server_mode()) {
  660. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  661. cpu_init();
  662. }
  663. /* start up the necessary listeners based on which ports are non-zero. */
  664. if(retry_all_listeners() < 0) {
  665. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  666. return -1;
  667. }
  668. for(;;) {
  669. #ifdef MS_WINDOWS /* Do service stuff only on windows. */
  670. if (service_status.dwCurrentState != SERVICE_RUNNING) {
  671. return 0;
  672. }
  673. #else /* do signal stuff only on unix */
  674. if(please_shutdown) {
  675. if(shutting_down) { /* we've already been asked. do it now. */
  676. log(LOG_NOTICE,"Second sigint received; exiting now.");
  677. exit(0);
  678. } else {
  679. log(LOG_NOTICE,"Interrupt: will shut down in %d seconds. Interrupt again to exit now.", SHUTDOWN_WAIT_LENGTH);
  680. shutting_down = time(NULL) + SHUTDOWN_WAIT_LENGTH;
  681. }
  682. please_shutdown = 0;
  683. }
  684. if(please_dumpstats) {
  685. /* prefer to log it at INFO, but make sure we always see it */
  686. dumpstats(get_min_log_level()>LOG_INFO ? get_min_log_level() : LOG_INFO);
  687. please_dumpstats = 0;
  688. }
  689. if(please_reset) {
  690. do_hup();
  691. please_reset = 0;
  692. }
  693. if(please_reap_children) {
  694. while(waitpid(-1,NULL,WNOHANG)) ; /* keep reaping until no more zombies */
  695. please_reap_children = 0;
  696. }
  697. #endif /* signal stuff */
  698. timeout = prepare_for_poll();
  699. /* poll until we have an event, or the second ends */
  700. poll_result = tor_poll(poll_array, nfds, timeout);
  701. /* let catch() handle things like ^c, and otherwise don't worry about it */
  702. if(poll_result < 0) {
  703. /* let the program survive things like ^z */
  704. if(tor_socket_errno(-1) != EINTR) {
  705. log_fn(LOG_ERR,"poll failed: %s [%d]",
  706. tor_socket_strerror(tor_socket_errno(-1)),
  707. tor_socket_errno(-1));
  708. return -1;
  709. } else {
  710. log_fn(LOG_DEBUG,"poll interrupted.");
  711. }
  712. }
  713. /* do all the reads and errors first, so we can detect closed sockets */
  714. for(i=0;i<nfds;i++)
  715. conn_read(i); /* this also marks broken connections */
  716. /* then do the writes */
  717. for(i=0;i<nfds;i++)
  718. conn_write(i);
  719. /* any of the conns need to be closed now? */
  720. for(i=0;i<nfds;i++)
  721. conn_close_if_marked(i);
  722. /* refilling buckets and sending cells happens at the beginning of the
  723. * next iteration of the loop, inside prepare_for_poll()
  724. */
  725. }
  726. }
  727. /** Unix signal handler. */
  728. static void catch(int the_signal) {
  729. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  730. switch(the_signal) {
  731. // case SIGABRT:
  732. case SIGTERM:
  733. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  734. exit(0);
  735. case SIGINT:
  736. please_shutdown = 1;
  737. break;
  738. case SIGPIPE:
  739. log(LOG_NOTICE,"Caught sigpipe. Ignoring.");
  740. break;
  741. case SIGHUP:
  742. please_reset = 1;
  743. break;
  744. case SIGUSR1:
  745. please_dumpstats = 1;
  746. break;
  747. case SIGCHLD:
  748. please_reap_children = 1;
  749. break;
  750. default:
  751. log(LOG_WARN,"Caught signal %d that we can't handle??", the_signal);
  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,"Average bandwidth used: %d bytes/sec",
  802. (int) (stats_n_bytes_read/stats_n_seconds_uptime));
  803. rep_hist_dump_stats(now,severity);
  804. rend_service_dump_stats(severity);
  805. }
  806. /** Called before we make any calls to network-related functions.
  807. * (Some operating systems require their network libraries to be
  808. * initialized.) */
  809. int network_init(void)
  810. {
  811. #ifdef MS_WINDOWS
  812. /* This silly exercise is necessary before windows will allow gethostbyname to work.
  813. */
  814. WSADATA WSAData;
  815. int r;
  816. r = WSAStartup(0x101,&WSAData);
  817. if (r) {
  818. log_fn(LOG_WARN,"Error initializing windows network layer: code was %d",r);
  819. return -1;
  820. }
  821. /* XXXX We should call WSACleanup on exit, I think. */
  822. #endif
  823. return 0;
  824. }
  825. /** Called by exit() as we shut down the process.
  826. */
  827. void exit_function(void)
  828. {
  829. /* Remove our pid file. We don't care if there was an error when we
  830. * unlink, nothing we could do about it anyways. */
  831. if(options.PidFile)
  832. unlink(options.PidFile);
  833. #ifdef MS_WINDOWS
  834. WSACleanup();
  835. #endif
  836. }
  837. /** Main entry point for the Tor command-line client.
  838. */
  839. int tor_init(int argc, char *argv[]) {
  840. /* give it somewhere to log to initially */
  841. add_temp_log();
  842. log_fn(LOG_NOTICE,"Tor v%s. This is experimental software. Do not use it if you need anonymity.",VERSION);
  843. if (network_init()<0) {
  844. log_fn(LOG_ERR,"Error initializing network; exiting.");
  845. return -1;
  846. }
  847. atexit(exit_function);
  848. if (init_from_config(argc,argv) < 0)
  849. return -1;
  850. #ifndef MS_WINDOWS
  851. if(geteuid()==0)
  852. log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
  853. #endif
  854. if(exit_server_mode()) { /* only spawn dns handlers if we're a router */
  855. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  856. }
  857. if(proxy_mode()) {
  858. client_dns_init(); /* init the client dns cache */
  859. }
  860. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  861. {
  862. struct sigaction action;
  863. action.sa_flags = 0;
  864. sigemptyset(&action.sa_mask);
  865. action.sa_handler = catch;
  866. sigaction(SIGINT, &action, NULL); /* do a controlled slow shutdown */
  867. sigaction(SIGTERM, &action, NULL); /* to terminate now */
  868. sigaction(SIGPIPE, &action, NULL); /* otherwise sigpipe kills us */
  869. sigaction(SIGUSR1, &action, NULL); /* dump stats */
  870. sigaction(SIGHUP, &action, NULL); /* to reload config, retry conns, etc */
  871. sigaction(SIGCHLD, &action, NULL); /* handle dns/cpu workers that exit */
  872. }
  873. #endif /* signal stuff */
  874. crypto_global_init();
  875. crypto_seed_rng();
  876. return 0;
  877. }
  878. void tor_cleanup(void) {
  879. crypto_global_cleanup();
  880. }
  881. #ifdef MS_WINDOWS
  882. void nt_service_control(DWORD request)
  883. {
  884. switch (request) {
  885. case SERVICE_CONTROL_STOP:
  886. case SERVICE_CONTROL_SHUTDOWN:
  887. log(LOG_ERR, "Got stop/shutdown request; shutting down cleanly.");
  888. service_status.dwWin32ExitCode = 0;
  889. service_status.dwCurrentState = SERVICE_STOPPED;
  890. return;
  891. }
  892. SetServiceStatus(hStatus, &service_status);
  893. }
  894. void nt_service_body(int argc, char **argv)
  895. {
  896. int err;
  897. FILE *f;
  898. f = fopen("d:\\foo.txt", "w");
  899. fprintf(f, "POINT 1\n");
  900. fclose(f);
  901. service_status.dwServiceType = SERVICE_WIN32;
  902. service_status.dwCurrentState = SERVICE_START_PENDING;
  903. service_status.dwControlsAccepted =
  904. SERVICE_ACCEPT_STOP |
  905. SERVICE_ACCEPT_SHUTDOWN;
  906. service_status.dwWin32ExitCode = 0;
  907. service_status.dwServiceSpecificExitCode = 0;
  908. service_status.dwCheckPoint = 0;
  909. service_status.dwWaitHint = 0;
  910. hStatus = RegisterServiceCtrlHandler("Tor", (LPHANDLER_FUNCTION) nt_service_control);
  911. if (hStatus == 0) {
  912. // failed;
  913. return;
  914. }
  915. err = tor_init(argc, argv); // refactor this part out of tor_main and do_main_loop
  916. if (err) {
  917. // failed.
  918. service_status.dwCurrentState = SERVICE_STOPPED;
  919. service_status.dwWin32ExitCode = -1;
  920. SetServiceStatus(hStatus, &service_status);
  921. return;
  922. }
  923. service_status.dwCurrentState = SERVICE_RUNNING;
  924. SetServiceStatus(hStatus, &service_status);
  925. do_main_loop();
  926. tor_cleanup();
  927. return;
  928. }
  929. void nt_service_main(void)
  930. {
  931. SERVICE_TABLE_ENTRY table[2];
  932. table[0].lpServiceName = "Tor";
  933. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
  934. table[1].lpServiceName = NULL;
  935. table[1].lpServiceProc = NULL;
  936. if (!StartServiceCtrlDispatcher(table))
  937. printf("Error was %d\n",GetLastError());
  938. }
  939. #endif
  940. int tor_main(int argc, char *argv[]) {
  941. #ifdef MS_WINDOWS_SERVICE
  942. nt_service_main();
  943. return 0;
  944. #else
  945. if (tor_init(argc, argv)<0)
  946. return -1;
  947. do_main_loop();
  948. tor_cleanup();
  949. return -1;
  950. #endif
  951. }
  952. /*
  953. Local Variables:
  954. mode:c
  955. indent-tabs-mode:nil
  956. c-basic-offset:2
  957. End:
  958. */