main.c 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  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_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 >= 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(server_mode()) { /* connect to the appropriate routers */
  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 bw;
  353. bw = rep_hist_bandwidth_assess();
  354. router_set_advertised_bandwidth(bw);
  355. if(options.ClientOnly)
  356. return 0;
  357. if(!options.ORPort)
  358. return 0;
  359. /* XXX008 for now, you're only a server if you're a server */
  360. return server_mode();
  361. /* here, determine if we're reachable */
  362. if(0) { /* we've recently failed to reach our IP/ORPort from the outside */
  363. return 0;
  364. }
  365. if(bw < 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. /** Remember if we've advertised ourselves to the dirservers. */
  390. static int server_is_advertised=0;
  391. /** Return true iff we have published our descriptor lately.
  392. */
  393. int advertised_server_mode(void) {
  394. return server_is_advertised;
  395. }
  396. /** Return true iff we are trying to be a socks proxy. */
  397. int proxy_mode(void) {
  398. return (options.SocksPort != 0);
  399. }
  400. /** Perform regular maintenance tasks. This function gets run once per
  401. * second by prepare_for_poll.
  402. */
  403. static void run_scheduled_events(time_t now) {
  404. static long time_to_fetch_directory = 0;
  405. static time_t last_uploaded_services = 0;
  406. static time_t last_rotated_certificate = 0;
  407. int i;
  408. /** 0. See if we've been asked to shut down and our timeout has
  409. * expired. If so, exit now.
  410. */
  411. if(shutting_down && shutting_down <= now) {
  412. log(LOG_NOTICE,"Clean shutdown finished. Exiting.");
  413. tor_cleanup();
  414. exit(0);
  415. }
  416. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  417. * shut down and restart all cpuworkers, and update the directory if
  418. * necessary.
  419. */
  420. if (server_mode() && get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  421. log_fn(LOG_INFO,"Rotating onion key.");
  422. rotate_onion_key();
  423. cpuworkers_rotate();
  424. if (router_rebuild_descriptor()<0) {
  425. log_fn(LOG_WARN, "Couldn't rebuild router descriptor");
  426. }
  427. if(advertised_server_mode())
  428. router_upload_dir_desc_to_dirservers();
  429. }
  430. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  431. if (!last_rotated_certificate)
  432. last_rotated_certificate = now;
  433. /*XXXX008 we should remove the server_mode() check once OPs also use
  434. * identity keys (which they can't do until the known-router check in
  435. * connection_or.c is removed. */
  436. if (server_mode() && last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
  437. log_fn(LOG_INFO,"Rotating tls context.");
  438. if (tor_tls_context_new(get_identity_key(), 1, options.Nickname,
  439. MAX_SSL_KEY_LIFETIME) < 0) {
  440. log_fn(LOG_WARN, "Error reinitializing TLS context");
  441. }
  442. last_rotated_certificate = now;
  443. /* XXXX We should rotate TLS connections as well; this code doesn't change
  444. * XXXX them at all. */
  445. }
  446. /** 2. Every DirFetchPostPeriod seconds, we get a new directory and upload
  447. * our descriptor (if we've passed our internal checks). */
  448. if(time_to_fetch_directory < now) {
  449. if(decide_if_publishable_server(now)) {
  450. server_is_advertised = 1;
  451. router_rebuild_descriptor();
  452. router_upload_dir_desc_to_dirservers();
  453. } else {
  454. server_is_advertised = 0;
  455. }
  456. /* purge obsolete entries */
  457. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  458. if(authdir_mode()) {
  459. /* We're a directory; dump any old descriptors. */
  460. dirserv_remove_old_servers(ROUTER_MAX_AGE);
  461. }
  462. if(server_mode()) {
  463. /* dirservers try to reconnect, in case connections have failed;
  464. * and normal servers try to reconnect to dirservers */
  465. router_retry_connections();
  466. }
  467. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  468. /* Force an upload of our rend descriptors every DirFetchPostPeriod seconds. */
  469. rend_services_upload(1);
  470. last_uploaded_services = now;
  471. rend_cache_clean(); /* should this go elsewhere? */
  472. time_to_fetch_directory = now + options.DirFetchPostPeriod;
  473. }
  474. /** 3a. Every second, we examine pending circuits and prune the
  475. * ones which have been pending for more than a few seconds.
  476. * We do this before step 3, so it can try building more if
  477. * it's not comfortable with the number of available circuits.
  478. */
  479. circuit_expire_building(now);
  480. /** 3b. Also look at pending streams and prune the ones that 'began'
  481. * a long time ago but haven't gotten a 'connected' yet.
  482. * Do this before step 3, so we can put them back into pending
  483. * state to be picked up by the new circuit.
  484. */
  485. connection_ap_expire_beginning();
  486. /** 3c. And expire connections that we've held open for too long.
  487. */
  488. connection_expire_held_open();
  489. /** 4. Every second, we try a new circuit if there are no valid
  490. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  491. * that became dirty more than NewCircuitPeriod seconds ago,
  492. * and we make a new circ if there are no clean circuits.
  493. */
  494. if(has_fetched_directory)
  495. circuit_build_needed_circs(now);
  496. /** 5. We do housekeeping for each connection... */
  497. for(i=0;i<nfds;i++) {
  498. run_connection_housekeeping(i, now);
  499. }
  500. /** 6. And remove any marked circuits... */
  501. circuit_close_all_marked();
  502. /** 7. And upload service descriptors for any services whose intro points
  503. * have changed in the last second. */
  504. if (last_uploaded_services < now-5) {
  505. rend_services_upload(0);
  506. last_uploaded_services = now;
  507. }
  508. /** 8. and blow away any connections that need to die. have to do this now,
  509. * because if we marked a conn for close and left its socket -1, then
  510. * we'll pass it to poll/select and bad things will happen.
  511. */
  512. for(i=0;i<nfds;i++)
  513. conn_close_if_marked(i);
  514. }
  515. /** Called every time we're about to call tor_poll. Increments statistics,
  516. * and adjusts token buckets. Returns the number of milliseconds to use for
  517. * the poll() timeout.
  518. */
  519. static int prepare_for_poll(void) {
  520. static long current_second = 0; /* from previous calls to gettimeofday */
  521. connection_t *conn;
  522. struct timeval now;
  523. int i;
  524. tor_gettimeofday(&now);
  525. /* Check how much bandwidth we've consumed, and increment the token
  526. * buckets. */
  527. stats_n_bytes_read += stats_prev_global_read_bucket - global_read_bucket;
  528. connection_bucket_refill(&now);
  529. stats_prev_global_read_bucket = global_read_bucket;
  530. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  531. if(current_second)
  532. stats_n_seconds_uptime += (now.tv_sec - current_second);
  533. assert_all_pending_dns_resolves_ok();
  534. run_scheduled_events(now.tv_sec);
  535. assert_all_pending_dns_resolves_ok();
  536. current_second = now.tv_sec; /* remember which second it is, for next time */
  537. }
  538. for(i=0;i<nfds;i++) {
  539. conn = connection_array[i];
  540. if(connection_has_pending_tls_data(conn) &&
  541. connection_is_reading(conn)) {
  542. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  543. return 0; /* has pending bytes to read; don't let poll wait. */
  544. }
  545. }
  546. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  547. }
  548. /** Configure the Tor process from the command line arguments and from the
  549. * configuration file.
  550. */
  551. static int init_from_config(int argc, char **argv) {
  552. /* read the configuration file. */
  553. if(getconfig(argc,argv,&options)) {
  554. log_fn(LOG_ERR,"Reading config failed. For usage, try -h.");
  555. return -1;
  556. }
  557. /* Setuid/setgid as appropriate */
  558. if(options.User || options.Group) {
  559. if(switch_id(options.User, options.Group) != 0) {
  560. return -1;
  561. }
  562. }
  563. /* Ensure data directory is private; create if possible. */
  564. if (get_data_directory(&options) &&
  565. check_private_dir(get_data_directory(&options), 1) != 0) {
  566. log_fn(LOG_ERR, "Couldn't access/create private data directory %s",
  567. get_data_directory(&options));
  568. return -1;
  569. }
  570. /* Start backgrounding the process, if requested. */
  571. if (options.RunAsDaemon) {
  572. start_daemon(get_data_directory(&options));
  573. }
  574. /* Configure the log(s) */
  575. if (config_init_logs(&options)<0)
  576. return -1;
  577. /* Close the temporary log we used while starting up, if it isn't already
  578. * gone. */
  579. close_temp_logs();
  580. /* Set up our buckets */
  581. connection_bucket_init();
  582. stats_prev_global_read_bucket = global_read_bucket;
  583. /* Finish backgrounding the process */
  584. if(options.RunAsDaemon) {
  585. /* XXXX Can we delay this any more? */
  586. finish_daemon();
  587. }
  588. /* Write our pid to the pid file. If we do not have write permissions we
  589. * will log a warning */
  590. if(options.PidFile)
  591. write_pidfile(options.PidFile);
  592. return 0;
  593. }
  594. /** Called when we get a SIGHUP: reload configuration files and keys,
  595. * retry all connections, re-upload all descriptors, and so on. */
  596. static int do_hup(void) {
  597. char keydir[512];
  598. log_fn(LOG_NOTICE,"Received sighup. Reloading config.");
  599. has_completed_circuit=0;
  600. mark_logs_temp(); /* Close current logs once new logs are open. */
  601. /* first, reload config variables, in case they've changed */
  602. /* no need to provide argc/v, they've been cached inside init_from_config */
  603. if (init_from_config(0, NULL) < 0) {
  604. tor_cleanup();
  605. exit(1);
  606. }
  607. /* reload keys as needed for rendezvous services. */
  608. if (rend_service_load_keys()<0) {
  609. log_fn(LOG_ERR,"Error reloading rendezvous service keys");
  610. tor_cleanup();
  611. exit(1);
  612. }
  613. if(retry_all_listeners() < 0) {
  614. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  615. return -1;
  616. }
  617. if(authdir_mode()) {
  618. /* reload the approved-routers file */
  619. sprintf(keydir,"%s/approved-routers", get_data_directory(&options));
  620. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  621. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  622. log_fn(LOG_WARN, "Error reloading fingerprints. Continuing with old list.");
  623. }
  624. /* Since we aren't fetching a directory, we won't retry rendezvous points
  625. * when it gets in. Try again now. */
  626. rend_services_introduce();
  627. }
  628. /* Fetch a new directory. Even authdirservers do this. */
  629. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  630. if(server_mode()) {
  631. /* Restart cpuworker and dnsworker processes, so they get up-to-date
  632. * configuration options. */
  633. cpuworkers_rotate();
  634. if (server_mode())
  635. dnsworkers_rotate();
  636. /* Rebuild fresh descriptor as needed. */
  637. router_rebuild_descriptor();
  638. sprintf(keydir,"%s/router.desc", get_data_directory(&options));
  639. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  640. if (write_str_to_file(keydir, router_get_my_descriptor())) {
  641. return -1;
  642. }
  643. }
  644. return 0;
  645. }
  646. /** Tor main loop. */
  647. static int do_main_loop(void) {
  648. int i;
  649. int timeout;
  650. int poll_result;
  651. /* Initialize the history structures. */
  652. rep_hist_init();
  653. /* Intialize the service cache. */
  654. rend_cache_init();
  655. /* load the private keys, if we're supposed to have them, and set up the
  656. * TLS context. */
  657. if (init_keys() < 0 || rend_service_load_keys() < 0) {
  658. log_fn(LOG_ERR,"Error initializing keys; exiting");
  659. return -1;
  660. }
  661. /* load the routers file */
  662. if(options.RouterFile) {
  663. routerlist_clear_trusted_directories();
  664. if (router_load_routerlist_from_file(options.RouterFile, 1) < 0) {
  665. log_fn(LOG_ERR,"Error loading router list.");
  666. return -1;
  667. }
  668. }
  669. if(authdir_mode()) {
  670. /* the directory is already here, run startup things */
  671. directory_has_arrived();
  672. }
  673. if(server_mode()) {
  674. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  675. cpu_init();
  676. }
  677. /* start up the necessary listeners based on which ports are non-zero. */
  678. if(retry_all_listeners() < 0) {
  679. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  680. return -1;
  681. }
  682. for(;;) {
  683. #ifdef MS_WINDOWS_SERVICE /* Do service stuff only on windows. */
  684. if (service_status.dwCurrentState != SERVICE_RUNNING) {
  685. return 0;
  686. }
  687. #endif
  688. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  689. if(please_shutdown) {
  690. if(!server_mode()) { /* do it now */
  691. log(LOG_NOTICE,"Interrupt: exiting cleanly.");
  692. tor_cleanup();
  693. exit(0);
  694. }
  695. if(shutting_down) { /* we've already been asked. do it now. */
  696. log(LOG_NOTICE,"Second sigint received; exiting now.");
  697. tor_cleanup();
  698. exit(0);
  699. } else {
  700. log(LOG_NOTICE,"Interrupt: will shut down in %d seconds. Interrupt again to exit now.", SHUTDOWN_WAIT_LENGTH);
  701. shutting_down = time(NULL) + SHUTDOWN_WAIT_LENGTH;
  702. }
  703. please_shutdown = 0;
  704. }
  705. if(please_dumpstats) {
  706. /* prefer to log it at INFO, but make sure we always see it */
  707. dumpstats(get_min_log_level()>LOG_INFO ? get_min_log_level() : LOG_INFO);
  708. please_dumpstats = 0;
  709. }
  710. if(please_reset) {
  711. do_hup();
  712. please_reset = 0;
  713. }
  714. if(please_reap_children) {
  715. while(waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more zombies */
  716. please_reap_children = 0;
  717. }
  718. #endif /* signal stuff */
  719. timeout = prepare_for_poll();
  720. /* poll until we have an event, or the second ends */
  721. poll_result = tor_poll(poll_array, nfds, timeout);
  722. /* let catch() handle things like ^c, and otherwise don't worry about it */
  723. if(poll_result < 0) {
  724. /* let the program survive things like ^z */
  725. if(tor_socket_errno(-1) != EINTR) {
  726. log_fn(LOG_ERR,"poll failed: %s [%d]",
  727. tor_socket_strerror(tor_socket_errno(-1)),
  728. tor_socket_errno(-1));
  729. return -1;
  730. } else {
  731. log_fn(LOG_DEBUG,"poll interrupted.");
  732. }
  733. }
  734. /* do all the reads and errors first, so we can detect closed sockets */
  735. for(i=0;i<nfds;i++)
  736. conn_read(i); /* this also marks broken connections */
  737. /* then do the writes */
  738. for(i=0;i<nfds;i++)
  739. conn_write(i);
  740. /* any of the conns need to be closed now? */
  741. for(i=0;i<nfds;i++)
  742. conn_close_if_marked(i);
  743. /* refilling buckets and sending cells happens at the beginning of the
  744. * next iteration of the loop, inside prepare_for_poll()
  745. */
  746. }
  747. }
  748. /** Unix signal handler. */
  749. static void catch(int the_signal) {
  750. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  751. switch(the_signal) {
  752. // case SIGABRT:
  753. case SIGTERM:
  754. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  755. tor_cleanup();
  756. exit(0);
  757. case SIGINT:
  758. please_shutdown = 1;
  759. break;
  760. case SIGPIPE:
  761. log(LOG_NOTICE,"Caught sigpipe. Ignoring.");
  762. break;
  763. case SIGHUP:
  764. please_reset = 1;
  765. break;
  766. case SIGUSR1:
  767. please_dumpstats = 1;
  768. break;
  769. case SIGCHLD:
  770. please_reap_children = 1;
  771. break;
  772. default:
  773. log(LOG_WARN,"Caught signal %d that we can't handle??", the_signal);
  774. }
  775. #endif /* signal stuff */
  776. }
  777. /** Write all statistics to the log, with log level 'severity'. Called
  778. * in response to a SIGUSR1. */
  779. static void dumpstats(int severity) {
  780. int i;
  781. connection_t *conn;
  782. time_t now = time(NULL);
  783. log(severity, "Dumping stats:");
  784. for(i=0;i<nfds;i++) {
  785. conn = connection_array[i];
  786. log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  787. i, conn->s, conn->type, CONN_TYPE_TO_STRING(conn->type),
  788. conn->state, conn_state_to_string[conn->type][conn->state], (int)(now - conn->timestamp_created));
  789. if(!connection_is_listener(conn)) {
  790. log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
  791. log(severity,"Conn %d: %d bytes waiting on inbuf (last read %d secs ago)",i,
  792. (int)buf_datalen(conn->inbuf),
  793. (int)(now - conn->timestamp_lastread));
  794. log(severity,"Conn %d: %d bytes waiting on outbuf (last written %d secs ago)",i,
  795. (int)buf_datalen(conn->outbuf), (int)(now - conn->timestamp_lastwritten));
  796. }
  797. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
  798. }
  799. log(severity,
  800. "Cells processed: %10lu padding\n"
  801. " %10lu create\n"
  802. " %10lu created\n"
  803. " %10lu relay\n"
  804. " (%10lu relayed)\n"
  805. " (%10lu delivered)\n"
  806. " %10lu destroy",
  807. stats_n_padding_cells_processed,
  808. stats_n_create_cells_processed,
  809. stats_n_created_cells_processed,
  810. stats_n_relay_cells_processed,
  811. stats_n_relay_cells_relayed,
  812. stats_n_relay_cells_delivered,
  813. stats_n_destroy_cells_processed);
  814. if (stats_n_data_cells_packaged)
  815. log(severity,"Average packaged cell fullness: %2.3f%%",
  816. 100*(((double)stats_n_data_bytes_packaged) /
  817. (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  818. if (stats_n_data_cells_received)
  819. log(severity,"Average delivered cell fullness: %2.3f%%",
  820. 100*(((double)stats_n_data_bytes_received) /
  821. (stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  822. if (stats_n_seconds_uptime)
  823. log(severity,"Average bandwidth used: %llu/%ld = %d bytes/sec",
  824. stats_n_bytes_read, stats_n_seconds_uptime,
  825. (int) (stats_n_bytes_read/stats_n_seconds_uptime));
  826. rep_hist_dump_stats(now,severity);
  827. rend_service_dump_stats(severity);
  828. }
  829. /** Called before we make any calls to network-related functions.
  830. * (Some operating systems require their network libraries to be
  831. * initialized.) */
  832. static int network_init(void)
  833. {
  834. #ifdef MS_WINDOWS
  835. /* This silly exercise is necessary before windows will allow gethostbyname to work.
  836. */
  837. WSADATA WSAData;
  838. int r;
  839. r = WSAStartup(0x101,&WSAData);
  840. if (r) {
  841. log_fn(LOG_WARN,"Error initializing windows network layer: code was %d",r);
  842. return -1;
  843. }
  844. /* XXXX We should call WSACleanup on exit, I think. */
  845. #endif
  846. return 0;
  847. }
  848. /** Called by exit() as we shut down the process.
  849. */
  850. void exit_function(void)
  851. {
  852. /* XXX if we ever daemonize, this gets called immediately */
  853. #ifdef MS_WINDOWS
  854. WSACleanup();
  855. #endif
  856. }
  857. /** Main entry point for the Tor command-line client.
  858. */
  859. static int tor_init(int argc, char *argv[]) {
  860. /* give it somewhere to log to initially */
  861. add_temp_log();
  862. log_fn(LOG_NOTICE,"Tor v%s. This is experimental software. Do not use it if you need anonymity.",VERSION);
  863. if (network_init()<0) {
  864. log_fn(LOG_ERR,"Error initializing network; exiting.");
  865. return -1;
  866. }
  867. atexit(exit_function);
  868. if (init_from_config(argc,argv) < 0)
  869. return -1;
  870. #ifndef MS_WINDOWS
  871. if(geteuid()==0)
  872. log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
  873. #endif
  874. if(server_mode()) { /* only spawn dns handlers if we're a router */
  875. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  876. }
  877. if(proxy_mode()) {
  878. client_dns_init(); /* init the client dns cache */
  879. }
  880. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  881. {
  882. struct sigaction action;
  883. action.sa_flags = 0;
  884. sigemptyset(&action.sa_mask);
  885. action.sa_handler = catch;
  886. sigaction(SIGINT, &action, NULL); /* do a controlled slow shutdown */
  887. sigaction(SIGTERM, &action, NULL); /* to terminate now */
  888. sigaction(SIGPIPE, &action, NULL); /* otherwise sigpipe kills us */
  889. sigaction(SIGUSR1, &action, NULL); /* dump stats */
  890. sigaction(SIGHUP, &action, NULL); /* to reload config, retry conns, etc */
  891. sigaction(SIGCHLD, &action, NULL); /* handle dns/cpu workers that exit */
  892. }
  893. #endif /* signal stuff */
  894. crypto_global_init();
  895. crypto_seed_rng();
  896. return 0;
  897. }
  898. /** Do whatever cleanup is necessary before shutting Tor down. */
  899. void tor_cleanup(void) {
  900. /* Remove our pid file. We don't care if there was an error when we
  901. * unlink, nothing we could do about it anyways. */
  902. if(options.PidFile)
  903. unlink(options.PidFile);
  904. crypto_global_cleanup();
  905. }
  906. #ifdef MS_WINDOWS_SERVICE
  907. void nt_service_control(DWORD request)
  908. {
  909. switch (request) {
  910. case SERVICE_CONTROL_STOP:
  911. case SERVICE_CONTROL_SHUTDOWN:
  912. log(LOG_ERR, "Got stop/shutdown request; shutting down cleanly.");
  913. service_status.dwWin32ExitCode = 0;
  914. service_status.dwCurrentState = SERVICE_STOPPED;
  915. return;
  916. }
  917. SetServiceStatus(hStatus, &service_status);
  918. }
  919. void nt_service_body(int argc, char **argv)
  920. {
  921. int err;
  922. FILE *f;
  923. f = fopen("d:\\foo.txt", "w");
  924. fprintf(f, "POINT 1\n");
  925. fclose(f);
  926. service_status.dwServiceType = SERVICE_WIN32;
  927. service_status.dwCurrentState = SERVICE_START_PENDING;
  928. service_status.dwControlsAccepted =
  929. SERVICE_ACCEPT_STOP |
  930. SERVICE_ACCEPT_SHUTDOWN;
  931. service_status.dwWin32ExitCode = 0;
  932. service_status.dwServiceSpecificExitCode = 0;
  933. service_status.dwCheckPoint = 0;
  934. service_status.dwWaitHint = 0;
  935. hStatus = RegisterServiceCtrlHandler("Tor", (LPHANDLER_FUNCTION) nt_service_control);
  936. if (hStatus == 0) {
  937. // failed;
  938. return;
  939. }
  940. err = tor_init(argc, argv); // refactor this part out of tor_main and do_main_loop
  941. if (err) {
  942. // failed.
  943. service_status.dwCurrentState = SERVICE_STOPPED;
  944. service_status.dwWin32ExitCode = -1;
  945. SetServiceStatus(hStatus, &service_status);
  946. return;
  947. }
  948. service_status.dwCurrentState = SERVICE_RUNNING;
  949. SetServiceStatus(hStatus, &service_status);
  950. do_main_loop();
  951. tor_cleanup();
  952. return;
  953. }
  954. void nt_service_main(void)
  955. {
  956. SERVICE_TABLE_ENTRY table[2];
  957. table[0].lpServiceName = "Tor";
  958. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
  959. table[1].lpServiceName = NULL;
  960. table[1].lpServiceProc = NULL;
  961. if (!StartServiceCtrlDispatcher(table))
  962. printf("Error was %d\n",GetLastError());
  963. }
  964. #endif
  965. int tor_main(int argc, char *argv[]) {
  966. #ifdef MS_WINDOWS_SERVICE
  967. nt_service_main();
  968. return 0;
  969. #else
  970. if (tor_init(argc, argv)<0)
  971. return -1;
  972. do_main_loop();
  973. tor_cleanup();
  974. return -1;
  975. #endif
  976. }
  977. /*
  978. Local Variables:
  979. mode:c
  980. indent-tabs-mode:nil
  981. c-basic-offset:2
  982. End:
  983. */