main.c 38 KB

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