main.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. /* Copyright 2001,2002 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "or.h"
  5. /********* START PROTOTYPES **********/
  6. static void dumpstats(void); /* dump stats to stdout */
  7. static int init_descriptor(void);
  8. /********* START VARIABLES **********/
  9. extern char *conn_type_to_string[];
  10. extern char *conn_state_to_string[][_CONN_TYPE_MAX+1];
  11. or_options_t options; /* command-line and config-file options */
  12. int global_read_bucket; /* max number of bytes I can read this second */
  13. static connection_t *connection_array[MAXCONNECTIONS] =
  14. { NULL };
  15. static struct pollfd poll_array[MAXCONNECTIONS];
  16. static int nfds=0; /* number of connections currently active */
  17. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  18. static int please_dumpstats=0; /* whether we should dump stats during the loop */
  19. static int please_reset =0; /* whether we just got a sighup */
  20. static int please_reap_children=0; /* whether we should waitpid for exited children*/
  21. #endif /* signal stuff */
  22. /* private keys */
  23. static crypto_pk_env_t *onionkey=NULL;
  24. static crypto_pk_env_t *linkkey=NULL;
  25. static crypto_pk_env_t *identitykey=NULL;
  26. routerinfo_t *my_routerinfo=NULL;
  27. /********* END VARIABLES ************/
  28. void set_onion_key(crypto_pk_env_t *k) {
  29. onionkey = k;
  30. }
  31. crypto_pk_env_t *get_onion_key(void) {
  32. assert(onionkey);
  33. return onionkey;
  34. }
  35. void set_link_key(crypto_pk_env_t *k)
  36. {
  37. linkkey = k;
  38. }
  39. crypto_pk_env_t *get_link_key(void)
  40. {
  41. assert(linkkey);
  42. return linkkey;
  43. }
  44. void set_identity_key(crypto_pk_env_t *k) {
  45. identitykey = k;
  46. }
  47. crypto_pk_env_t *get_identity_key(void) {
  48. assert(identitykey);
  49. return identitykey;
  50. }
  51. /****************************************************************************
  52. *
  53. * This section contains accessors and other methods on the connection_array
  54. * and poll_array variables (which are global within this file and unavailable
  55. * outside it).
  56. *
  57. ****************************************************************************/
  58. int connection_add(connection_t *conn) {
  59. if(nfds >= options.MaxConn-1) {
  60. log(LOG_INFO,"connection_add(): failing because nfds is too high.");
  61. return -1;
  62. }
  63. conn->poll_index = nfds;
  64. connection_set_poll_socket(conn);
  65. connection_array[nfds] = conn;
  66. /* zero these out here, because otherwise we'll inherit values from the previously freed one */
  67. poll_array[nfds].events = 0;
  68. poll_array[nfds].revents = 0;
  69. nfds++;
  70. log(LOG_INFO,"connection_add(): new conn type %d, socket %d, nfds %d.",conn->type, conn->s, nfds);
  71. return 0;
  72. }
  73. void connection_set_poll_socket(connection_t *conn) {
  74. poll_array[conn->poll_index].fd = conn->s;
  75. }
  76. int connection_remove(connection_t *conn) {
  77. int current_index;
  78. assert(conn);
  79. assert(nfds>0);
  80. log(LOG_INFO,"connection_remove(): removing socket %d, nfds now %d",conn->s, nfds-1);
  81. circuit_about_to_close_connection(conn); /* if it's an edge conn, remove it from the list
  82. * of conn's on this circuit. If it's not on an edge,
  83. * flush and send destroys for all circuits on this conn
  84. */
  85. current_index = conn->poll_index;
  86. if(current_index == nfds-1) { /* this is the end */
  87. nfds--;
  88. return 0;
  89. }
  90. /* we replace this one with the one at the end, then free it */
  91. nfds--;
  92. poll_array[current_index].fd = poll_array[nfds].fd;
  93. poll_array[current_index].events = poll_array[nfds].events;
  94. poll_array[current_index].revents = poll_array[nfds].revents;
  95. connection_array[current_index] = connection_array[nfds];
  96. connection_array[current_index]->poll_index = current_index;
  97. return 0;
  98. }
  99. connection_t *connection_twin_get_by_addr_port(uint32_t addr, uint16_t port) {
  100. /* Find a connection to the router described by addr and port,
  101. * or alternately any router which knows its key.
  102. * This connection *must* be in 'open' state.
  103. * If not, return NULL.
  104. */
  105. int i;
  106. connection_t *conn;
  107. routerinfo_t *router;
  108. /* first check if it's there exactly */
  109. conn = connection_exact_get_by_addr_port(addr,port);
  110. if(conn && connection_state_is_open(conn)) {
  111. log(LOG_INFO,"connection_twin_get_by_addr_port(): Found exact match.");
  112. return conn;
  113. }
  114. /* now check if any of the other open connections are a twin for this one */
  115. router = router_get_by_addr_port(addr,port);
  116. if(!router)
  117. return NULL;
  118. for(i=0;i<nfds;i++) {
  119. conn = connection_array[i];
  120. assert(conn);
  121. if(connection_state_is_open(conn) &&
  122. !conn->marked_for_close &&
  123. !crypto_pk_cmp_keys(conn->onion_pkey, router->onion_pkey)) {
  124. log(LOG_INFO,"connection_twin_get_by_addr_port(): Found twin (%s).",conn->address);
  125. return conn;
  126. }
  127. }
  128. /* guess not */
  129. return NULL;
  130. }
  131. connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
  132. int i;
  133. connection_t *conn;
  134. for(i=0;i<nfds;i++) {
  135. conn = connection_array[i];
  136. if(conn->addr == addr && conn->port == port && !conn->marked_for_close)
  137. return conn;
  138. }
  139. return NULL;
  140. }
  141. connection_t *connection_get_by_type(int type) {
  142. int i;
  143. connection_t *conn;
  144. for(i=0;i<nfds;i++) {
  145. conn = connection_array[i];
  146. if(conn->type == type && !conn->marked_for_close)
  147. return conn;
  148. }
  149. return NULL;
  150. }
  151. connection_t *connection_get_by_type_state(int type, int state) {
  152. int i;
  153. connection_t *conn;
  154. for(i=0;i<nfds;i++) {
  155. conn = connection_array[i];
  156. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  157. return conn;
  158. }
  159. return NULL;
  160. }
  161. connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
  162. int i;
  163. connection_t *conn, *best=NULL;
  164. for(i=0;i<nfds;i++) {
  165. conn = connection_array[i];
  166. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  167. if(!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  168. best = conn;
  169. }
  170. return best;
  171. }
  172. void connection_watch_events(connection_t *conn, short events) {
  173. assert(conn && conn->poll_index < nfds);
  174. poll_array[conn->poll_index].events = events;
  175. }
  176. int connection_is_reading(connection_t *conn) {
  177. return poll_array[conn->poll_index].events & POLLIN;
  178. }
  179. void connection_stop_reading(connection_t *conn) {
  180. assert(conn && conn->poll_index < nfds);
  181. log(LOG_DEBUG,"connection_stop_reading() called.");
  182. if(poll_array[conn->poll_index].events & POLLIN)
  183. poll_array[conn->poll_index].events -= POLLIN;
  184. }
  185. void connection_start_reading(connection_t *conn) {
  186. assert(conn && conn->poll_index < nfds);
  187. poll_array[conn->poll_index].events |= POLLIN;
  188. }
  189. void connection_stop_writing(connection_t *conn) {
  190. assert(conn && conn->poll_index < nfds);
  191. if(poll_array[conn->poll_index].events & POLLOUT)
  192. poll_array[conn->poll_index].events -= POLLOUT;
  193. }
  194. void connection_start_writing(connection_t *conn) {
  195. assert(conn && conn->poll_index < nfds);
  196. poll_array[conn->poll_index].events |= POLLOUT;
  197. }
  198. static void conn_read(int i) {
  199. connection_t *conn;
  200. if(!(poll_array[i].revents & (POLLIN|POLLHUP|POLLERR)))
  201. return; /* this conn doesn't want to read */
  202. /* see http://www.greenend.org.uk/rjk/2001/06/poll.html for
  203. * discussion of POLLIN vs POLLHUP */
  204. conn = connection_array[i];
  205. log_fn(LOG_DEBUG,"socket %d wants to read.",conn->s);
  206. assert_connection_ok(conn, time(NULL));
  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. {
  214. /* this connection is broken. remove it */
  215. log_fn(LOG_INFO,"%s connection broken, removing.", conn_type_to_string[conn->type]);
  216. connection_remove(conn);
  217. connection_free(conn);
  218. if(i<nfds) { /* we just replaced the one at i with a new one. process it too. */
  219. conn_read(i);
  220. }
  221. } else assert_connection_ok(conn, time(NULL));
  222. }
  223. static void conn_write(int i) {
  224. connection_t *conn;
  225. if(!(poll_array[i].revents & POLLOUT))
  226. return; /* this conn doesn't want to write */
  227. conn = connection_array[i];
  228. log_fn(LOG_DEBUG,"socket %d wants to write.",conn->s);
  229. assert_connection_ok(conn, time(NULL));
  230. if(connection_handle_write(conn) < 0) { /* this connection is broken. remove it. */
  231. log_fn(LOG_DEBUG,"%s connection broken, removing.", conn_type_to_string[conn->type]);
  232. connection_remove(conn);
  233. connection_free(conn);
  234. if(i<nfds) { /* we just replaced the one at i with a new one. process it too. */
  235. conn_write(i);
  236. }
  237. } else assert_connection_ok(conn, time(NULL));
  238. }
  239. static void check_conn_marked(int i) {
  240. connection_t *conn;
  241. conn = connection_array[i];
  242. assert_connection_ok(conn, time(NULL));
  243. if(conn->marked_for_close) {
  244. log_fn(LOG_DEBUG,"Cleaning up connection.");
  245. if(conn->s >= 0) { /* might be an incomplete edge connection */
  246. /* FIXME there's got to be a better way to check for this -- and make other checks? */
  247. if(connection_speaks_cells(conn)) {
  248. if(conn->state == OR_CONN_STATE_OPEN)
  249. flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  250. } else {
  251. flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  252. }
  253. if(connection_wants_to_flush(conn)) /* not done flushing */
  254. log_fn(LOG_WARNING,"Conn (socket %d) still wants to flush. Losing %d bytes!",conn->s, (int)buf_datalen(conn->inbuf));
  255. }
  256. connection_remove(conn);
  257. connection_free(conn);
  258. if(i<nfds) { /* we just replaced the one at i with a new one.
  259. process it too. */
  260. check_conn_marked(i);
  261. }
  262. }
  263. }
  264. static int prepare_for_poll(void) {
  265. int i;
  266. connection_t *conn;
  267. struct timeval now; //soonest;
  268. static long current_second = 0; /* from previous calls to gettimeofday */
  269. static long time_to_fetch_directory = 0;
  270. static long time_to_new_circuit = 0;
  271. // int ms_until_conn;
  272. cell_t cell;
  273. circuit_t *circ;
  274. my_gettimeofday(&now);
  275. if(now.tv_sec > current_second) { /* the second has rolled over. check more stuff. */
  276. if(!options.DirPort) {
  277. if(time_to_fetch_directory < now.tv_sec) {
  278. /* it's time to fetch a new directory */
  279. /* NOTE directory servers do not currently fetch directories.
  280. * Hope this doesn't bite us later.
  281. */
  282. directory_initiate_command(router_pick_directory_server(),
  283. DIR_CONN_STATE_CONNECTING_FETCH);
  284. time_to_fetch_directory = now.tv_sec + options.DirFetchPeriod;
  285. }
  286. }
  287. if(options.APPort && time_to_new_circuit < now.tv_sec) {
  288. circuit_expire_unused_circuits();
  289. circuit_launch_new(-1); /* tell it to forget about previous failures */
  290. circ = circuit_get_newest_open();
  291. if(!circ || circ->dirty) {
  292. log_fn(LOG_INFO,"Youngest circuit %s; launching replacement.", circ ? "dirty" : "missing");
  293. circuit_launch_new(0); /* make an onion and lay the circuit */
  294. }
  295. time_to_new_circuit = now.tv_sec + options.NewCircuitPeriod;
  296. }
  297. if(global_read_bucket < 9*options.TotalBandwidth) {
  298. global_read_bucket += options.TotalBandwidth;
  299. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  300. }
  301. /* do housekeeping for each connection */
  302. for(i=0;i<nfds;i++) {
  303. conn = connection_array[i];
  304. if(connection_receiver_bucket_should_increase(conn)) {
  305. conn->receiver_bucket += conn->bandwidth;
  306. // log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  307. }
  308. if(conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  309. && global_read_bucket > 0 /* and we're allowed to read */
  310. && conn->receiver_bucket != 0) { /* and either an edge conn or non-empty bucket */
  311. conn->wants_to_read = 0;
  312. connection_start_reading(conn);
  313. if(conn->wants_to_write == 1) {
  314. conn->wants_to_write = 0;
  315. connection_start_writing(conn);
  316. }
  317. }
  318. /* check connections to see whether we should send a keepalive, expire, or wait */
  319. if(!connection_speaks_cells(conn))
  320. continue; /* this conn type doesn't send cells */
  321. if(now.tv_sec >= conn->timestamp_lastwritten + options.KeepalivePeriod) {
  322. if((!options.OnionRouter && !circuit_get_by_conn(conn)) ||
  323. (!connection_state_is_open(conn))) {
  324. /* we're an onion proxy, with no circuits; or our handshake has expired. kill it. */
  325. log_fn(LOG_DEBUG,"Expiring connection to %d (%s:%d).",
  326. i,conn->address, conn->port);
  327. conn->marked_for_close = 1;
  328. } else {
  329. /* either a full router, or we've got a circuit. send a padding cell. */
  330. // log_fn(LOG_DEBUG,"Sending keepalive to (%s:%d)",
  331. // conn->address, conn->port);
  332. memset(&cell,0,sizeof(cell_t));
  333. cell.command = CELL_PADDING;
  334. if(connection_write_cell_to_buf(&cell, conn) < 0)
  335. conn->marked_for_close = 1;
  336. }
  337. }
  338. }
  339. /* blow away any connections that need to die. can't do this later
  340. * because we might open up a circuit and not realize it we're about to cull it.
  341. */
  342. for(i=0;i<nfds;i++)
  343. check_conn_marked(i);
  344. current_second = now.tv_sec; /* remember which second it is, for next time */
  345. }
  346. return (1000 - (now.tv_usec / 1000)); /* how many milliseconds til the next second? */
  347. }
  348. #define FN_ERROR -1
  349. #define FN_NOENT 0
  350. #define FN_FILE 1
  351. #define FN_DIR 2
  352. static int fn_exists(const char *fname)
  353. {
  354. struct stat st;
  355. if (stat(fname, &st)) {
  356. if (errno == ENOENT) {
  357. return FN_NOENT;
  358. }
  359. return FN_ERROR;
  360. }
  361. if (st.st_mode & S_IFDIR)
  362. return FN_DIR;
  363. else
  364. return FN_FILE;
  365. }
  366. static crypto_pk_env_t *init_key_from_file(const char *fname)
  367. {
  368. crypto_pk_env_t *prkey = NULL;
  369. int fd = -1;
  370. FILE *file = NULL;
  371. if (!(prkey = crypto_new_pk_env(CRYPTO_PK_RSA))) {
  372. log(LOG_ERR, "Error creating crypto environment.");
  373. goto error;
  374. }
  375. switch(fn_exists(fname)) {
  376. case FN_DIR:
  377. case FN_ERROR:
  378. log(LOG_ERR, "Can't read key from %s", fname);
  379. goto error;
  380. case FN_NOENT:
  381. log(LOG_INFO, "No key found in %s; generating fresh key.", fname);
  382. if (crypto_pk_generate_key(prkey)) {
  383. log(LOG_ERR, "Error generating key: %s", crypto_perror());
  384. goto error;
  385. }
  386. if (crypto_pk_check_key(prkey) <= 0) {
  387. log(LOG_ERR, "Generated key seems invalid");
  388. goto error;
  389. }
  390. log(LOG_INFO, "Generated key seems valid");
  391. fd = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0400);
  392. if (fd == -1) {
  393. log(LOG_ERR, "Can't open %s for writing", fname);
  394. goto error;
  395. }
  396. file = fdopen(fd, "w");
  397. if (!file) {
  398. log(LOG_ERR, "Can't fdopen %s for writing", fname);
  399. goto error;
  400. }
  401. if (crypto_pk_write_private_key_to_file(prkey, file) < 0) {
  402. log(LOG_ERR, "Can't write private key to %s", fname);
  403. goto error;
  404. }
  405. fclose(file);
  406. /* XXX fingerprint */
  407. return prkey;
  408. case FN_FILE:
  409. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  410. log(LOG_ERR, "Error loading private key.");
  411. goto error;
  412. }
  413. return prkey;
  414. default:
  415. assert(0);
  416. }
  417. error:
  418. if (prkey)
  419. crypto_free_pk_env(prkey);
  420. if (fd >= 0 && !file)
  421. close(fd);
  422. if (file)
  423. fclose(file);
  424. return NULL;
  425. }
  426. static int init_keys(void)
  427. {
  428. char keydir[512];
  429. char fingerprint[FINGERPRINT_LEN+1];
  430. char *cp;
  431. crypto_pk_env_t *prkey;
  432. FILE *file;
  433. /* OP's don't need keys. Just initialize the TLS context.*/
  434. if (!options.OnionRouter && !options.DirPort) {
  435. if (tor_tls_context_new(NULL, 0, NULL)<0) {
  436. log_fn(LOG_ERR, "Error creating TLS context for OP.");
  437. return -1;
  438. }
  439. return 0;
  440. }
  441. assert(options.DataDirectory);
  442. if (strlen(options.DataDirectory) > (512-128)) {
  443. log_fn(LOG_ERR, "DataDirectory is too long.");
  444. return -1;
  445. }
  446. strcpy(keydir, options.DataDirectory);
  447. switch (fn_exists(keydir)) {
  448. case FN_NOENT:
  449. log_fn(LOG_ERR, "DataDirectory does not exist");
  450. return -1;
  451. case FN_ERROR:
  452. log_fn(LOG_ERR, "DataDirectory can't be read");
  453. return -1;
  454. case FN_FILE:
  455. log_fn(LOG_ERR, "DataDirectory is not a directory.");
  456. return -1;
  457. }
  458. strcat(keydir, "/keys");
  459. switch (fn_exists(keydir)) {
  460. case FN_NOENT:
  461. if (mkdir(keydir, 0700)) {
  462. log_fn(LOG_ERR, "Error making key directory.");
  463. return -1;
  464. }
  465. break;
  466. case FN_ERROR:
  467. log_fn(LOG_ERR, "Error reading key directory.");
  468. return -1;
  469. case FN_FILE:
  470. log_fn(LOG_ERR, "Key directory is not a directory.");
  471. return -1;
  472. case FN_DIR:
  473. chmod(keydir, 0700);
  474. break;
  475. }
  476. cp = keydir + strlen(keydir); /* End of string. */
  477. assert(!*cp);
  478. /* 1. Read identity key. Make it if none is found. */
  479. strcat(keydir, "/identity.key");
  480. prkey = init_key_from_file(keydir);
  481. if (!prkey) return -1;
  482. set_identity_key(prkey);
  483. /* 2. Read onion key. Make it if none is found. */
  484. *cp = '\0';
  485. strcat(keydir, "/onion.key");
  486. prkey = init_key_from_file(keydir);
  487. if (!prkey) return -1;
  488. set_onion_key(prkey);
  489. /* 3. Initialize link key and TLS context. */
  490. *cp = '\0';
  491. strcat(keydir, "/link.key");
  492. prkey = init_key_from_file(keydir);
  493. if (!prkey) return -1;
  494. set_link_key(prkey);
  495. if (tor_tls_context_new(prkey, 1, options.Nickname) < 0) {
  496. log_fn(LOG_ERR, "Error initializing TLS context");
  497. return -1;
  498. }
  499. /* 4. Dump router descriptor to 'router.desc' */
  500. /* Must be called after keys are initialized. */
  501. if (init_descriptor()<0) {
  502. log_fn(LOG_ERR, "Error initializing descriptor.");
  503. return -1;
  504. }
  505. strcpy(keydir, options.DataDirectory);
  506. strcat(keydir, "/router.desc");
  507. file = fopen(keydir, "w");
  508. if (!file) {
  509. log_fn(LOG_ERR, "Error opening %s for writing", keydir);
  510. return -1;
  511. }
  512. fputs(router_get_my_descriptor(), file);
  513. fclose(file);
  514. /* 5. Dump fingerprint to 'fingerprint' */
  515. strcpy(keydir, options.DataDirectory);
  516. strcat(keydir, "/fingerprint");
  517. file = fopen(keydir, "w");
  518. if (!file) {
  519. log_fn(LOG_ERR, "Error opening %s for writing", keydir);
  520. return -1;
  521. }
  522. if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint)<0) {
  523. log_fn(LOG_ERR, "Error computing fingerprint");
  524. return -1;
  525. }
  526. fprintf(file, "%s %s\n", options.Nickname, fingerprint);
  527. fclose(file);
  528. return 0;
  529. }
  530. static int do_main_loop(void) {
  531. int i;
  532. int timeout;
  533. int poll_result;
  534. /* load the routers file */
  535. if(router_get_list_from_file(options.RouterFile) < 0) {
  536. log_fn(LOG_ERR,"Error loading router list.");
  537. return -1;
  538. }
  539. /* load the private keys, if we're supposed to have them, and set up the
  540. * TLS context. */
  541. if (init_keys() < 0) {
  542. log_fn(LOG_ERR,"Error initializing keys; exiting");
  543. return -1;
  544. }
  545. if(options.OnionRouter) {
  546. cpu_init(); /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  547. if(options.DirPort == 0) /* not a dirserver; XXX eventually do this for dirservers too */
  548. router_upload_desc_to_dirservers(); /* upload our descriptor to all dirservers */
  549. }
  550. /* start up the necessary connections based on which ports are
  551. * non-zero. This is where we try to connect to all the other ORs,
  552. * and start the listeners.
  553. */
  554. retry_all_connections((uint16_t) options.ORPort,
  555. (uint16_t) options.APPort,
  556. (uint16_t) options.DirPort);
  557. for(;;) {
  558. #ifndef MS_WIN32 /* do signal stuff only on unix */
  559. if(please_dumpstats) {
  560. dumpstats();
  561. please_dumpstats = 0;
  562. }
  563. if(please_reset) {
  564. /* fetch a new directory */
  565. if(options.DirPort) {
  566. if(router_get_list_from_file(options.RouterFile) < 0) {
  567. log(LOG_ERR,"Error reloading router list. Continuing with old list.");
  568. }
  569. } else {
  570. directory_initiate_command(router_pick_directory_server(), DIR_CONN_STATE_CONNECTING_FETCH);
  571. }
  572. /* close and reopen the log files */
  573. reset_logs();
  574. please_reset = 0;
  575. }
  576. if(please_reap_children) {
  577. while(waitpid(-1,NULL,WNOHANG)) ; /* keep reaping until no more zombies */
  578. please_reap_children = 0;
  579. }
  580. #endif /* signal stuff */
  581. timeout = prepare_for_poll();
  582. /* poll until we have an event, or the second ends */
  583. poll_result = poll(poll_array, nfds, timeout);
  584. #if 0 /* let catch() handle things like ^c, and otherwise don't worry about it */
  585. if(poll_result < 0) {
  586. log(LOG_ERR,"do_main_loop(): poll failed.");
  587. if(errno != EINTR) /* let the program survive things like ^z */
  588. return -1;
  589. }
  590. #endif
  591. if(poll_result > 0) { /* we have at least one connection to deal with */
  592. /* do all the reads and errors first, so we can detect closed sockets */
  593. for(i=0;i<nfds;i++)
  594. conn_read(i); /* this also blows away broken connections */
  595. /* then do the writes */
  596. for(i=0;i<nfds;i++)
  597. conn_write(i);
  598. /* any of the conns need to be closed now? */
  599. for(i=0;i<nfds;i++)
  600. check_conn_marked(i);
  601. }
  602. /* refilling buckets and sending cells happens at the beginning of the
  603. * next iteration of the loop, inside prepare_for_poll()
  604. */
  605. }
  606. }
  607. static void catch(int the_signal) {
  608. #ifndef MS_WIN32 /* do signal stuff only on unix */
  609. switch(the_signal) {
  610. // case SIGABRT:
  611. case SIGTERM:
  612. case SIGINT:
  613. log(LOG_NOTICE,"Catching signal %d, exiting cleanly.", the_signal);
  614. exit(0);
  615. case SIGHUP:
  616. please_reset = 1;
  617. break;
  618. case SIGUSR1:
  619. please_dumpstats = 1;
  620. break;
  621. case SIGCHLD:
  622. please_reap_children = 1;
  623. break;
  624. default:
  625. log(LOG_ERR,"Caught signal %d that we can't handle??", the_signal);
  626. }
  627. #endif /* signal stuff */
  628. }
  629. static void dumpstats(void) { /* dump stats to stdout */
  630. int i;
  631. connection_t *conn;
  632. struct timeval now;
  633. printf("Dumping stats:\n");
  634. my_gettimeofday(&now);
  635. for(i=0;i<nfds;i++) {
  636. conn = connection_array[i];
  637. printf("Conn %d (socket %d) type %d (%s), state %d (%s), created %ld secs ago\n",
  638. i, conn->s, conn->type, conn_type_to_string[conn->type],
  639. conn->state, conn_state_to_string[conn->type][conn->state], now.tv_sec - conn->timestamp_created);
  640. if(!connection_is_listener(conn)) {
  641. printf("Conn %d is to '%s:%d'.\n",i,conn->address, conn->port);
  642. printf("Conn %d: %d bytes waiting on inbuf (last read %ld secs ago)\n",i,
  643. (int)buf_datalen(conn->inbuf),
  644. now.tv_sec - conn->timestamp_lastread);
  645. printf("Conn %d: %d bytes waiting on outbuf (last written %ld secs ago)\n",i,(int)buf_datalen(conn->outbuf),
  646. now.tv_sec - conn->timestamp_lastwritten);
  647. }
  648. circuit_dump_by_conn(conn); /* dump info about all the circuits using this conn */
  649. printf("\n");
  650. }
  651. }
  652. int dump_router_to_string(char *s, int maxlen, routerinfo_t *router,
  653. crypto_pk_env_t *ident_key) {
  654. char *onion_pkey;
  655. char *link_pkey;
  656. char *identity_pkey;
  657. char digest[20];
  658. char signature[128];
  659. int onion_pkeylen, link_pkeylen, identity_pkeylen;
  660. int written;
  661. int result=0;
  662. struct exit_policy_t *tmpe;
  663. if(crypto_pk_write_public_key_to_string(router->onion_pkey,
  664. &onion_pkey,&onion_pkeylen)<0) {
  665. log_fn(LOG_ERR,"write onion_pkey to string failed!");
  666. return -1;
  667. }
  668. if(crypto_pk_write_public_key_to_string(router->identity_pkey,
  669. &identity_pkey,&identity_pkeylen)<0) {
  670. log_fn(LOG_ERR,"write identity_pkey to string failed!");
  671. return -1;
  672. }
  673. if(crypto_pk_write_public_key_to_string(router->link_pkey,
  674. &link_pkey,&link_pkeylen)<0) {
  675. log_fn(LOG_ERR,"write link_pkey to string failed!");
  676. return -1;
  677. }
  678. result = snprintf(s, maxlen,
  679. "router %s %d %d %d %d\nonion-key\n%s"
  680. "link-key\n%s"
  681. "signing-key\n%s",
  682. router->address,
  683. router->or_port,
  684. router->ap_port,
  685. router->dir_port,
  686. router->bandwidth,
  687. onion_pkey, link_pkey, identity_pkey);
  688. free(onion_pkey);
  689. free(link_pkey);
  690. free(identity_pkey);
  691. if(result < 0 || result > maxlen) {
  692. /* apparently different glibcs do different things on snprintf error.. so check both */
  693. return -1;
  694. }
  695. written = result;
  696. for(tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  697. result = snprintf(s+written, maxlen-written, "%s %s:%s\n",
  698. tmpe->policy_type == EXIT_POLICY_ACCEPT ? "accept" : "reject",
  699. tmpe->address, tmpe->port);
  700. if(result < 0 || result+written > maxlen) {
  701. /* apparently different glibcs do different things on snprintf error.. so check both */
  702. return -1;
  703. }
  704. written += result;
  705. }
  706. if (written > maxlen-256) /* Not enough room for signature. */
  707. return -1;
  708. strcat(s+written, "router-signature\n");
  709. written += strlen(s+written);
  710. s[written] = '\0';
  711. if (router_get_router_hash(s, digest) < 0)
  712. return -1;
  713. if (crypto_pk_private_sign(ident_key, digest, 20, signature) < 0) {
  714. log_fn(LOG_ERR, "Error signing digest");
  715. return -1;
  716. }
  717. strcat(s+written, "-----BEGIN SIGNATURE-----\n");
  718. written += strlen(s+written);
  719. if (base64_encode(s+written, maxlen-written, signature, 128) < 0) {
  720. log_fn(LOG_ERR, "Couldn't base64-encode signature");
  721. }
  722. written += strlen(s+written);
  723. strcat(s+written, "-----END SIGNATURE-----\n");
  724. written += strlen(s+written);
  725. if (written > maxlen-2)
  726. return -1;
  727. /* include a last '\n' */
  728. s[written] = '\n';
  729. s[written+1] = 0;
  730. return written+1;
  731. }
  732. static int
  733. build_directory(directory_t *dir) {
  734. routerinfo_t **routers = NULL;
  735. connection_t *conn;
  736. routerinfo_t *router;
  737. int i, n = 0;
  738. routers = (routerinfo_t **)tor_malloc(sizeof(routerinfo_t*) * (nfds+1));
  739. if (my_routerinfo) {
  740. log(LOG_INFO, "build_directory(): adding self (%s:%d)",
  741. my_routerinfo->address, my_routerinfo->or_port);
  742. routers[n++] = my_routerinfo;
  743. }
  744. for(i = 0; i<nfds; ++i) {
  745. conn = connection_array[i];
  746. if(conn->type != CONN_TYPE_OR)
  747. continue; /* we only want to list ORs */
  748. if(conn->state != OR_CONN_STATE_OPEN)
  749. continue; /* we only want to list ones that successfully handshaked */
  750. router = router_get_by_addr_port(conn->addr,conn->port);
  751. if(!router) {
  752. /* XXX this legitimately happens when conn is an OP. How to detect this? */
  753. log(LOG_ERR,"build_directory(): couldn't find router %d:%d!",
  754. conn->addr,conn->port);
  755. continue;
  756. }
  757. log(LOG_INFO, "build_directory(): adding router (%s:%d)",
  758. router->address, router->or_port);
  759. routers[n++] = router;
  760. }
  761. dir->routers = routers;
  762. dir->n_routers = n;
  763. return 0;
  764. }
  765. int
  766. dump_signed_directory_to_string(char *s, int maxlen,
  767. crypto_pk_env_t *private_key)
  768. {
  769. directory_t dir;
  770. if (build_directory(&dir)) {
  771. log(LOG_ERR,"dump_signed_directory_to_string(): build_directory failed.");
  772. return -1;
  773. }
  774. return dump_signed_directory_to_string_impl(s, maxlen, &dir, private_key);
  775. }
  776. int
  777. dump_signed_directory_to_string_impl(char *s, int maxlen, directory_t *dir,
  778. crypto_pk_env_t *private_key)
  779. {
  780. char *cp, *eos;
  781. char digest[20];
  782. char signature[128];
  783. int i, written;
  784. routerinfo_t *router;
  785. eos = s+maxlen;
  786. strncpy(s,
  787. "signed-directory\n"
  788. "recommended-software "
  789. RECOMMENDED_SOFTWARE_VERSIONS
  790. "\n"
  791. , maxlen);
  792. i = strlen(s);
  793. cp = s+i;
  794. for (i = 0; i < dir->n_routers; ++i) {
  795. router = dir->routers[i];
  796. /* XXX This is wrong; we shouldn't sign routers, but rather propagate
  797. * XXX the original router blocks, unaltered.
  798. */
  799. written = dump_router_to_string(cp, eos-cp, router, private_key);
  800. if(written < 0) {
  801. log(LOG_ERR,"dump_signed_directory_to_string(): tried to exceed string length.");
  802. cp[maxlen-1] = 0; /* make sure it's null terminated */
  803. free(dir->routers);
  804. return -1;
  805. }
  806. cp += written;
  807. }
  808. free(dir->routers); /* not needed anymore */
  809. /* These multiple strlen calls are inefficient, but dwarfed by the RSA
  810. signature.
  811. */
  812. i = strlen(s);
  813. strncat(s, "directory-signature\n", maxlen-i);
  814. i = strlen(s);
  815. cp = s + i;
  816. if (crypto_SHA_digest(s, i, digest)) {
  817. log(LOG_ERR,"dump_signed_directory_to_string(): couldn't compute digest");
  818. return -1;
  819. }
  820. if (crypto_pk_private_sign(private_key, digest, 20, signature) < 0) {
  821. log(LOG_ERR,"dump_signed_directory_to_string(): couldn't sign digest");
  822. return -1;
  823. }
  824. strncpy(cp,
  825. "-----BEGIN SIGNATURE-----\n", maxlen-i);
  826. i = strlen(s);
  827. cp = s+i;
  828. if (base64_encode(cp, maxlen-i, signature, 128) < 0) {
  829. log_fn(LOG_ERR," couldn't base64-encode signature");
  830. return -1;
  831. }
  832. i = strlen(s);
  833. cp = s+i;
  834. strncat(cp, "-----END SIGNATURE-----\n", maxlen-i);
  835. i = strlen(s);
  836. if (i == maxlen) {
  837. log(LOG_ERR,"dump_signed_directory_to_string(): tried to exceed string length.");
  838. return -1;
  839. }
  840. return 0;
  841. }
  842. static char descriptor[8192];
  843. /* XXX should this replace my_routerinfo? */
  844. static routerinfo_t *desc_routerinfo;
  845. const char *router_get_my_descriptor(void) {
  846. log_fn(LOG_DEBUG,"my desc is '%s'",descriptor);
  847. return descriptor;
  848. }
  849. static int init_descriptor(void) {
  850. routerinfo_t *ri;
  851. char localhostname[256];
  852. if(gethostname(localhostname,sizeof(localhostname)) < 0) {
  853. log_fn(LOG_ERR,"Error obtaining local hostname");
  854. return -1;
  855. }
  856. ri = tor_malloc(sizeof(routerinfo_t));
  857. ri->address = strdup(localhostname);
  858. ri->nickname = strdup(options.Nickname);
  859. /* No need to set addr. ???? */
  860. ri->or_port = options.ORPort;
  861. ri->ap_port = options.APPort;
  862. ri->dir_port = options.DirPort;
  863. ri->onion_pkey = crypto_pk_dup_key(get_onion_key());
  864. ri->link_pkey = crypto_pk_dup_key(get_link_key());
  865. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  866. ri->bandwidth = options.TotalBandwidth;
  867. ri->exit_policy = NULL; /* XXX implement this. */
  868. if (desc_routerinfo)
  869. routerinfo_free(desc_routerinfo);
  870. desc_routerinfo = ri;
  871. if (dump_router_to_string(descriptor, 8192, ri, get_identity_key())<0) {
  872. log_fn(LOG_ERR, "Couldn't dump router to string.");
  873. return -1;
  874. }
  875. return 0;
  876. }
  877. void daemonize(void) {
  878. #ifndef MS_WINDOWS
  879. /* Fork; parent exits. */
  880. if (fork())
  881. exit(0);
  882. /* Create new session; make sure we never get a terminal */
  883. setsid();
  884. if (fork())
  885. exit(0);
  886. chdir("/");
  887. umask(000);
  888. fclose(stdin);
  889. fclose(stdout); /* XXX Nick: this closes our log, right? is it safe to leave this open? */
  890. fclose(stderr);
  891. #endif
  892. }
  893. int tor_main(int argc, char *argv[]) {
  894. int retval = 0;
  895. if(getconfig(argc,argv,&options))
  896. exit(1);
  897. log_set_severity(options.loglevel); /* assign logging severity level from options */
  898. global_read_bucket = options.TotalBandwidth; /* start it at 1 second of traffic */
  899. if(options.Daemon)
  900. daemonize();
  901. if(options.OnionRouter) { /* only spawn dns handlers if we're a router */
  902. dns_init(); /* initialize the dns resolve tree, and spawn workers */
  903. }
  904. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  905. signal (SIGINT, catch); /* catch kills so we can exit cleanly */
  906. signal (SIGTERM, catch);
  907. signal (SIGUSR1, catch); /* to dump stats to stdout */
  908. signal (SIGHUP, catch); /* to reload directory */
  909. signal (SIGCHLD, catch); /* for exiting dns/cpu workers */
  910. #endif /* signal stuff */
  911. crypto_global_init();
  912. crypto_seed_rng();
  913. retval = do_main_loop();
  914. crypto_global_cleanup();
  915. return retval;
  916. }
  917. /*
  918. Local Variables:
  919. mode:c
  920. indent-tabs-mode:nil
  921. c-basic-offset:2
  922. End:
  923. */