main.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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. #endif /* signal stuff */
  36. /** We set this to 1 when we've fetched a dir, to know whether to complain
  37. * yet about unrecognized nicknames in entrynodes, exitnodes, etc.
  38. * Also, we don't try building circuits unless this is 1. */
  39. int has_fetched_directory=0;
  40. /** We set this to 1 when we've opened a circuit, so we can print a log
  41. * entry to inform the user that Tor is working. */
  42. int has_completed_circuit=0;
  43. #ifdef MS_WINDOWS
  44. SERVICE_STATUS service_status;
  45. SERVICE_STATUS_HANDLE hStatus;
  46. #endif
  47. /********* END VARIABLES ************/
  48. /****************************************************************************
  49. *
  50. * This section contains accessors and other methods on the connection_array
  51. * and poll_array variables (which are global within this file and unavailable
  52. * outside it).
  53. *
  54. ****************************************************************************/
  55. /** Add <b>conn</b> to the array of connections that we can poll on. The
  56. * connection's socket must be set; the connection starts out
  57. * non-reading and non-writing.
  58. */
  59. int connection_add(connection_t *conn) {
  60. tor_assert(conn);
  61. tor_assert(conn->s >= 0);
  62. if(nfds >= options.MaxConn-1) {
  63. log_fn(LOG_WARN,"failing because nfds is too high.");
  64. return -1;
  65. }
  66. tor_assert(conn->poll_index == -1); /* can only connection_add once */
  67. conn->poll_index = nfds;
  68. connection_array[nfds] = conn;
  69. poll_array[nfds].fd = conn->s;
  70. /* zero these out here, because otherwise we'll inherit values from the previously freed one */
  71. poll_array[nfds].events = 0;
  72. poll_array[nfds].revents = 0;
  73. nfds++;
  74. log_fn(LOG_INFO,"new conn type %s, socket %d, nfds %d.",
  75. CONN_TYPE_TO_STRING(conn->type), conn->s, nfds);
  76. return 0;
  77. }
  78. /** Remove the connection from the global list, and remove the
  79. * corresponding poll entry. Calling this function will shift the last
  80. * connection (if any) into the position occupied by conn.
  81. */
  82. int connection_remove(connection_t *conn) {
  83. int current_index;
  84. tor_assert(conn);
  85. tor_assert(nfds>0);
  86. log_fn(LOG_INFO,"removing socket %d (type %s), nfds now %d",
  87. conn->s, CONN_TYPE_TO_STRING(conn->type), nfds-1);
  88. tor_assert(conn->poll_index >= 0);
  89. current_index = conn->poll_index;
  90. if(current_index == nfds-1) { /* this is the end */
  91. nfds--;
  92. return 0;
  93. }
  94. /* replace this one with the one at the end */
  95. nfds--;
  96. poll_array[current_index].fd = poll_array[nfds].fd;
  97. poll_array[current_index].events = poll_array[nfds].events;
  98. poll_array[current_index].revents = poll_array[nfds].revents;
  99. connection_array[current_index] = connection_array[nfds];
  100. connection_array[current_index]->poll_index = current_index;
  101. return 0;
  102. }
  103. /** Return true iff conn is in the current poll array. */
  104. int connection_in_array(connection_t *conn) {
  105. int i;
  106. for (i=0; i<nfds; ++i) {
  107. if (conn==connection_array[i])
  108. return 1;
  109. }
  110. return 0;
  111. }
  112. /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
  113. * to the length of the array. <b>*array</b> and <b>*n</b> must not
  114. * be modified.
  115. */
  116. void get_connection_array(connection_t ***array, int *n) {
  117. *array = connection_array;
  118. *n = nfds;
  119. }
  120. /** Set the event mask on <b>conn</b> to <b>events</b>. (The form of
  121. * the event mask is as for poll().)
  122. */
  123. void connection_watch_events(connection_t *conn, short events) {
  124. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  125. poll_array[conn->poll_index].events = events;
  126. }
  127. /** Return true iff <b>conn</b> is listening for read events. */
  128. int connection_is_reading(connection_t *conn) {
  129. tor_assert(conn && conn->poll_index >= 0);
  130. return poll_array[conn->poll_index].events & POLLIN;
  131. }
  132. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  133. void connection_stop_reading(connection_t *conn) {
  134. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  135. log(LOG_DEBUG,"connection_stop_reading() called.");
  136. if(poll_array[conn->poll_index].events & POLLIN)
  137. poll_array[conn->poll_index].events -= POLLIN;
  138. }
  139. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  140. void connection_start_reading(connection_t *conn) {
  141. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  142. poll_array[conn->poll_index].events |= POLLIN;
  143. }
  144. /** Return true iff <b>conn</b> is listening for write events. */
  145. int connection_is_writing(connection_t *conn) {
  146. return poll_array[conn->poll_index].events & POLLOUT;
  147. }
  148. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  149. void connection_stop_writing(connection_t *conn) {
  150. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  151. if(poll_array[conn->poll_index].events & POLLOUT)
  152. poll_array[conn->poll_index].events -= POLLOUT;
  153. }
  154. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  155. void connection_start_writing(connection_t *conn) {
  156. tor_assert(conn && conn->poll_index >= 0 && conn->poll_index < nfds);
  157. poll_array[conn->poll_index].events |= POLLOUT;
  158. }
  159. /** Called when the connection at connection_array[i] has a read event,
  160. * or it has pending tls data waiting to be read: checks for validity,
  161. * catches numerous errors, and dispatches to connection_handle_read.
  162. */
  163. static void conn_read(int i) {
  164. connection_t *conn = connection_array[i];
  165. if (conn->marked_for_close)
  166. return;
  167. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
  168. * discussion of POLLIN vs POLLHUP */
  169. if(!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
  170. if(!connection_is_reading(conn) ||
  171. !connection_has_pending_tls_data(conn))
  172. return; /* this conn should not read */
  173. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  174. assert_connection_ok(conn, time(NULL));
  175. assert_all_pending_dns_resolves_ok();
  176. if(
  177. /* XXX does POLLHUP also mean it's definitely broken? */
  178. #ifdef MS_WINDOWS
  179. (poll_array[i].revents & POLLERR) ||
  180. #endif
  181. connection_handle_read(conn) < 0) {
  182. if (!conn->marked_for_close) {
  183. /* this connection is broken. remove it */
  184. log_fn(LOG_WARN,"Unhandled error on read for %s connection (fd %d); removing",
  185. CONN_TYPE_TO_STRING(conn->type), conn->s);
  186. connection_mark_for_close(conn);
  187. }
  188. }
  189. assert_connection_ok(conn, time(NULL));
  190. assert_all_pending_dns_resolves_ok();
  191. }
  192. /** Called when the connection at connection_array[i] has a write event:
  193. * checks for validity, catches numerous errors, and dispatches to
  194. * connection_handle_write.
  195. */
  196. static void conn_write(int i) {
  197. connection_t *conn;
  198. if(!(poll_array[i].revents & POLLOUT))
  199. return; /* this conn doesn't want to write */
  200. conn = connection_array[i];
  201. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  202. if (conn->marked_for_close)
  203. return;
  204. assert_connection_ok(conn, time(NULL));
  205. assert_all_pending_dns_resolves_ok();
  206. if (connection_handle_write(conn) < 0) {
  207. if (!conn->marked_for_close) {
  208. /* this connection is broken. remove it. */
  209. log_fn(LOG_WARN,"Unhandled error on read for %s connection (fd %d); removing",
  210. CONN_TYPE_TO_STRING(conn->type), conn->s);
  211. conn->has_sent_end = 1; /* otherwise we cry wolf about duplicate close */
  212. /* XXX do we need a close-immediate here, so we don't try to flush? */
  213. connection_mark_for_close(conn);
  214. }
  215. }
  216. assert_connection_ok(conn, time(NULL));
  217. assert_all_pending_dns_resolves_ok();
  218. }
  219. /** If the connection at connection_array[i] is marked for close, then:
  220. * - If it has data that it wants to flush, try to flush it.
  221. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  222. * true, then leave the connection open and return.
  223. * - Otherwise, remove the connection from connection_array and from
  224. * all other lists, close it, and free it.
  225. * If we remove the connection, then call conn_closed_if_marked at the new
  226. * connection at position i.
  227. */
  228. static void conn_close_if_marked(int i) {
  229. connection_t *conn;
  230. int retval;
  231. conn = connection_array[i];
  232. assert_connection_ok(conn, time(NULL));
  233. assert_all_pending_dns_resolves_ok();
  234. if(!conn->marked_for_close)
  235. return; /* nothing to see here, move along */
  236. log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
  237. if(conn->s >= 0 && connection_wants_to_flush(conn)) {
  238. /* -1 means it's an incomplete edge connection, or that the socket
  239. * has already been closed as unflushable. */
  240. if(!conn->hold_open_until_flushed)
  241. log_fn(LOG_WARN,
  242. "Conn (fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
  243. "(Marked at %s:%d)",
  244. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  245. conn->outbuf_flushlen, conn->marked_for_close_file, conn->marked_for_close);
  246. if(connection_speaks_cells(conn)) {
  247. if(conn->state == OR_CONN_STATE_OPEN) {
  248. retval = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  249. } else
  250. retval = -1; /* never flush non-open broken tls connections */
  251. } else {
  252. retval = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  253. }
  254. if(retval >= 0 &&
  255. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  256. log_fn(LOG_INFO,"Holding conn (fd %d) open for more flushing.",conn->s);
  257. /* XXX should we reset timestamp_lastwritten here? */
  258. return;
  259. }
  260. if(connection_wants_to_flush(conn)) {
  261. log_fn(LOG_WARN,"Conn (fd %d, type %s, state %d) still wants to flush. Losing %d bytes! (Marked at %s:%d)",
  262. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  263. (int)buf_datalen(conn->outbuf), conn->marked_for_close_file,
  264. conn->marked_for_close);
  265. }
  266. }
  267. /* if it's an edge conn, remove it from the list
  268. * of conn's on this circuit. If it's not on an edge,
  269. * flush and send destroys for all circuits on this conn
  270. */
  271. circuit_about_to_close_connection(conn);
  272. connection_about_to_close_connection(conn);
  273. connection_remove(conn);
  274. if(conn->type == CONN_TYPE_EXIT) {
  275. assert_connection_edge_not_dns_pending(conn);
  276. }
  277. connection_free(conn);
  278. if(i<nfds) { /* we just replaced the one at i with a new one.
  279. process it too. */
  280. conn_close_if_marked(i);
  281. }
  282. }
  283. /** This function is called whenever we successfully pull down a directory */
  284. void directory_has_arrived(void) {
  285. log_fn(LOG_INFO, "A directory has arrived.");
  286. has_fetched_directory=1;
  287. if(options.ORPort) { /* connect to them all */
  288. router_retry_connections();
  289. }
  290. }
  291. /** Perform regular maintenance tasks for a single connection. This
  292. * function gets run once per second per connection by run_housekeeping.
  293. */
  294. static void run_connection_housekeeping(int i, time_t now) {
  295. cell_t cell;
  296. connection_t *conn = connection_array[i];
  297. /* Expire any directory connections that haven't sent anything for 5 min */
  298. if(conn->type == CONN_TYPE_DIR &&
  299. !conn->marked_for_close &&
  300. conn->timestamp_lastwritten + 5*60 < now) {
  301. log_fn(LOG_WARN,"Expiring wedged directory conn (fd %d, purpose %d)", conn->s, conn->purpose);
  302. if (connection_wants_to_flush(conn)) {
  303. if(flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen) < 0) {
  304. log_fn(LOG_WARN,"flushing expired directory conn failed.");
  305. connection_close_immediate(conn);
  306. connection_mark_for_close(conn);
  307. /* */
  308. } else {
  309. /* XXXX Does this next part make sense, really? */
  310. connection_mark_for_close(conn);
  311. conn->hold_open_until_flushed = 1; /* give it a last chance */
  312. }
  313. } else {
  314. connection_mark_for_close(conn);
  315. }
  316. return;
  317. }
  318. /* check connections to see whether we should send a keepalive, expire, or wait */
  319. if(!connection_speaks_cells(conn))
  320. return;
  321. /* If we haven't written to an OR connection for a while, then either nuke
  322. the connection or send a keepalive, depending. */
  323. if(now >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
  324. if((!options.ORPort && !circuit_get_by_conn(conn)) ||
  325. (!connection_state_is_open(conn))) {
  326. /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
  327. log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
  328. i,conn->address, conn->port);
  329. /* flush anything waiting, e.g. a destroy for a just-expired circ */
  330. connection_mark_for_close(conn);
  331. conn->hold_open_until_flushed = 1;
  332. } else {
  333. /* either a full router, or we've got a circuit. send a padding cell. */
  334. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  335. conn->address, conn->port);
  336. memset(&cell,0,sizeof(cell_t));
  337. cell.command = CELL_PADDING;
  338. connection_or_write_cell_to_buf(&cell, conn);
  339. }
  340. }
  341. }
  342. /** Perform regular maintenance tasks. This function gets run once per
  343. * second by prepare_for_poll.
  344. */
  345. static void run_scheduled_events(time_t now) {
  346. static long time_to_fetch_directory = 0;
  347. static time_t last_uploaded_services = 0;
  348. static time_t last_rotated_certificate = 0;
  349. int i;
  350. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  351. * shut down and restart all cpuworkers, and update the directory if
  352. * necessary.
  353. */
  354. if (options.ORPort && get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  355. log_fn(LOG_INFO,"Rotating onion key.");
  356. rotate_onion_key();
  357. cpuworkers_rotate();
  358. if (router_rebuild_descriptor()<0) {
  359. log_fn(LOG_WARN, "Couldn't rebuild router descriptor");
  360. }
  361. router_upload_dir_desc_to_dirservers();
  362. }
  363. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  364. if (!last_rotated_certificate)
  365. last_rotated_certificate = now;
  366. if (options.ORPort && last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
  367. log_fn(LOG_INFO,"Rotating tls context.");
  368. if (tor_tls_context_new(get_identity_key(), 1, options.Nickname,
  369. MAX_SSL_KEY_LIFETIME) < 0) {
  370. log_fn(LOG_WARN, "Error reinitializing TLS context");
  371. }
  372. last_rotated_certificate = now;
  373. /* XXXX We should rotate TLS connections as well; this code doesn't change
  374. * XXXX them at all. */
  375. }
  376. /** 1c. Every DirFetchPostPeriod seconds, we get a new directory and upload
  377. * our descriptor (if any). */
  378. if(time_to_fetch_directory < now) {
  379. /* it's time to fetch a new directory and/or post our descriptor */
  380. if(options.ORPort) {
  381. router_rebuild_descriptor();
  382. router_upload_dir_desc_to_dirservers();
  383. }
  384. routerlist_remove_old_routers(); /* purge obsolete entries */
  385. if(options.AuthoritativeDir) {
  386. /* We're a directory; dump any old descriptors. */
  387. dirserv_remove_old_servers();
  388. /* dirservers try to reconnect too, in case connections have failed */
  389. router_retry_connections();
  390. }
  391. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  392. /* Force an upload of our descriptors every DirFetchPostPeriod seconds. */
  393. rend_services_upload(1);
  394. last_uploaded_services = now;
  395. rend_cache_clean(); /* should this go elsewhere? */
  396. time_to_fetch_directory = now + options.DirFetchPostPeriod;
  397. }
  398. /** 2. Every second, we examine pending circuits and prune the
  399. * ones which have been pending for more than a few seconds.
  400. * We do this before step 3, so it can try building more if
  401. * it's not comfortable with the number of available circuits.
  402. */
  403. circuit_expire_building(now);
  404. /** 2b. Also look at pending streams and prune the ones that 'began'
  405. * a long time ago but haven't gotten a 'connected' yet.
  406. * Do this before step 3, so we can put them back into pending
  407. * state to be picked up by the new circuit.
  408. */
  409. connection_ap_expire_beginning();
  410. /** 2c. And expire connections that we've held open for too long.
  411. */
  412. connection_expire_held_open();
  413. /** 3. Every second, we try a new circuit if there are no valid
  414. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  415. * that became dirty more than NewCircuitPeriod seconds ago,
  416. * and we make a new circ if there are no clean circuits.
  417. */
  418. if(has_fetched_directory)
  419. circuit_build_needed_circs(now);
  420. /** 4. We do housekeeping for each connection... */
  421. for(i=0;i<nfds;i++) {
  422. run_connection_housekeeping(i, now);
  423. }
  424. /** 5. And remove any marked circuits... */
  425. circuit_close_all_marked();
  426. /** 6. And upload service descriptors for any services whose intro points
  427. * have changed in the last second. */
  428. if (last_uploaded_services < now-5) {
  429. rend_services_upload(0);
  430. last_uploaded_services = now;
  431. }
  432. /** 7. and blow away any connections that need to die. have to do this now,
  433. * because if we marked a conn for close and left its socket -1, then
  434. * we'll pass it to poll/select and bad things will happen.
  435. */
  436. for(i=0;i<nfds;i++)
  437. conn_close_if_marked(i);
  438. }
  439. /** Called every time we're about to call tor_poll. Increments statistics,
  440. * and adjusts token buckets. Returns the number of milliseconds to use for
  441. * the poll() timeout.
  442. */
  443. static int prepare_for_poll(void) {
  444. static long current_second = 0; /* from previous calls to gettimeofday */
  445. connection_t *conn;
  446. struct timeval now;
  447. int i;
  448. tor_gettimeofday(&now);
  449. /* Check how much bandwidth we've consumed, and increment the token
  450. * buckets. */
  451. stats_n_bytes_read += stats_prev_global_read_bucket-global_read_bucket;
  452. connection_bucket_refill(&now);
  453. stats_prev_global_read_bucket = global_read_bucket;
  454. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  455. ++stats_n_seconds_uptime;
  456. assert_all_pending_dns_resolves_ok();
  457. run_scheduled_events(now.tv_sec);
  458. assert_all_pending_dns_resolves_ok();
  459. current_second = now.tv_sec; /* remember which second it is, for next time */
  460. }
  461. for(i=0;i<nfds;i++) {
  462. conn = connection_array[i];
  463. if(connection_has_pending_tls_data(conn) &&
  464. connection_is_reading(conn)) {
  465. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  466. return 0; /* has pending bytes to read; don't let poll wait. */
  467. }
  468. }
  469. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  470. }
  471. /** Configure the Tor process from the command line arguments and from the
  472. * configuration file.
  473. */
  474. static int init_from_config(int argc, char **argv) {
  475. /* read the configuration file. */
  476. if(getconfig(argc,argv,&options)) {
  477. log_fn(LOG_ERR,"Reading config failed. For usage, try -h.");
  478. return -1;
  479. }
  480. /* Setuid/setgid as appropriate */
  481. if(options.User || options.Group) {
  482. if(switch_id(options.User, options.Group) != 0) {
  483. return -1;
  484. }
  485. }
  486. /* Ensure data directory is private; create if possible. */
  487. if (check_private_dir(get_data_directory(&options), 1) != 0) {
  488. log_fn(LOG_ERR, "Couldn't access/create private data directory %s",
  489. get_data_directory(&options));
  490. return -1;
  491. }
  492. /* Start backgrounding the process, if requested. */
  493. if (options.RunAsDaemon) {
  494. start_daemon(get_data_directory(&options));
  495. }
  496. /* Configure the log(s) */
  497. if (config_init_logs(&options)<0)
  498. return -1;
  499. /* Close the temporary log we used while starting up, if it isn't already
  500. * gone. */
  501. close_temp_logs();
  502. /* Set up our buckets */
  503. connection_bucket_init();
  504. stats_prev_global_read_bucket = global_read_bucket;
  505. /* Finish backgrounding the process */
  506. if(options.RunAsDaemon) {
  507. /* XXXX Can we delay this any more? */
  508. finish_daemon();
  509. }
  510. /* Write our pid to the pid file. If we do not have write permissions we
  511. * will log a warning */
  512. if(options.PidFile)
  513. write_pidfile(options.PidFile);
  514. return 0;
  515. }
  516. /** Called when we get a SIGHUP: reload configuration files and keys,
  517. * retry all connections, re-upload all descriptors, and so on. */
  518. static int do_hup(void) {
  519. char keydir[512];
  520. log_fn(LOG_NOTICE,"Received sighup. Reloading config.");
  521. has_completed_circuit=0;
  522. mark_logs_temp(); /* Close current logs once new logs are open. */
  523. /* first, reload config variables, in case they've changed */
  524. /* no need to provide argc/v, they've been cached inside init_from_config */
  525. if (init_from_config(0, NULL) < 0) {
  526. exit(1);
  527. }
  528. /* reload keys as needed for rendezvous services. */
  529. if (rend_service_load_keys()<0) {
  530. log_fn(LOG_ERR,"Error reloading rendezvous service keys");
  531. exit(1);
  532. }
  533. if(retry_all_connections() < 0) {
  534. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  535. return -1;
  536. }
  537. if(options.DirPort) {
  538. /* reload the approved-routers file */
  539. sprintf(keydir,"%s/approved-routers", get_data_directory(&options));
  540. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  541. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  542. log_fn(LOG_WARN, "Error reloading fingerprints. Continuing with old list.");
  543. }
  544. /* Since we aren't fetching a directory, we won't retry rendezvous points
  545. * when it gets in. Try again now. */
  546. rend_services_introduce();
  547. } else {
  548. /* fetch a new directory */
  549. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  550. }
  551. if(options.ORPort) {
  552. /* Restart cpuworker and dnsworker processes, so they get up-to-date
  553. * configuration options. */
  554. cpuworkers_rotate();
  555. dnsworkers_rotate();
  556. /* Rebuild fresh descriptor as needed. */
  557. router_rebuild_descriptor();
  558. sprintf(keydir,"%s/router.desc", get_data_directory(&options));
  559. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  560. if (write_str_to_file(keydir, router_get_my_descriptor())) {
  561. return -1;
  562. }
  563. }
  564. return 0;
  565. }
  566. /** Tor main loop. */
  567. static int do_main_loop(void) {
  568. int i;
  569. int timeout;
  570. int poll_result;
  571. /* Initialize the history structures. */
  572. rep_hist_init();
  573. /* Intialize the service cache. */
  574. rend_cache_init();
  575. /* load the private keys, if we're supposed to have them, and set up the
  576. * TLS context. */
  577. if (init_keys() < 0 || rend_service_load_keys() < 0) {
  578. log_fn(LOG_ERR,"Error initializing keys; exiting");
  579. return -1;
  580. }
  581. /* load the routers file */
  582. if(options.RouterFile) {
  583. routerlist_clear_trusted_directories();
  584. if (router_load_routerlist_from_file(options.RouterFile, 1) < 0) {
  585. log_fn(LOG_ERR,"Error loading router list.");
  586. return -1;
  587. }
  588. }
  589. if(options.DirPort) { /* the directory is already here, run startup things */
  590. has_fetched_directory = 1;
  591. directory_has_arrived();
  592. }
  593. if(options.ORPort) {
  594. cpu_init(); /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  595. }
  596. /* start up the necessary connections based on which ports are
  597. * non-zero. This is where we try to connect to all the other ORs,
  598. * and start the listeners.
  599. */
  600. if(retry_all_connections() < 0) {
  601. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  602. return -1;
  603. }
  604. for(;;) {
  605. #ifdef MS_WINDOWS /* Do service stuff only on windows. */
  606. if (service_status.dwCurrentState != SERVICE_RUNNING) {
  607. return 0;
  608. }
  609. #else /* do signal stuff only on unix */
  610. if(please_dumpstats) {
  611. /* prefer to log it at INFO, but make sure we always see it */
  612. dumpstats(get_min_log_level()>LOG_INFO ? get_min_log_level() : LOG_INFO);
  613. please_dumpstats = 0;
  614. }
  615. if(please_reset) {
  616. do_hup();
  617. please_reset = 0;
  618. }
  619. if(please_reap_children) {
  620. while(waitpid(-1,NULL,WNOHANG)) ; /* keep reaping until no more zombies */
  621. please_reap_children = 0;
  622. }
  623. #endif /* signal stuff */
  624. timeout = prepare_for_poll();
  625. /* poll until we have an event, or the second ends */
  626. poll_result = tor_poll(poll_array, nfds, timeout);
  627. /* let catch() handle things like ^c, and otherwise don't worry about it */
  628. if(poll_result < 0) {
  629. /* let the program survive things like ^z */
  630. if(tor_socket_errno(-1) != EINTR) {
  631. log_fn(LOG_ERR,"poll failed: %s [%d]",
  632. tor_socket_strerror(tor_socket_errno(-1)),
  633. tor_socket_errno(-1));
  634. return -1;
  635. } else {
  636. log_fn(LOG_DEBUG,"poll interrupted.");
  637. }
  638. }
  639. /* do all the reads and errors first, so we can detect closed sockets */
  640. for(i=0;i<nfds;i++)
  641. conn_read(i); /* this also marks broken connections */
  642. /* then do the writes */
  643. for(i=0;i<nfds;i++)
  644. conn_write(i);
  645. /* any of the conns need to be closed now? */
  646. for(i=0;i<nfds;i++)
  647. conn_close_if_marked(i);
  648. /* refilling buckets and sending cells happens at the beginning of the
  649. * next iteration of the loop, inside prepare_for_poll()
  650. */
  651. }
  652. }
  653. /** Unix signal handler. */
  654. static void catch(int the_signal) {
  655. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  656. switch(the_signal) {
  657. // case SIGABRT:
  658. case SIGTERM:
  659. case SIGINT:
  660. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  661. /* we don't care if there was an error when we unlink, nothing
  662. we could do about it anyways */
  663. if(options.PidFile)
  664. unlink(options.PidFile);
  665. exit(0);
  666. case SIGPIPE:
  667. log(LOG_INFO,"Caught sigpipe. Ignoring.");
  668. break;
  669. case SIGHUP:
  670. please_reset = 1;
  671. break;
  672. case SIGUSR1:
  673. please_dumpstats = 1;
  674. break;
  675. case SIGCHLD:
  676. please_reap_children = 1;
  677. break;
  678. default:
  679. log(LOG_WARN,"Caught signal %d that we can't handle??", the_signal);
  680. }
  681. #endif /* signal stuff */
  682. }
  683. /** Write all statistics to the log, with log level 'severity'. Called
  684. * in response to a SIGUSR1. */
  685. static void dumpstats(int severity) {
  686. int i;
  687. connection_t *conn;
  688. time_t now = time(NULL);
  689. log(severity, "Dumping stats:");
  690. for(i=0;i<nfds;i++) {
  691. conn = connection_array[i];
  692. log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  693. i, conn->s, conn->type, CONN_TYPE_TO_STRING(conn->type),
  694. conn->state, conn_state_to_string[conn->type][conn->state], (int)(now - conn->timestamp_created));
  695. if(!connection_is_listener(conn)) {
  696. log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
  697. log(severity,"Conn %d: %d bytes waiting on inbuf (last read %d secs ago)",i,
  698. (int)buf_datalen(conn->inbuf),
  699. (int)(now - conn->timestamp_lastread));
  700. log(severity,"Conn %d: %d bytes waiting on outbuf (last written %d secs ago)",i,
  701. (int)buf_datalen(conn->outbuf), (int)(now - conn->timestamp_lastwritten));
  702. }
  703. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
  704. }
  705. log(severity,
  706. "Cells processed: %10lu padding\n"
  707. " %10lu create\n"
  708. " %10lu created\n"
  709. " %10lu relay\n"
  710. " (%10lu relayed)\n"
  711. " (%10lu delivered)\n"
  712. " %10lu destroy",
  713. stats_n_padding_cells_processed,
  714. stats_n_create_cells_processed,
  715. stats_n_created_cells_processed,
  716. stats_n_relay_cells_processed,
  717. stats_n_relay_cells_relayed,
  718. stats_n_relay_cells_delivered,
  719. stats_n_destroy_cells_processed);
  720. if (stats_n_data_cells_packaged)
  721. log(severity,"Average packaged cell fullness: %2.3f%%",
  722. 100*(((double)stats_n_data_bytes_packaged) /
  723. (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  724. if (stats_n_data_cells_received)
  725. log(severity,"Average delivered cell fullness: %2.3f%%",
  726. 100*(((double)stats_n_data_bytes_received) /
  727. (stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  728. if (stats_n_seconds_uptime)
  729. log(severity,"Average bandwidth used: %d bytes/sec",
  730. (int) (stats_n_bytes_read/stats_n_seconds_uptime));
  731. rep_hist_dump_stats(now,severity);
  732. rend_service_dump_stats(severity);
  733. }
  734. /** Called before we make any calls to network-related functions.
  735. * (Some operating systems require their network libraries to be
  736. * initialized.) */
  737. int network_init(void)
  738. {
  739. #ifdef MS_WINDOWS
  740. /* This silly exercise is necessary before windows will allow gethostbyname to work.
  741. */
  742. WSADATA WSAData;
  743. int r;
  744. r = WSAStartup(0x101,&WSAData);
  745. if (r) {
  746. log_fn(LOG_WARN,"Error initializing windows network layer: code was %d",r);
  747. return -1;
  748. }
  749. /* XXXX We should call WSACleanup on exit, I think. */
  750. #endif
  751. return 0;
  752. }
  753. /** Called by exit() as we shut down the process.
  754. */
  755. void exit_function(void)
  756. {
  757. #ifdef MS_WINDOWS
  758. WSACleanup();
  759. #endif
  760. }
  761. /** Main entry point for the Tor command-line client.
  762. */
  763. int tor_init(int argc, char *argv[]) {
  764. /* give it somewhere to log to initially */
  765. add_temp_log();
  766. log_fn(LOG_NOTICE,"Tor v%s. This is experimental software. Do not use it if you need anonymity.",VERSION);
  767. if (network_init()<0) {
  768. log_fn(LOG_ERR,"Error initializing network; exiting.");
  769. return -1;
  770. }
  771. atexit(exit_function);
  772. if (init_from_config(argc,argv) < 0)
  773. return -1;
  774. #ifndef MS_WINDOWS
  775. if(geteuid()==0)
  776. log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
  777. #endif
  778. if(options.ORPort) { /* only spawn dns handlers if we're a router */
  779. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  780. }
  781. if(options.SocksPort) {
  782. client_dns_init(); /* init the client dns cache */
  783. }
  784. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  785. {
  786. struct sigaction action;
  787. action.sa_flags = 0;
  788. sigemptyset(&action.sa_mask);
  789. action.sa_handler = catch;
  790. sigaction(SIGINT, &action, NULL);
  791. sigaction(SIGTERM, &action, NULL);
  792. sigaction(SIGPIPE, &action, NULL);
  793. sigaction(SIGUSR1, &action, NULL);
  794. sigaction(SIGHUP, &action, NULL); /* to reload config, retry conns, etc */
  795. sigaction(SIGCHLD, &action, NULL); /* handle dns/cpu workers that exit */
  796. }
  797. #endif /* signal stuff */
  798. crypto_global_init();
  799. crypto_seed_rng();
  800. return 0;
  801. }
  802. void tor_cleanup(void) {
  803. crypto_global_cleanup();
  804. }
  805. #ifdef MS_WINDOWS
  806. void nt_service_control(DWORD request)
  807. {
  808. switch (request) {
  809. case SERVICE_CONTROL_STOP:
  810. case SERVICE_CONTROL_SHUTDOWN:
  811. log(LOG_ERR, "Got stop/shutdown request; shutting down cleanly.");
  812. service_status.dwWin32ExitCode = 0;
  813. service_status.dwCurrentState = SERVICE_STOPPED;
  814. return;
  815. }
  816. SetServiceStatus(hStatus, &service_status);
  817. }
  818. void nt_service_body(int argc, char **argv)
  819. {
  820. int err;
  821. FILE *f;
  822. f = fopen("d:\\foo.txt", "w");
  823. fprintf(f, "POINT 1\n");
  824. fclose(f);
  825. service_status.dwServiceType = SERVICE_WIN32;
  826. service_status.dwCurrentState = SERVICE_START_PENDING;
  827. service_status.dwControlsAccepted =
  828. SERVICE_ACCEPT_STOP |
  829. SERVICE_ACCEPT_SHUTDOWN;
  830. service_status.dwWin32ExitCode = 0;
  831. service_status.dwServiceSpecificExitCode = 0;
  832. service_status.dwCheckPoint = 0;
  833. service_status.dwWaitHint = 0;
  834. hStatus = RegisterServiceCtrlHandler("Tor", (LPHANDLER_FUNCTION) nt_service_control);
  835. if (hStatus == 0) {
  836. // failed;
  837. return;
  838. }
  839. err = tor_init(argc, argv); // refactor this part out of tor_main and do_main_loop
  840. if (err) {
  841. // failed.
  842. service_status.dwCurrentState = SERVICE_STOPPED;
  843. service_status.dwWin32ExitCode = -1;
  844. SetServiceStatus(hStatus, &service_status);
  845. return;
  846. }
  847. service_status.dwCurrentState = SERVICE_RUNNING;
  848. SetServiceStatus(hStatus, &service_status);
  849. do_main_loop();
  850. tor_cleanup();
  851. return;
  852. }
  853. void nt_service_main(void)
  854. {
  855. SERVICE_TABLE_ENTRY table[2];
  856. table[0].lpServiceName = "Tor";
  857. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
  858. table[1].lpServiceName = NULL;
  859. table[1].lpServiceProc = NULL;
  860. if (!StartServiceCtrlDispatcher(table))
  861. printf("Error was %d\n",GetLastError());
  862. }
  863. #endif
  864. int tor_main(int argc, char *argv[]) {
  865. #ifdef MS_WINDOWS_SERVICE
  866. nt_service_main();
  867. return 0;
  868. #else
  869. if (tor_init(argc, argv)<0)
  870. return -1;
  871. do_main_loop();
  872. tor_cleanup();
  873. return -1;
  874. #endif
  875. }
  876. /*
  877. Local Variables:
  878. mode:c
  879. indent-tabs-mode:nil
  880. c-basic-offset:2
  881. End:
  882. */