main.c 34 KB

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