main.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  1. /* Copyright 2001,2002,2003,2004 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. static int read_bandwidth_usage(void);
  13. static int record_bandwidth_usage(time_t now);
  14. static void configure_accounting(time_t now);
  15. static time_t start_of_accounting_period_after(time_t now);
  16. static time_t start_of_accounting_period_containing(time_t now);
  17. static void accounting_set_wakeup_time(void);
  18. /********* START VARIABLES **********/
  19. or_options_t options; /**< Command-line and config-file options. */
  20. int global_read_bucket; /**< Max number of bytes I can read this second. */
  21. int global_write_bucket; /**< Max number of bytes I can write this second. */
  22. /** What was the read bucket before the last call to prepare_for_pool?
  23. * (used to determine how many bytes we've read). */
  24. static int stats_prev_global_read_bucket;
  25. /** What was the write bucket before the last call to prepare_for_pool?
  26. * (used to determine how many bytes we've written). */
  27. static int stats_prev_global_write_bucket;
  28. /** How many bytes have we read/written since we started the process? */
  29. static uint64_t stats_n_bytes_read = 0;
  30. static uint64_t stats_n_bytes_written = 0;
  31. /** How many seconds have we been running? */
  32. long stats_n_seconds_uptime = 0;
  33. /** When do we next download a directory? */
  34. static time_t time_to_fetch_directory = 0;
  35. /** How many bytes have we read/written in this accounting interval? */
  36. static uint64_t stats_n_bytes_read_in_interval = 0;
  37. static uint64_t stats_n_bytes_written_in_interval = 0;
  38. /** When did this accounting interval start? */
  39. static time_t interval_start_time = 0;
  40. /** When will this accounting interval end? */
  41. static time_t interval_end_time = 0;
  42. /** How far into the accounting interval should we hibernate? */
  43. static time_t interval_wakeup_time = 0;
  44. /** Array of all open connections; each element corresponds to the element of
  45. * poll_array in the same position. The first nfds elements are valid. */
  46. static connection_t *connection_array[MAXCONNECTIONS] =
  47. { NULL };
  48. /** Array of pollfd objects for calls to poll(). */
  49. static struct pollfd poll_array[MAXCONNECTIONS];
  50. static int nfds=0; /**< Number of connections currently active. */
  51. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  52. static int please_dumpstats=0; /**< Whether we should dump stats during the loop. */
  53. static int please_reset=0; /**< Whether we just got a sighup. */
  54. static int please_reap_children=0; /**< Whether we should waitpid for exited children. */
  55. static int please_sigpipe=0; /**< Whether we've caught a sigpipe lately. */
  56. static int please_shutdown=0; /**< Whether we should shut down Tor. */
  57. #endif /* signal stuff */
  58. /** We set this to 1 when we've fetched a dir, to know whether to complain
  59. * yet about unrecognized nicknames in entrynodes, exitnodes, etc.
  60. * Also, we don't try building circuits unless this is 1. */
  61. int has_fetched_directory=0;
  62. /** We set this to 1 when we've opened a circuit, so we can print a log
  63. * entry to inform the user that Tor is working. */
  64. int has_completed_circuit=0;
  65. #ifdef MS_WINDOWS_SERVICE
  66. SERVICE_STATUS service_status;
  67. SERVICE_STATUS_HANDLE hStatus;
  68. #endif
  69. /********* END VARIABLES ************/
  70. /****************************************************************************
  71. *
  72. * This section contains accessors and other methods on the connection_array
  73. * and poll_array variables (which are global within this file and unavailable
  74. * outside it).
  75. *
  76. ****************************************************************************/
  77. /** Add <b>conn</b> to the array of connections that we can poll on. The
  78. * connection's socket must be set; the connection starts out
  79. * non-reading and non-writing.
  80. */
  81. int connection_add(connection_t *conn) {
  82. tor_assert(conn);
  83. tor_assert(conn->s >= 0);
  84. if(nfds >= options.MaxConn-1) {
  85. log_fn(LOG_WARN,"failing because nfds is too high.");
  86. return -1;
  87. }
  88. tor_assert(conn->poll_index == -1); /* can only connection_add once */
  89. conn->poll_index = nfds;
  90. connection_array[nfds] = conn;
  91. poll_array[nfds].fd = conn->s;
  92. /* zero these out here, because otherwise we'll inherit values from the previously freed one */
  93. poll_array[nfds].events = 0;
  94. poll_array[nfds].revents = 0;
  95. nfds++;
  96. log_fn(LOG_INFO,"new conn type %s, socket %d, nfds %d.",
  97. CONN_TYPE_TO_STRING(conn->type), conn->s, nfds);
  98. return 0;
  99. }
  100. /** Remove the connection from the global list, and remove the
  101. * corresponding poll entry. Calling this function will shift the last
  102. * connection (if any) into the position occupied by conn.
  103. */
  104. int connection_remove(connection_t *conn) {
  105. int current_index;
  106. tor_assert(conn);
  107. tor_assert(nfds>0);
  108. log_fn(LOG_INFO,"removing socket %d (type %s), nfds now %d",
  109. conn->s, CONN_TYPE_TO_STRING(conn->type), nfds-1);
  110. tor_assert(conn->poll_index >= 0);
  111. current_index = conn->poll_index;
  112. if(current_index == nfds-1) { /* this is the end */
  113. nfds--;
  114. return 0;
  115. }
  116. /* replace this one with the one at the end */
  117. nfds--;
  118. poll_array[current_index].fd = poll_array[nfds].fd;
  119. poll_array[current_index].events = poll_array[nfds].events;
  120. poll_array[current_index].revents = poll_array[nfds].revents;
  121. connection_array[current_index] = connection_array[nfds];
  122. connection_array[current_index]->poll_index = current_index;
  123. return 0;
  124. }
  125. /** Return true iff conn is in the current poll array. */
  126. int connection_in_array(connection_t *conn) {
  127. int i;
  128. for (i=0; i<nfds; ++i) {
  129. if (conn==connection_array[i])
  130. return 1;
  131. }
  132. return 0;
  133. }
  134. /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
  135. * to the length of the array. <b>*array</b> and <b>*n</b> must not
  136. * be modified.
  137. */
  138. void get_connection_array(connection_t ***array, int *n) {
  139. *array = connection_array;
  140. *n = nfds;
  141. }
  142. /** Set the event mask on <b>conn</b> to <b>events</b>. (The form of
  143. * the event mask is as for poll().)
  144. */
  145. void connection_watch_events(connection_t *conn, short events) {
  146. tor_assert(conn);
  147. tor_assert(conn->poll_index >= 0);
  148. tor_assert(conn->poll_index < nfds);
  149. poll_array[conn->poll_index].events = events;
  150. }
  151. /** Return true iff <b>conn</b> is listening for read events. */
  152. int connection_is_reading(connection_t *conn) {
  153. tor_assert(conn);
  154. tor_assert(conn->poll_index >= 0);
  155. return poll_array[conn->poll_index].events & POLLIN;
  156. }
  157. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  158. void connection_stop_reading(connection_t *conn) {
  159. tor_assert(conn);
  160. tor_assert(conn->poll_index >= 0);
  161. tor_assert(conn->poll_index < nfds);
  162. log(LOG_DEBUG,"connection_stop_reading() called.");
  163. poll_array[conn->poll_index].events &= ~POLLIN;
  164. }
  165. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  166. void connection_start_reading(connection_t *conn) {
  167. tor_assert(conn);
  168. tor_assert(conn->poll_index >= 0);
  169. tor_assert(conn->poll_index < nfds);
  170. poll_array[conn->poll_index].events |= POLLIN;
  171. }
  172. /** Return true iff <b>conn</b> is listening for write events. */
  173. int connection_is_writing(connection_t *conn) {
  174. return poll_array[conn->poll_index].events & POLLOUT;
  175. }
  176. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  177. void connection_stop_writing(connection_t *conn) {
  178. tor_assert(conn);
  179. tor_assert(conn->poll_index >= 0);
  180. tor_assert(conn->poll_index < nfds);
  181. poll_array[conn->poll_index].events &= ~POLLOUT;
  182. }
  183. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  184. void connection_start_writing(connection_t *conn) {
  185. tor_assert(conn);
  186. tor_assert(conn->poll_index >= 0);
  187. tor_assert(conn->poll_index < nfds);
  188. poll_array[conn->poll_index].events |= POLLOUT;
  189. }
  190. /** Called when the connection at connection_array[i] has a read event,
  191. * or it has pending tls data waiting to be read: checks for validity,
  192. * catches numerous errors, and dispatches to connection_handle_read.
  193. */
  194. static void conn_read(int i) {
  195. connection_t *conn = connection_array[i];
  196. if (conn->marked_for_close)
  197. return;
  198. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
  199. * discussion of POLLIN vs POLLHUP */
  200. if(!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
  201. if(!connection_is_reading(conn) ||
  202. !connection_has_pending_tls_data(conn))
  203. return; /* this conn should not read */
  204. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  205. assert_connection_ok(conn, time(NULL));
  206. assert_all_pending_dns_resolves_ok();
  207. if(
  208. /* XXX does POLLHUP also mean it's definitely broken? */
  209. #ifdef MS_WINDOWS
  210. (poll_array[i].revents & POLLERR) ||
  211. #endif
  212. connection_handle_read(conn) < 0) {
  213. if (!conn->marked_for_close) {
  214. /* this connection is broken. remove it */
  215. log_fn(LOG_WARN,"Unhandled error on read for %s connection (fd %d); removing",
  216. CONN_TYPE_TO_STRING(conn->type), conn->s);
  217. connection_mark_for_close(conn);
  218. }
  219. }
  220. assert_connection_ok(conn, time(NULL));
  221. assert_all_pending_dns_resolves_ok();
  222. }
  223. /** Called when the connection at connection_array[i] has a write event:
  224. * checks for validity, catches numerous errors, and dispatches to
  225. * connection_handle_write.
  226. */
  227. static void conn_write(int i) {
  228. connection_t *conn;
  229. if(!(poll_array[i].revents & POLLOUT))
  230. return; /* this conn doesn't want to write */
  231. conn = connection_array[i];
  232. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  233. if (conn->marked_for_close)
  234. return;
  235. assert_connection_ok(conn, time(NULL));
  236. assert_all_pending_dns_resolves_ok();
  237. if (connection_handle_write(conn) < 0) {
  238. if (!conn->marked_for_close) {
  239. /* this connection is broken. remove it. */
  240. log_fn(LOG_WARN,"Unhandled error on write for %s connection (fd %d); removing",
  241. CONN_TYPE_TO_STRING(conn->type), conn->s);
  242. conn->has_sent_end = 1; /* otherwise we cry wolf about duplicate close */
  243. /* XXX do we need a close-immediate here, so we don't try to flush? */
  244. connection_mark_for_close(conn);
  245. }
  246. }
  247. assert_connection_ok(conn, time(NULL));
  248. assert_all_pending_dns_resolves_ok();
  249. }
  250. /** If the connection at connection_array[i] is marked for close, then:
  251. * - If it has data that it wants to flush, try to flush it.
  252. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  253. * true, then leave the connection open and return.
  254. * - Otherwise, remove the connection from connection_array and from
  255. * all other lists, close it, and free it.
  256. * If we remove the connection, then call conn_closed_if_marked at the new
  257. * connection at position i.
  258. */
  259. static void conn_close_if_marked(int i) {
  260. connection_t *conn;
  261. int retval;
  262. conn = connection_array[i];
  263. assert_connection_ok(conn, time(NULL));
  264. assert_all_pending_dns_resolves_ok();
  265. if(!conn->marked_for_close)
  266. return; /* nothing to see here, move along */
  267. log_fn(LOG_INFO,"Cleaning up connection (fd %d).",conn->s);
  268. if(conn->s >= 0 && connection_wants_to_flush(conn)) {
  269. /* -1 means it's an incomplete edge connection, or that the socket
  270. * has already been closed as unflushable. */
  271. if(!conn->hold_open_until_flushed)
  272. log_fn(LOG_INFO,
  273. "Conn (addr %s, fd %d, type %s, state %d) marked, but wants to flush %d bytes. "
  274. "(Marked at %s:%d)",
  275. conn->address, conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  276. (int)conn->outbuf_flushlen, conn->marked_for_close_file, conn->marked_for_close);
  277. if(connection_speaks_cells(conn)) {
  278. if(conn->state == OR_CONN_STATE_OPEN) {
  279. retval = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  280. } else
  281. retval = -1; /* never flush non-open broken tls connections */
  282. } else {
  283. retval = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  284. }
  285. if(retval >= 0 &&
  286. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  287. log_fn(LOG_INFO,"Holding conn (fd %d) open for more flushing.",conn->s);
  288. /* XXX should we reset timestamp_lastwritten here? */
  289. return;
  290. }
  291. if(connection_wants_to_flush(conn)) {
  292. log_fn(LOG_WARN,"Conn (addr %s, fd %d, type %s, state %d) still wants to flush. Losing %d bytes! (Marked at %s:%d)",
  293. conn->address, conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state,
  294. (int)buf_datalen(conn->outbuf), conn->marked_for_close_file,
  295. conn->marked_for_close);
  296. }
  297. }
  298. /* if it's an edge conn, remove it from the list
  299. * of conn's on this circuit. If it's not on an edge,
  300. * flush and send destroys for all circuits on this conn
  301. */
  302. circuit_about_to_close_connection(conn);
  303. connection_about_to_close_connection(conn);
  304. connection_remove(conn);
  305. if(conn->type == CONN_TYPE_EXIT) {
  306. assert_connection_edge_not_dns_pending(conn);
  307. }
  308. connection_free(conn);
  309. if(i<nfds) { /* we just replaced the one at i with a new one.
  310. process it too. */
  311. conn_close_if_marked(i);
  312. }
  313. }
  314. /** This function is called whenever we successfully pull down a directory */
  315. void directory_has_arrived(time_t now) {
  316. log_fn(LOG_INFO, "A directory has arrived.");
  317. has_fetched_directory=1;
  318. /* Don't try to upload or download anything for DirFetchPostPeriod
  319. * seconds after the directory we had when we started.
  320. */
  321. if (!time_to_fetch_directory)
  322. time_to_fetch_directory = now + options.DirFetchPostPeriod;
  323. if (server_mode() &&
  324. !we_are_hibernating()) { /* connect to the appropriate routers */
  325. router_retry_connections();
  326. }
  327. }
  328. /* ************
  329. * Functions for bandwidth accounting.
  330. * ************/
  331. static time_t start_of_accounting_period_containing(time_t now)
  332. {
  333. struct tm *tm;
  334. /* Only months are supported. */
  335. tm = gmtime(&now);
  336. /* If this is before the Nth, we want the Nth of last month. */
  337. if (tm->tm_mday < options.AccountingStart) {
  338. if (--tm->tm_mon < 0) {
  339. tm->tm_mon = 11;
  340. --tm->tm_year;
  341. }
  342. }
  343. /* Otherwise, the month and year are correct.*/
  344. tm->tm_mday = options.AccountingStart;
  345. tm->tm_hour = 0;
  346. tm->tm_min = 0;
  347. tm->tm_sec = 0;
  348. return tor_timegm(tm);
  349. }
  350. static time_t start_of_accounting_period_after(time_t now)
  351. {
  352. time_t start;
  353. struct tm *tm;
  354. start = start_of_accounting_period_containing(now);
  355. tm = gmtime(&start);
  356. if (++tm->tm_mon > 11) {
  357. tm->tm_mon = 0;
  358. ++tm->tm_year;
  359. }
  360. return tor_timegm(tm);
  361. }
  362. static void configure_accounting(time_t now)
  363. {
  364. if (!interval_start_time)
  365. read_bandwidth_usage(); /* XXXX009 check warning? */
  366. if (!interval_start_time ||
  367. start_of_accounting_period_after(interval_start_time) <= now) {
  368. /* We start a new interval. */
  369. log_fn(LOG_INFO, "Starting new accounting interval.");
  370. interval_start_time = start_of_accounting_period_containing(now);
  371. interval_end_time = start_of_accounting_period_after(interval_start_time);
  372. stats_n_bytes_read_in_interval = 0;
  373. stats_n_bytes_written_in_interval = 0;
  374. } if (interval_start_time ==
  375. start_of_accounting_period_containing(interval_start_time)) {
  376. log_fn(LOG_INFO, "Continuing accounting interval.");
  377. /* We are in the interval we thought we were in. Do nothing.*/
  378. } else {
  379. /* XXXX009 We are in an incompatible interval; we must have
  380. * changed our configuration. Do we reset the interval, or
  381. * what? */
  382. log_fn(LOG_INFO, "Mismatched accounting interval.");
  383. }
  384. accounting_set_wakeup_time();
  385. }
  386. static INLINE int time_to_record_bandwidth_usage(time_t now)
  387. {
  388. /* Note every 5 minutes */
  389. #define NOTE_INTERVAL (5*60)
  390. /* Or every 20 megabytes */
  391. #define NOTE_BYTES 20*(1024*1024)
  392. static uint64_t last_read_bytes_noted = 0;
  393. static uint64_t last_written_bytes_noted = 0;
  394. static time_t last_time_noted = 0;
  395. if ((options.AccountingMaxKB || 1)&&
  396. (last_time_noted + NOTE_INTERVAL <= now ||
  397. last_read_bytes_noted + NOTE_BYTES <= stats_n_bytes_read_in_interval ||
  398. last_written_bytes_noted + NOTE_BYTES <=
  399. stats_n_bytes_written_in_interval ||
  400. (interval_end_time && interval_end_time <= now))) {
  401. last_time_noted = now;
  402. last_read_bytes_noted = stats_n_bytes_read_in_interval;
  403. last_written_bytes_noted = stats_n_bytes_written_in_interval;
  404. return 1;
  405. }
  406. return 0;
  407. }
  408. void accounting_set_wakeup_time(void)
  409. {
  410. struct tm *tm;
  411. char buf[ISO_TIME_LEN+1];
  412. char digest[DIGEST_LEN];
  413. crypto_digest_env_t *d;
  414. int n_days_in_interval;
  415. format_iso_time(buf, interval_start_time);
  416. crypto_pk_get_digest(get_identity_key(), digest);
  417. d = crypto_new_digest_env();
  418. crypto_digest_add_bytes(d, buf, ISO_TIME_LEN);
  419. crypto_digest_add_bytes(d, digest, DIGEST_LEN);
  420. crypto_digest_get_digest(d, digest, DIGEST_LEN);
  421. crypto_free_digest_env(d);
  422. /* XXXX009 This logic is wrong. Instead of choosing randomly
  423. * from the days in the interval, we should avoid days so close to the end
  424. * that we won't use up all our bandwidth. This could potentially waste
  425. * 50% of all donated bandwidth.
  426. */
  427. tm = gmtime(&interval_start_time);
  428. if (++tm->tm_mon > 11) { tm->tm_mon = 0; ++tm->tm_year; }
  429. n_days_in_interval = (tor_timegm(tm)-interval_start_time+1)/(24*60*60);
  430. while (((unsigned char)digest[0]) > n_days_in_interval)
  431. crypto_digest(digest, digest, DIGEST_LEN);
  432. interval_wakeup_time = interval_start_time +
  433. 24*60*60 * (unsigned char)digest[0];
  434. }
  435. static int record_bandwidth_usage(time_t now)
  436. {
  437. char buf[128];
  438. char fname[512];
  439. char *cp = buf;
  440. *cp++ = '0';
  441. *cp++ = ' ';
  442. format_iso_time(cp, interval_start_time);
  443. cp += ISO_TIME_LEN;
  444. *cp++ = ' ';
  445. format_iso_time(cp, now);
  446. cp += ISO_TIME_LEN;
  447. tor_snprintf(cp, sizeof(buf)-ISO_TIME_LEN*2-3,
  448. " "U64_FORMAT" "U64_FORMAT"\n",
  449. U64_PRINTF_ARG(stats_n_bytes_read_in_interval),
  450. U64_PRINTF_ARG(stats_n_bytes_written_in_interval));
  451. tor_snprintf(fname, sizeof(fname), "%s/bw_accounting",
  452. get_data_directory(&options));
  453. return write_str_to_file(fname, buf, 0);
  454. }
  455. static int read_bandwidth_usage(void)
  456. {
  457. char *s = NULL;
  458. char fname[512];
  459. time_t scratch_time;
  460. /*
  461. if (!options.AccountingMaxKB)
  462. return 0;
  463. */
  464. tor_snprintf(fname, sizeof(fname), "%s/bw_accounting",
  465. get_data_directory(&options));
  466. if (!(s = read_file_to_str(fname, 0))) {
  467. return 0;
  468. }
  469. /* version, space, time, space, time, space, bw, space, bw, nl. */
  470. if (strlen(s) < ISO_TIME_LEN*2+6) {
  471. log_fn(LOG_WARN,
  472. "Recorded bandwidth usage file seems truncated or corrupted");
  473. goto err;
  474. }
  475. if (s[0] != '0' || s[1] != ' ') {
  476. log_fn(LOG_WARN, "Unrecognized version on bandwidth usage file");
  477. goto err;
  478. }
  479. if (parse_iso_time(s+2, &interval_start_time)) {
  480. log_fn(LOG_WARN, "Error parsing bandwidth usage start time.");
  481. goto err;
  482. }
  483. if (s[ISO_TIME_LEN+2] != ' ') {
  484. log_fn(LOG_WARN, "Expected space after start time.");
  485. goto err;
  486. }
  487. if (parse_iso_time(s+ISO_TIME_LEN+3, &scratch_time)) {
  488. log_fn(LOG_WARN, "Error parsing bandwidth usage last-written time");
  489. goto err;
  490. }
  491. if (s[ISO_TIME_LEN+3+ISO_TIME_LEN] != ' ') {
  492. log_fn(LOG_WARN, "Expected space after last-written time.");
  493. goto err;
  494. }
  495. if (sscanf(s+ISO_TIME_LEN*2+4, U64_FORMAT" "U64_FORMAT,
  496. U64_SCANF_ARG(&stats_n_bytes_read_in_interval),
  497. U64_SCANF_ARG(&stats_n_bytes_written_in_interval))<2) {
  498. log_fn(LOG_WARN, "Error reading bandwidth usage.");
  499. goto err;
  500. }
  501. tor_free(s);
  502. accounting_set_wakeup_time();
  503. return 0;
  504. err:
  505. tor_free(s);
  506. return -1;
  507. }
  508. int accounting_hard_limit_reached(void)
  509. {
  510. uint64_t hard_limit = options.AccountingMaxKB<<10;
  511. if (!hard_limit)
  512. return 0;
  513. return stats_n_bytes_read_in_interval >= hard_limit
  514. || stats_n_bytes_written_in_interval >= hard_limit;
  515. }
  516. int accounting_soft_limit_reached(void)
  517. {
  518. uint64_t soft_limit = (uint64_t) ((options.AccountingMaxKB<<10) * .99);
  519. if (!soft_limit)
  520. return 0;
  521. return stats_n_bytes_read_in_interval >= soft_limit
  522. || stats_n_bytes_written_in_interval >= soft_limit;
  523. }
  524. time_t accounting_get_wakeup_time(void)
  525. {
  526. if (interval_wakeup_time > time(NULL))
  527. return interval_wakeup_time;
  528. else
  529. /*XXXX009 this means that callers must check for wakeup time again
  530. * at the start of the next interval. Not right! */
  531. return interval_end_time;
  532. }
  533. int accounting_should_hibernate(void)
  534. {
  535. return accounting_hard_limit_reached() || interval_wakeup_time > time(NULL);
  536. }
  537. /** Perform regular maintenance tasks for a single connection. This
  538. * function gets run once per second per connection by run_housekeeping.
  539. */
  540. static void run_connection_housekeeping(int i, time_t now) {
  541. cell_t cell;
  542. connection_t *conn = connection_array[i];
  543. /* Expire any directory connections that haven't sent anything for 5 min */
  544. if(conn->type == CONN_TYPE_DIR &&
  545. !conn->marked_for_close &&
  546. conn->timestamp_lastwritten + 5*60 < now) {
  547. log_fn(LOG_INFO,"Expiring wedged directory conn (fd %d, purpose %d)", conn->s, conn->purpose);
  548. connection_mark_for_close(conn);
  549. return;
  550. }
  551. /* If we haven't written to an OR connection for a while, then either nuke
  552. the connection or send a keepalive, depending. */
  553. if(connection_speaks_cells(conn) &&
  554. now >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
  555. routerinfo_t *router = router_get_by_digest(conn->identity_digest);
  556. if((!connection_state_is_open(conn)) ||
  557. (we_are_hibernating() && !circuit_get_by_conn(conn)) ||
  558. (!clique_mode() && !circuit_get_by_conn(conn) &&
  559. (!router || !server_mode() || !router_is_clique_mode(router)))) {
  560. /* our handshake has expired; we're hibernating;
  561. * or we have no circuits and we're both either OPs or normal ORs,
  562. * then kill it. */
  563. log_fn(LOG_INFO,"Expiring connection to %d (%s:%d).",
  564. i,conn->address, conn->port);
  565. /* flush anything waiting, e.g. a destroy for a just-expired circ */
  566. connection_mark_for_close(conn);
  567. conn->hold_open_until_flushed = 1;
  568. } else {
  569. /* either in clique mode, or we've got a circuit. send a padding cell. */
  570. log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  571. conn->address, conn->port);
  572. memset(&cell,0,sizeof(cell_t));
  573. cell.command = CELL_PADDING;
  574. connection_or_write_cell_to_buf(&cell, conn);
  575. }
  576. }
  577. }
  578. #define MIN_BW_TO_PUBLISH_DESC 5000 /* 5000 bytes/s sustained */
  579. #define MIN_UPTIME_TO_PUBLISH_DESC (30*60) /* half an hour */
  580. /** Decide if we're a publishable server or just a client. We are a server if:
  581. * - We have the AuthoritativeDirectory option set.
  582. * or
  583. * - We don't have the ClientOnly option set; and
  584. * - We have ORPort set; and
  585. * - We have been up for at least MIN_UPTIME_TO_PUBLISH_DESC seconds; and
  586. * - We have processed some suitable minimum bandwidth recently; and
  587. * - We believe we are reachable from the outside.
  588. */
  589. static int decide_if_publishable_server(time_t now) {
  590. int bw;
  591. bw = rep_hist_bandwidth_assess();
  592. router_set_bandwidth_capacity(bw);
  593. if(options.ClientOnly)
  594. return 0;
  595. if(!options.ORPort)
  596. return 0;
  597. /* XXX008 for now, you're only a server if you're a server */
  598. return server_mode();
  599. /* here, determine if we're reachable */
  600. if(0) { /* we've recently failed to reach our IP/ORPort from the outside */
  601. return 0;
  602. }
  603. if(bw < MIN_BW_TO_PUBLISH_DESC)
  604. return 0;
  605. if(options.AuthoritativeDir)
  606. return 1;
  607. if(stats_n_seconds_uptime < MIN_UPTIME_TO_PUBLISH_DESC)
  608. return 0;
  609. return 1;
  610. }
  611. /** Return true iff we believe ourselves to be an authoritative
  612. * directory server.
  613. */
  614. int authdir_mode(void) {
  615. return (options.AuthoritativeDir != 0);
  616. }
  617. /** Return true iff we try to stay connected to all ORs at once.
  618. */
  619. int clique_mode(void) {
  620. return authdir_mode();
  621. }
  622. /** Return true iff we are trying to be a server.
  623. */
  624. int server_mode(void) {
  625. return (options.ORPort != 0 || options.ORBindAddress);
  626. }
  627. /** Remember if we've advertised ourselves to the dirservers. */
  628. static int server_is_advertised=0;
  629. /** Return true iff we have published our descriptor lately.
  630. */
  631. int advertised_server_mode(void) {
  632. return server_is_advertised;
  633. }
  634. /** Return true iff we are trying to be a socks proxy. */
  635. int proxy_mode(void) {
  636. return (options.SocksPort != 0 || options.SocksBindAddress);
  637. }
  638. /** Perform regular maintenance tasks. This function gets run once per
  639. * second by prepare_for_poll.
  640. */
  641. static void run_scheduled_events(time_t now) {
  642. static time_t last_uploaded_services = 0;
  643. static time_t last_rotated_certificate = 0;
  644. static time_t time_to_check_listeners = 0;
  645. int i;
  646. /** 0. See if we've been asked to shut down and our timeout has
  647. * expired; or if our bandwidth limits are exhausted and we
  648. * should hibernate; or if it's time to wake up from hibernation.
  649. */
  650. consider_hibernation(now);
  651. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  652. * shut down and restart all cpuworkers, and update the directory if
  653. * necessary.
  654. */
  655. if (server_mode() && get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  656. log_fn(LOG_INFO,"Rotating onion key.");
  657. rotate_onion_key();
  658. cpuworkers_rotate();
  659. if (router_rebuild_descriptor()<0) {
  660. log_fn(LOG_WARN, "Couldn't rebuild router descriptor");
  661. }
  662. if(advertised_server_mode())
  663. router_upload_dir_desc_to_dirservers();
  664. }
  665. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  666. if (!last_rotated_certificate)
  667. last_rotated_certificate = now;
  668. if (last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
  669. log_fn(LOG_INFO,"Rotating tls context.");
  670. if (tor_tls_context_new(get_identity_key(), 1, options.Nickname,
  671. MAX_SSL_KEY_LIFETIME) < 0) {
  672. log_fn(LOG_WARN, "Error reinitializing TLS context");
  673. }
  674. last_rotated_certificate = now;
  675. /* XXXX We should rotate TLS connections as well; this code doesn't change
  676. * XXXX them at all. */
  677. }
  678. /** 1c. If we have to change the accounting interval or record
  679. * bandwidth used in this accounting interval, do so. */
  680. if (now >= interval_end_time) {
  681. configure_accounting(now);
  682. }
  683. if (time_to_record_bandwidth_usage(now)) {
  684. if (record_bandwidth_usage(now)) {
  685. log_fn(LOG_WARN, "Couldn't record bandwidth usage!");
  686. /* XXXX009 should this exit? */
  687. }
  688. }
  689. /** 2. Every DirFetchPostPeriod seconds, we get a new directory and upload
  690. * our descriptor (if we've passed our internal checks). */
  691. if(time_to_fetch_directory < now) {
  692. if(decide_if_publishable_server(now)) {
  693. server_is_advertised = 1;
  694. router_rebuild_descriptor();
  695. router_upload_dir_desc_to_dirservers();
  696. } else {
  697. server_is_advertised = 0;
  698. }
  699. /* purge obsolete entries */
  700. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  701. if(authdir_mode()) {
  702. /* We're a directory; dump any old descriptors. */
  703. dirserv_remove_old_servers(ROUTER_MAX_AGE);
  704. }
  705. if(server_mode() && !we_are_hibernating()) {
  706. /* dirservers try to reconnect, in case connections have failed;
  707. * and normal servers try to reconnect to dirservers */
  708. router_retry_connections();
  709. }
  710. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  711. if(!we_are_hibernating()) {
  712. /* Force an upload of our rend descriptors every DirFetchPostPeriod seconds. */
  713. rend_services_upload(1);
  714. last_uploaded_services = now;
  715. }
  716. rend_cache_clean(); /* should this go elsewhere? */
  717. time_to_fetch_directory = now + options.DirFetchPostPeriod;
  718. }
  719. /** 3a. Every second, we examine pending circuits and prune the
  720. * ones which have been pending for more than a few seconds.
  721. * We do this before step 3, so it can try building more if
  722. * it's not comfortable with the number of available circuits.
  723. */
  724. circuit_expire_building(now);
  725. /** 3b. Also look at pending streams and prune the ones that 'began'
  726. * a long time ago but haven't gotten a 'connected' yet.
  727. * Do this before step 3, so we can put them back into pending
  728. * state to be picked up by the new circuit.
  729. */
  730. connection_ap_expire_beginning();
  731. /** 3c. And expire connections that we've held open for too long.
  732. */
  733. connection_expire_held_open();
  734. /** 3d. And every 60 seconds, we relaunch listeners if any died. */
  735. if (!we_are_hibernating() && time_to_check_listeners < now) {
  736. retry_all_listeners(0); /* 0 means "only if some died." */
  737. time_to_check_listeners = now+60;
  738. }
  739. /** 4. Every second, we try a new circuit if there are no valid
  740. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  741. * that became dirty more than NewCircuitPeriod seconds ago,
  742. * and we make a new circ if there are no clean circuits.
  743. */
  744. if(has_fetched_directory && !we_are_hibernating())
  745. circuit_build_needed_circs(now);
  746. /** 5. We do housekeeping for each connection... */
  747. for(i=0;i<nfds;i++) {
  748. run_connection_housekeeping(i, now);
  749. }
  750. /** 6. And remove any marked circuits... */
  751. circuit_close_all_marked();
  752. /** 7. And upload service descriptors for any services whose intro points
  753. * have changed in the last second. */
  754. if (last_uploaded_services < now-5) {
  755. rend_services_upload(0);
  756. last_uploaded_services = now;
  757. }
  758. /** 8. and blow away any connections that need to die. have to do this now,
  759. * because if we marked a conn for close and left its socket -1, then
  760. * we'll pass it to poll/select and bad things will happen.
  761. */
  762. for(i=0;i<nfds;i++)
  763. conn_close_if_marked(i);
  764. }
  765. /** Called every time we're about to call tor_poll. Increments statistics,
  766. * and adjusts token buckets. Returns the number of milliseconds to use for
  767. * the poll() timeout.
  768. */
  769. static int prepare_for_poll(void) {
  770. static long current_second = 0; /* from previous calls to gettimeofday */
  771. connection_t *conn;
  772. struct timeval now;
  773. int i;
  774. tor_gettimeofday(&now);
  775. if(now.tv_sec > current_second) {
  776. /* the second has rolled over. check more stuff. */
  777. size_t bytes_written;
  778. size_t bytes_read;
  779. bytes_written = stats_prev_global_write_bucket - global_write_bucket;
  780. bytes_read = stats_prev_global_read_bucket - global_read_bucket;
  781. stats_n_bytes_read += bytes_read;
  782. stats_n_bytes_read_in_interval += bytes_read;
  783. stats_n_bytes_written += bytes_written;
  784. stats_n_bytes_written_in_interval += bytes_written;
  785. control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
  786. connection_bucket_refill(&now);
  787. stats_prev_global_read_bucket = global_read_bucket;
  788. stats_prev_global_write_bucket = global_write_bucket;
  789. if(current_second)
  790. stats_n_seconds_uptime += (now.tv_sec - current_second);
  791. assert_all_pending_dns_resolves_ok();
  792. run_scheduled_events(now.tv_sec);
  793. assert_all_pending_dns_resolves_ok();
  794. current_second = now.tv_sec; /* remember which second it is, for next time */
  795. }
  796. for(i=0;i<nfds;i++) {
  797. conn = connection_array[i];
  798. if(connection_has_pending_tls_data(conn) &&
  799. connection_is_reading(conn)) {
  800. log_fn(LOG_DEBUG,"sock %d has pending bytes.",conn->s);
  801. return 0; /* has pending bytes to read; don't let poll wait. */
  802. }
  803. }
  804. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  805. }
  806. /** Configure the Tor process from the command line arguments and from the
  807. * configuration file.
  808. */
  809. static int init_from_config(int argc, char **argv) {
  810. /* read the configuration file. */
  811. if(getconfig(argc,argv,&options)) {
  812. log_fn(LOG_ERR,"Reading config failed--see warnings above. For usage, try -h.");
  813. return -1;
  814. }
  815. /* Setuid/setgid as appropriate */
  816. if(options.User || options.Group) {
  817. if(switch_id(options.User, options.Group) != 0) {
  818. return -1;
  819. }
  820. }
  821. /* Ensure data directory is private; create if possible. */
  822. if (get_data_directory(&options) &&
  823. check_private_dir(get_data_directory(&options), 1) != 0) {
  824. log_fn(LOG_ERR, "Couldn't access/create private data directory %s",
  825. get_data_directory(&options));
  826. return -1;
  827. }
  828. /* Bail out at this point if we're not going to be a server: we want
  829. * to not fork, and to log stuff to stderr. */
  830. if (options.command != CMD_RUN_TOR)
  831. return 0;
  832. /* Configure the log(s) */
  833. if (config_init_logs(&options)<0)
  834. return -1;
  835. /* Close the temporary log we used while starting up, if it isn't already
  836. * gone. */
  837. close_temp_logs();
  838. add_callback_log(LOG_WARN, LOG_ERR, control_event_logmsg);
  839. /* Start backgrounding the process, if requested. */
  840. if (options.RunAsDaemon) {
  841. start_daemon(get_data_directory(&options));
  842. }
  843. /* Set up our buckets */
  844. connection_bucket_init();
  845. stats_prev_global_read_bucket = global_read_bucket;
  846. stats_prev_global_write_bucket = global_write_bucket;
  847. /* Finish backgrounding the process */
  848. if(options.RunAsDaemon) {
  849. /* XXXX Can we delay this any more? */
  850. finish_daemon();
  851. }
  852. /* Write our pid to the pid file. If we do not have write permissions we
  853. * will log a warning */
  854. if(options.PidFile)
  855. write_pidfile(options.PidFile);
  856. return 0;
  857. }
  858. /** Called when we get a SIGHUP: reload configuration files and keys,
  859. * retry all connections, re-upload all descriptors, and so on. */
  860. static int do_hup(void) {
  861. char keydir[512];
  862. log_fn(LOG_NOTICE,"Received sighup. Reloading config.");
  863. has_completed_circuit=0;
  864. mark_logs_temp(); /* Close current logs once new logs are open. */
  865. /* first, reload config variables, in case they've changed */
  866. /* no need to provide argc/v, they've been cached inside init_from_config */
  867. if (init_from_config(0, NULL) < 0) {
  868. return -1;
  869. }
  870. /* reload keys as needed for rendezvous services. */
  871. if (rend_service_load_keys()<0) {
  872. log_fn(LOG_ERR,"Error reloading rendezvous service keys");
  873. return -1;
  874. }
  875. if(retry_all_listeners(1) < 0) {
  876. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  877. return -1;
  878. }
  879. if(authdir_mode()) {
  880. /* reload the approved-routers file */
  881. tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", get_data_directory(&options));
  882. log_fn(LOG_INFO,"Reloading approved fingerprints from %s...",keydir);
  883. if(dirserv_parse_fingerprint_file(keydir) < 0) {
  884. log_fn(LOG_WARN, "Error reloading fingerprints. Continuing with old list.");
  885. }
  886. }
  887. /* Fetch a new directory. Even authdirservers do this. */
  888. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  889. if(server_mode()) {
  890. /* Restart cpuworker and dnsworker processes, so they get up-to-date
  891. * configuration options. */
  892. cpuworkers_rotate();
  893. dnsworkers_rotate();
  894. /* Rebuild fresh descriptor as needed. */
  895. router_rebuild_descriptor();
  896. tor_snprintf(keydir,sizeof(keydir),"%s/router.desc", get_data_directory(&options));
  897. log_fn(LOG_INFO,"Dumping descriptor to %s...",keydir);
  898. if (write_str_to_file(keydir, router_get_my_descriptor(), 0)) {
  899. return -1;
  900. }
  901. }
  902. return 0;
  903. }
  904. /** Tor main loop. */
  905. static int do_main_loop(void) {
  906. int i;
  907. int timeout;
  908. int poll_result;
  909. /* Initialize the history structures. */
  910. rep_hist_init();
  911. /* Intialize the service cache. */
  912. rend_cache_init();
  913. /* load the private keys, if we're supposed to have them, and set up the
  914. * TLS context. */
  915. if (init_keys() < 0 || rend_service_load_keys() < 0) {
  916. log_fn(LOG_ERR,"Error initializing keys; exiting");
  917. return -1;
  918. }
  919. /* Set up accounting */
  920. configure_accounting(time(NULL));
  921. /* load the routers file, or assign the defaults. */
  922. if(router_reload_router_list()) {
  923. return -1;
  924. }
  925. if(authdir_mode()) {
  926. /* the directory is already here, run startup things */
  927. router_retry_connections();
  928. }
  929. if(server_mode()) {
  930. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  931. cpu_init();
  932. }
  933. /* start up the necessary listeners based on which ports are non-zero. */
  934. if(retry_all_listeners(1) < 0) {
  935. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  936. return -1;
  937. }
  938. for(;;) {
  939. #ifdef MS_WINDOWS_SERVICE /* Do service stuff only on windows. */
  940. if (service_status.dwCurrentState != SERVICE_RUNNING) {
  941. return 0;
  942. }
  943. #endif
  944. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  945. if(please_shutdown) {
  946. if(!server_mode()) { /* do it now */
  947. log(LOG_NOTICE,"Interrupt: exiting cleanly.");
  948. tor_cleanup();
  949. exit(0);
  950. }
  951. hibernate_begin_shutdown();
  952. please_shutdown = 0;
  953. }
  954. if(please_sigpipe) {
  955. log(LOG_NOTICE,"Caught sigpipe. Ignoring.");
  956. please_sigpipe = 0;
  957. }
  958. if(please_dumpstats) {
  959. /* prefer to log it at INFO, but make sure we always see it */
  960. dumpstats(get_min_log_level()>LOG_INFO ? get_min_log_level() : LOG_INFO);
  961. please_dumpstats = 0;
  962. }
  963. if(please_reset) {
  964. if (do_hup() < 0) {
  965. log_fn(LOG_WARN,"Restart failed (config error?). Exiting.");
  966. tor_cleanup();
  967. exit(1);
  968. }
  969. please_reset = 0;
  970. }
  971. if(please_reap_children) {
  972. while(waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more zombies */
  973. please_reap_children = 0;
  974. }
  975. #endif /* signal stuff */
  976. timeout = prepare_for_poll();
  977. /* poll until we have an event, or the second ends */
  978. poll_result = tor_poll(poll_array, nfds, timeout);
  979. /* let catch() handle things like ^c, and otherwise don't worry about it */
  980. if(poll_result < 0) {
  981. /* let the program survive things like ^z */
  982. if(tor_socket_errno(-1) != EINTR) {
  983. log_fn(LOG_ERR,"poll failed: %s [%d]",
  984. tor_socket_strerror(tor_socket_errno(-1)),
  985. tor_socket_errno(-1));
  986. return -1;
  987. } else {
  988. log_fn(LOG_DEBUG,"poll interrupted.");
  989. }
  990. }
  991. /* do all the reads and errors first, so we can detect closed sockets */
  992. for(i=0;i<nfds;i++)
  993. conn_read(i); /* this also marks broken connections */
  994. /* then do the writes */
  995. for(i=0;i<nfds;i++)
  996. conn_write(i);
  997. /* any of the conns need to be closed now? */
  998. for(i=0;i<nfds;i++)
  999. conn_close_if_marked(i);
  1000. /* refilling buckets and sending cells happens at the beginning of the
  1001. * next iteration of the loop, inside prepare_for_poll()
  1002. */
  1003. }
  1004. }
  1005. /** Unix signal handler. */
  1006. static void catch(int the_signal) {
  1007. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  1008. switch(the_signal) {
  1009. // case SIGABRT:
  1010. case SIGTERM:
  1011. log(LOG_ERR,"Catching signal %d, exiting cleanly.", the_signal);
  1012. tor_cleanup();
  1013. exit(0);
  1014. case SIGINT:
  1015. please_shutdown = 1;
  1016. break;
  1017. case SIGPIPE:
  1018. /* don't log here, since it's possible you got the sigpipe because
  1019. * your log failed! */
  1020. please_sigpipe = 1;
  1021. break;
  1022. case SIGHUP:
  1023. please_reset = 1;
  1024. break;
  1025. case SIGUSR1:
  1026. please_dumpstats = 1;
  1027. break;
  1028. case SIGCHLD:
  1029. please_reap_children = 1;
  1030. break;
  1031. default:
  1032. log(LOG_WARN,"Caught signal %d that we can't handle??", the_signal);
  1033. tor_cleanup();
  1034. exit(1);
  1035. }
  1036. #endif /* signal stuff */
  1037. }
  1038. /** Write all statistics to the log, with log level 'severity'. Called
  1039. * in response to a SIGUSR1. */
  1040. static void dumpstats(int severity) {
  1041. int i;
  1042. connection_t *conn;
  1043. time_t now = time(NULL);
  1044. log(severity, "Dumping stats:");
  1045. for(i=0;i<nfds;i++) {
  1046. conn = connection_array[i];
  1047. log(severity, "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  1048. i, conn->s, conn->type, CONN_TYPE_TO_STRING(conn->type),
  1049. conn->state, conn_state_to_string[conn->type][conn->state], (int)(now - conn->timestamp_created));
  1050. if(!connection_is_listener(conn)) {
  1051. log(severity,"Conn %d is to '%s:%d'.",i,conn->address, conn->port);
  1052. log(severity,"Conn %d: %d bytes waiting on inbuf (last read %d secs ago)",i,
  1053. (int)buf_datalen(conn->inbuf),
  1054. (int)(now - conn->timestamp_lastread));
  1055. log(severity,"Conn %d: %d bytes waiting on outbuf (last written %d secs ago)",i,
  1056. (int)buf_datalen(conn->outbuf), (int)(now - conn->timestamp_lastwritten));
  1057. }
  1058. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits using this conn */
  1059. }
  1060. log(severity,
  1061. "Cells processed: %10lu padding\n"
  1062. " %10lu create\n"
  1063. " %10lu created\n"
  1064. " %10lu relay\n"
  1065. " (%10lu relayed)\n"
  1066. " (%10lu delivered)\n"
  1067. " %10lu destroy",
  1068. stats_n_padding_cells_processed,
  1069. stats_n_create_cells_processed,
  1070. stats_n_created_cells_processed,
  1071. stats_n_relay_cells_processed,
  1072. stats_n_relay_cells_relayed,
  1073. stats_n_relay_cells_delivered,
  1074. stats_n_destroy_cells_processed);
  1075. if (stats_n_data_cells_packaged)
  1076. log(severity,"Average packaged cell fullness: %2.3f%%",
  1077. 100*(((double)stats_n_data_bytes_packaged) /
  1078. (stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  1079. if (stats_n_data_cells_received)
  1080. log(severity,"Average delivered cell fullness: %2.3f%%",
  1081. 100*(((double)stats_n_data_bytes_received) /
  1082. (stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  1083. if (stats_n_seconds_uptime)
  1084. log(severity,
  1085. "Average bandwidth used: "U64_FORMAT"/%ld = %d bytes/sec",
  1086. U64_PRINTF_ARG(stats_n_bytes_read),
  1087. stats_n_seconds_uptime,
  1088. (int) (stats_n_bytes_read/stats_n_seconds_uptime));
  1089. rep_hist_dump_stats(now,severity);
  1090. rend_service_dump_stats(severity);
  1091. }
  1092. /** Called before we make any calls to network-related functions.
  1093. * (Some operating systems require their network libraries to be
  1094. * initialized.) */
  1095. static int network_init(void)
  1096. {
  1097. #ifdef MS_WINDOWS
  1098. /* This silly exercise is necessary before windows will allow gethostbyname to work.
  1099. */
  1100. WSADATA WSAData;
  1101. int r;
  1102. r = WSAStartup(0x101,&WSAData);
  1103. if (r) {
  1104. log_fn(LOG_WARN,"Error initializing windows network layer: code was %d",r);
  1105. return -1;
  1106. }
  1107. /* XXXX We should call WSACleanup on exit, I think. */
  1108. #endif
  1109. return 0;
  1110. }
  1111. /** Called by exit() as we shut down the process.
  1112. */
  1113. static void exit_function(void)
  1114. {
  1115. /* XXX if we ever daemonize, this gets called immediately */
  1116. #ifdef MS_WINDOWS
  1117. WSACleanup();
  1118. #endif
  1119. }
  1120. /** Set up the signal handlers for either parent or child. */
  1121. void handle_signals(int is_parent)
  1122. {
  1123. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  1124. struct sigaction action;
  1125. action.sa_flags = 0;
  1126. sigemptyset(&action.sa_mask);
  1127. action.sa_handler = is_parent ? catch : SIG_IGN;
  1128. sigaction(SIGINT, &action, NULL); /* do a controlled slow shutdown */
  1129. sigaction(SIGTERM, &action, NULL); /* to terminate now */
  1130. sigaction(SIGPIPE, &action, NULL); /* otherwise sigpipe kills us */
  1131. sigaction(SIGUSR1, &action, NULL); /* dump stats */
  1132. sigaction(SIGHUP, &action, NULL); /* to reload config, retry conns, etc */
  1133. if(is_parent)
  1134. sigaction(SIGCHLD, &action, NULL); /* handle dns/cpu workers that exit */
  1135. #endif /* signal stuff */
  1136. }
  1137. /** Main entry point for the Tor command-line client.
  1138. */
  1139. static int tor_init(int argc, char *argv[]) {
  1140. /* give it somewhere to log to initially */
  1141. add_temp_log();
  1142. log_fn(LOG_NOTICE,"Tor v%s. This is experimental software. Do not use it if you need anonymity.",VERSION);
  1143. if (network_init()<0) {
  1144. log_fn(LOG_ERR,"Error initializing network; exiting.");
  1145. return -1;
  1146. }
  1147. atexit(exit_function);
  1148. if (init_from_config(argc,argv) < 0)
  1149. return -1;
  1150. #ifndef MS_WINDOWS
  1151. if(geteuid()==0)
  1152. log_fn(LOG_WARN,"You are running Tor as root. You don't need to, and you probably shouldn't.");
  1153. #endif
  1154. if(server_mode()) { /* only spawn dns handlers if we're a router */
  1155. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  1156. }
  1157. if(proxy_mode()) {
  1158. client_dns_init(); /* init the client dns cache */
  1159. }
  1160. handle_signals(1);
  1161. if (set_max_file_descriptors(options.MaxConn) < 0)
  1162. return -1;
  1163. crypto_global_init();
  1164. crypto_seed_rng();
  1165. return 0;
  1166. }
  1167. /** Do whatever cleanup is necessary before shutting Tor down. */
  1168. void tor_cleanup(void) {
  1169. /* Remove our pid file. We don't care if there was an error when we
  1170. * unlink, nothing we could do about it anyways. */
  1171. if(options.PidFile && options.command == CMD_RUN_TOR)
  1172. unlink(options.PidFile);
  1173. crypto_global_cleanup();
  1174. }
  1175. /** Read/create keys as needed, and echo our fingerprint to stdout. */
  1176. static void do_list_fingerprint(void)
  1177. {
  1178. char buf[FINGERPRINT_LEN+1];
  1179. crypto_pk_env_t *k;
  1180. if (init_keys() < 0) {
  1181. log_fn(LOG_ERR,"Error initializing keys; exiting");
  1182. return;
  1183. }
  1184. if (!(k = get_identity_key())) {
  1185. log_fn(LOG_ERR,"Error: missing identity key.");
  1186. return;
  1187. }
  1188. if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
  1189. log_fn(LOG_ERR, "Error computing fingerprint");
  1190. return;
  1191. }
  1192. }
  1193. /** DOCDOC **/
  1194. static void do_hash_password(void)
  1195. {
  1196. char output[256];
  1197. char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
  1198. crypto_rand(key, S2K_SPECIFIER_LEN-1);
  1199. key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
  1200. secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
  1201. options.command_arg, strlen(options.command_arg),
  1202. key);
  1203. if (base64_encode(output, sizeof(output), key, sizeof(key))<0) {
  1204. log_fn(LOG_ERR, "Unable to compute base64");
  1205. } else {
  1206. printf("%s",output);
  1207. }
  1208. }
  1209. #ifdef MS_WINDOWS_SERVICE
  1210. void nt_service_control(DWORD request)
  1211. {
  1212. switch (request) {
  1213. case SERVICE_CONTROL_STOP:
  1214. case SERVICE_CONTROL_SHUTDOWN:
  1215. log(LOG_ERR, "Got stop/shutdown request; shutting down cleanly.");
  1216. service_status.dwWin32ExitCode = 0;
  1217. service_status.dwCurrentState = SERVICE_STOPPED;
  1218. return;
  1219. }
  1220. SetServiceStatus(hStatus, &service_status);
  1221. }
  1222. void nt_service_body(int argc, char **argv)
  1223. {
  1224. int err;
  1225. FILE *f;
  1226. f = fopen("d:\\foo.txt", "w");
  1227. fprintf(f, "POINT 1\n");
  1228. fclose(f);
  1229. service_status.dwServiceType = SERVICE_WIN32;
  1230. service_status.dwCurrentState = SERVICE_START_PENDING;
  1231. service_status.dwControlsAccepted =
  1232. SERVICE_ACCEPT_STOP |
  1233. SERVICE_ACCEPT_SHUTDOWN;
  1234. service_status.dwWin32ExitCode = 0;
  1235. service_status.dwServiceSpecificExitCode = 0;
  1236. service_status.dwCheckPoint = 0;
  1237. service_status.dwWaitHint = 0;
  1238. hStatus = RegisterServiceCtrlHandler("Tor", (LPHANDLER_FUNCTION) nt_service_control);
  1239. if (hStatus == 0) {
  1240. // failed;
  1241. return;
  1242. }
  1243. err = tor_init(argc, argv); // refactor this part out of tor_main and do_main_loop
  1244. if (err) {
  1245. // failed.
  1246. service_status.dwCurrentState = SERVICE_STOPPED;
  1247. service_status.dwWin32ExitCode = -1;
  1248. SetServiceStatus(hStatus, &service_status);
  1249. return;
  1250. }
  1251. service_status.dwCurrentState = SERVICE_RUNNING;
  1252. SetServiceStatus(hStatus, &service_status);
  1253. do_main_loop();
  1254. tor_cleanup();
  1255. return;
  1256. }
  1257. void nt_service_main(void)
  1258. {
  1259. SERVICE_TABLE_ENTRY table[2];
  1260. table[0].lpServiceName = "Tor";
  1261. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
  1262. table[1].lpServiceName = NULL;
  1263. table[1].lpServiceProc = NULL;
  1264. if (!StartServiceCtrlDispatcher(table))
  1265. printf("Error was %d\n",GetLastError());
  1266. }
  1267. #endif
  1268. int tor_main(int argc, char *argv[]) {
  1269. #ifdef MS_WINDOWS_SERVICE
  1270. nt_service_main();
  1271. return 0;
  1272. #else
  1273. if (tor_init(argc, argv)<0)
  1274. return -1;
  1275. switch (options.command) {
  1276. case CMD_RUN_TOR:
  1277. do_main_loop();
  1278. break;
  1279. case CMD_LIST_FINGERPRINT:
  1280. do_list_fingerprint();
  1281. break;
  1282. case CMD_HASH_PASSWORD:
  1283. do_hash_password();
  1284. break;
  1285. default:
  1286. log_fn(LOG_ERR, "Illegal command number %d: internal error.",
  1287. options.command);
  1288. }
  1289. tor_cleanup();
  1290. return -1;
  1291. #endif
  1292. }
  1293. /*
  1294. Local Variables:
  1295. mode:c
  1296. indent-tabs-mode:nil
  1297. c-basic-offset:2
  1298. End:
  1299. */