main.c 33 KB

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