1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008 |
- const char main_c_id[] =
- "$Id$";
- #define MAIN_PRIVATE
- #include "or.h"
- #ifdef USE_DMALLOC
- #include <dmalloc.h>
- #endif
- void evdns_shutdown(int);
- static void dumpmemusage(int severity);
- static void dumpstats(int severity);
- static void conn_read_callback(int fd, short event, void *_conn);
- static void conn_write_callback(int fd, short event, void *_conn);
- static void signal_callback(int fd, short events, void *arg);
- static void second_elapsed_callback(int fd, short event, void *args);
- static int conn_close_if_marked(int i);
- static void connection_start_reading_from_linked_conn(connection_t *conn);
- static int connection_should_read_from_linked_conn(connection_t *conn);
- int global_read_bucket;
- int global_write_bucket;
- int global_relayed_read_bucket;
- int global_relayed_write_bucket;
- static int stats_prev_global_read_bucket;
- static int stats_prev_global_write_bucket;
- static uint64_t stats_n_bytes_read = 0;
- static uint64_t stats_n_bytes_written = 0;
- time_t time_of_process_start = 0;
- long stats_n_seconds_working = 0;
- static time_t time_to_check_for_correct_dns = 0;
- #define MAX_SIGNEWNYM_RATE 10
- static time_t time_of_last_signewnym = 0;
- static int signewnym_is_pending = 0;
- static smartlist_t *connection_array = NULL;
- static smartlist_t *closeable_connection_lst = NULL;
- static smartlist_t *active_linked_connection_lst = NULL;
- static int called_loop_once = 0;
- int has_completed_circuit=0;
- #define GREEDY_DESCRIPTOR_RETRY_INTERVAL (10)
- #define LAZY_DESCRIPTOR_RETRY_INTERVAL (60)
- #define DESCRIPTOR_FAILURE_RESET_INTERVAL (60*60)
- #define DIR_CONN_MAX_STALL (5*60)
- #define TIME_BEFORE_OR_CONN_IS_OBSOLETE (60*60*24*7)
- #define TLS_HANDSHAKE_TIMEOUT (60)
- int
- connection_add(connection_t *conn)
- {
- tor_assert(conn);
- tor_assert(conn->s >= 0 ||
- conn->linked ||
- (conn->type == CONN_TYPE_AP &&
- TO_EDGE_CONN(conn)->is_dns_request));
- tor_assert(conn->conn_array_index == -1);
- conn->conn_array_index = smartlist_len(connection_array);
- smartlist_add(connection_array, conn);
- if (conn->s >= 0 || conn->linked) {
- conn->read_event = tor_malloc_zero(sizeof(struct event));
- conn->write_event = tor_malloc_zero(sizeof(struct event));
- event_set(conn->read_event, conn->s, EV_READ|EV_PERSIST,
- conn_read_callback, conn);
- event_set(conn->write_event, conn->s, EV_WRITE|EV_PERSIST,
- conn_write_callback, conn);
- }
- log_debug(LD_NET,"new conn type %s, socket %d, n_conns %d.",
- conn_type_to_string(conn->type), conn->s,
- smartlist_len(connection_array));
- return 0;
- }
- int
- connection_remove(connection_t *conn)
- {
- int current_index;
- connection_t *tmp;
- tor_assert(conn);
- log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
- conn->s, conn_type_to_string(conn->type),
- smartlist_len(connection_array));
- tor_assert(conn->conn_array_index >= 0);
- current_index = conn->conn_array_index;
- connection_unregister_events(conn);
- if (current_index == smartlist_len(connection_array)-1) {
- smartlist_del(connection_array, current_index);
- return 0;
- }
-
- smartlist_del(connection_array, current_index);
- tmp = smartlist_get(connection_array, current_index);
- tmp->conn_array_index = current_index;
- return 0;
- }
- static void
- connection_unlink(connection_t *conn)
- {
- connection_about_to_close_connection(conn);
- if (conn->conn_array_index >= 0) {
- connection_remove(conn);
- }
- if (conn->linked_conn) {
- conn->linked_conn->linked_conn = NULL;
- if (! conn->linked_conn->marked_for_close &&
- conn->linked_conn->reading_from_linked_conn)
- connection_start_reading(conn->linked_conn);
- conn->linked_conn = NULL;
- }
- smartlist_remove(closeable_connection_lst, conn);
- smartlist_remove(active_linked_connection_lst, conn);
- if (conn->type == CONN_TYPE_EXIT) {
- assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
- }
- if (conn->type == CONN_TYPE_OR) {
- if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
- connection_or_remove_from_identity_map(TO_OR_CONN(conn));
- }
- connection_free(conn);
- }
- void
- add_connection_to_closeable_list(connection_t *conn)
- {
- tor_assert(!smartlist_isin(closeable_connection_lst, conn));
- tor_assert(conn->marked_for_close);
- assert_connection_ok(conn, time(NULL));
- smartlist_add(closeable_connection_lst, conn);
- }
- int
- connection_is_on_closeable_list(connection_t *conn)
- {
- return smartlist_isin(closeable_connection_lst, conn);
- }
- int
- connection_in_array(connection_t *conn)
- {
- return smartlist_isin(connection_array, conn);
- }
- smartlist_t *
- get_connection_array(void)
- {
- return connection_array;
- }
- void
- connection_watch_events(connection_t *conn, short events)
- {
- if (events & EV_READ)
- connection_start_reading(conn);
- else
- connection_stop_reading(conn);
- if (events & EV_WRITE)
- connection_start_writing(conn);
- else
- connection_stop_writing(conn);
- }
- int
- connection_is_reading(connection_t *conn)
- {
- tor_assert(conn);
- return conn->reading_from_linked_conn ||
- (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
- }
- void
- connection_stop_reading(connection_t *conn)
- {
- tor_assert(conn);
- tor_assert(conn->read_event);
- if (conn->linked) {
- conn->reading_from_linked_conn = 0;
- connection_stop_reading_from_linked_conn(conn);
- } else {
- if (event_del(conn->read_event))
- log_warn(LD_NET, "Error from libevent setting read event state for %d "
- "to unwatched: %s",
- conn->s,
- tor_socket_strerror(tor_socket_errno(conn->s)));
- }
- }
- void
- connection_start_reading(connection_t *conn)
- {
- tor_assert(conn);
- tor_assert(conn->read_event);
- if (conn->linked) {
- conn->reading_from_linked_conn = 1;
- if (connection_should_read_from_linked_conn(conn))
- connection_start_reading_from_linked_conn(conn);
- } else {
- if (event_add(conn->read_event, NULL))
- log_warn(LD_NET, "Error from libevent setting read event state for %d "
- "to watched: %s",
- conn->s,
- tor_socket_strerror(tor_socket_errno(conn->s)));
- }
- }
- int
- connection_is_writing(connection_t *conn)
- {
- tor_assert(conn);
- return conn->writing_to_linked_conn ||
- (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
- }
- void
- connection_stop_writing(connection_t *conn)
- {
- tor_assert(conn);
- tor_assert(conn->write_event);
- if (conn->linked) {
- conn->writing_to_linked_conn = 0;
- if (conn->linked_conn)
- connection_stop_reading_from_linked_conn(conn->linked_conn);
- } else {
- if (event_del(conn->write_event))
- log_warn(LD_NET, "Error from libevent setting write event state for %d "
- "to unwatched: %s",
- conn->s,
- tor_socket_strerror(tor_socket_errno(conn->s)));
- }
- }
- void
- connection_start_writing(connection_t *conn)
- {
- tor_assert(conn);
- tor_assert(conn->write_event);
- if (conn->linked) {
- conn->writing_to_linked_conn = 1;
- if (conn->linked_conn &&
- connection_should_read_from_linked_conn(conn->linked_conn))
- connection_start_reading_from_linked_conn(conn->linked_conn);
- } else {
- if (event_add(conn->write_event, NULL))
- log_warn(LD_NET, "Error from libevent setting write event state for %d "
- "to watched: %s",
- conn->s,
- tor_socket_strerror(tor_socket_errno(conn->s)));
- }
- }
- static int
- connection_should_read_from_linked_conn(connection_t *conn)
- {
- if (conn->linked && conn->reading_from_linked_conn) {
- if (! conn->linked_conn ||
- (conn->linked_conn->writing_to_linked_conn &&
- buf_datalen(conn->linked_conn->outbuf)))
- return 1;
- }
- return 0;
- }
- static void
- connection_start_reading_from_linked_conn(connection_t *conn)
- {
- tor_assert(conn);
- tor_assert(conn->linked == 1);
- if (!conn->active_on_link) {
- conn->active_on_link = 1;
- smartlist_add(active_linked_connection_lst, conn);
- if (!called_loop_once) {
-
- struct timeval tv = { 0, 0 };
- event_loopexit(&tv);
- }
- } else {
- tor_assert(smartlist_isin(active_linked_connection_lst, conn));
- }
- }
- void
- connection_stop_reading_from_linked_conn(connection_t *conn)
- {
- tor_assert(conn);
- tor_assert(conn->linked == 1);
- if (conn->active_on_link) {
- conn->active_on_link = 0;
-
- smartlist_remove(active_linked_connection_lst, conn);
- } else {
- tor_assert(!smartlist_isin(active_linked_connection_lst, conn));
- }
- }
- static void
- close_closeable_connections(void)
- {
- int i;
- for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
- connection_t *conn = smartlist_get(closeable_connection_lst, i);
- if (conn->conn_array_index < 0) {
- connection_unlink(conn);
- } else {
- if (!conn_close_if_marked(conn->conn_array_index))
- ++i;
- }
- }
- }
- static void
- conn_read_callback(int fd, short event, void *_conn)
- {
- connection_t *conn = _conn;
- (void)fd;
- (void)event;
- log_debug(LD_NET,"socket %d wants to read.",conn->s);
- assert_connection_ok(conn, time(NULL));
- if (connection_handle_read(conn) < 0) {
- if (!conn->marked_for_close) {
- #ifndef MS_WINDOWS
- log_warn(LD_BUG,"Unhandled error on read for %s connection "
- "(fd %d); removing",
- conn_type_to_string(conn->type), conn->s);
- tor_fragile_assert();
- #endif
- if (CONN_IS_EDGE(conn))
- connection_edge_end_errno(TO_EDGE_CONN(conn));
- connection_mark_for_close(conn);
- }
- }
- assert_connection_ok(conn, time(NULL));
- if (smartlist_len(closeable_connection_lst))
- close_closeable_connections();
- }
- static void
- conn_write_callback(int fd, short events, void *_conn)
- {
- connection_t *conn = _conn;
- (void)fd;
- (void)events;
- LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",conn->s));
- assert_connection_ok(conn, time(NULL));
- if (connection_handle_write(conn, 0) < 0) {
- if (!conn->marked_for_close) {
-
- log_fn(LOG_WARN,LD_BUG,
- "unhandled error on write for %s connection (fd %d); removing",
- conn_type_to_string(conn->type), conn->s);
- tor_fragile_assert();
- if (CONN_IS_EDGE(conn)) {
-
- edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
- if (!edge_conn->end_reason)
- edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
- conn->edge_has_sent_end = 1;
- }
- connection_close_immediate(conn);
- connection_mark_for_close(conn);
- }
- }
- assert_connection_ok(conn, time(NULL));
- if (smartlist_len(closeable_connection_lst))
- close_closeable_connections();
- }
- static int
- conn_close_if_marked(int i)
- {
- connection_t *conn;
- int retval;
- time_t now;
- conn = smartlist_get(connection_array, i);
- if (!conn->marked_for_close)
- return 0;
- now = time(NULL);
- assert_connection_ok(conn, now);
- assert_all_pending_dns_resolves_ok();
- log_debug(LD_NET,"Cleaning up connection (fd %d).",conn->s);
- if ((conn->s >= 0 || conn->linked_conn) && connection_wants_to_flush(conn)) {
-
- ssize_t sz = connection_bucket_write_limit(conn, now);
- if (!conn->hold_open_until_flushed)
- log_info(LD_NET,
- "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
- "to flush %d bytes. (Marked at %s:%d)",
- escaped_safe_str(conn->address),
- conn->s, conn_type_to_string(conn->type), conn->state,
- (int)conn->outbuf_flushlen,
- conn->marked_for_close_file, conn->marked_for_close);
- if (conn->linked_conn) {
- retval = move_buf_to_buf(conn->linked_conn->inbuf, conn->outbuf,
- &conn->outbuf_flushlen);
- if (retval >= 0) {
-
- connection_start_reading_from_linked_conn(conn->linked_conn);
- }
- log_debug(LD_GENERAL, "Flushed last %d bytes from a linked conn; "
- "%d left; flushlen %d; wants-to-flush==%d", retval,
- (int)buf_datalen(conn->outbuf),
- (int)conn->outbuf_flushlen,
- connection_wants_to_flush(conn));
- } else if (connection_speaks_cells(conn)) {
- if (conn->state == OR_CONN_STATE_OPEN) {
- retval = flush_buf_tls(TO_OR_CONN(conn)->tls, conn->outbuf, sz,
- &conn->outbuf_flushlen);
- } else
- retval = -1;
- } else {
- retval = flush_buf(conn->s, conn->outbuf, sz, &conn->outbuf_flushlen);
- }
- if (retval >= 0 &&
- conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
- if (retval > 0) {
- LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
- "Holding conn (fd %d) open for more flushing.",
- conn->s));
- conn->timestamp_lastwritten = now;
- }
- return 0;
- }
- if (connection_wants_to_flush(conn)) {
- int severity;
- if (conn->type == CONN_TYPE_EXIT ||
- (conn->type == CONN_TYPE_OR && server_mode(get_options())) ||
- (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER))
- severity = LOG_INFO;
- else
- severity = LOG_NOTICE;
-
- log_fn(severity, LD_NET, "We stalled too much while trying to write %d "
- "bytes to address %s. If this happens a lot, either "
- "something is wrong with your network connection, or "
- "something is wrong with theirs. "
- "(fd %d, type %s, state %d, marked at %s:%d).",
- (int)buf_datalen(conn->outbuf),
- escaped_safe_str(conn->address), conn->s,
- conn_type_to_string(conn->type), conn->state,
- conn->marked_for_close_file,
- conn->marked_for_close);
- }
- }
- connection_unlink(conn);
- return 1;
- }
- void
- directory_all_unreachable(time_t now)
- {
- connection_t *conn;
- (void)now;
- stats_n_seconds_working=0;
- while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
- AP_CONN_STATE_CIRCUIT_WAIT))) {
- edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
- log_notice(LD_NET,
- "Is your network connection down? "
- "Failing connection to '%s:%d'.",
- safe_str(edge_conn->socks_request->address),
- edge_conn->socks_request->port);
- connection_mark_unattached_ap(edge_conn,
- END_STREAM_REASON_NET_UNREACHABLE);
- }
- control_event_general_status(LOG_ERR, "DIR_ALL_UNREACHABLE");
- }
- void
- directory_info_has_arrived(time_t now, int from_cache)
- {
- or_options_t *options = get_options();
- if (!router_have_minimum_dir_info()) {
- log(LOG_NOTICE, LD_DIR,
- "I learned some more directory information, but not enough to "
- "build a circuit: %s", get_dir_info_status_string());
- update_router_descriptor_downloads(now);
- return;
- } else {
-
- entry_guards_compute_status();
-
- if (options->DownloadExtraInfo)
- update_extrainfo_downloads(now);
- }
- if (server_mode(options) && !we_are_hibernating() && !from_cache &&
- (has_completed_circuit || !any_predicted_circuits(now)))
- consider_testing_reachability(1, 1);
- }
- static void
- run_connection_housekeeping(int i, time_t now)
- {
- cell_t cell;
- connection_t *conn = smartlist_get(connection_array, i);
- or_options_t *options = get_options();
- or_connection_t *or_conn;
- if (conn->outbuf && !buf_datalen(conn->outbuf) && conn->type == CONN_TYPE_OR)
- TO_OR_CONN(conn)->timestamp_lastempty = now;
- if (conn->marked_for_close) {
-
- return;
- }
-
- if (conn->type == CONN_TYPE_DIR &&
- ((DIR_CONN_IS_SERVER(conn) &&
- conn->timestamp_lastwritten + DIR_CONN_MAX_STALL < now) ||
- (!DIR_CONN_IS_SERVER(conn) &&
- conn->timestamp_lastread + DIR_CONN_MAX_STALL < now))) {
- log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
- conn->s, conn->purpose);
-
- if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
- buf_datalen(conn->inbuf)>=1024) {
- log_info(LD_DIR,"Trying to extract information from wedged server desc "
- "download.");
- connection_dir_reached_eof(TO_DIR_CONN(conn));
- } else {
- connection_mark_for_close(conn);
- }
- return;
- }
- if (!connection_speaks_cells(conn))
- return;
- or_conn = TO_OR_CONN(conn);
- if (!conn->or_is_obsolete) {
- if (conn->timestamp_created + TIME_BEFORE_OR_CONN_IS_OBSOLETE < now) {
- log_info(LD_OR,
- "Marking OR conn to %s:%d obsolete (fd %d, %d secs old).",
- conn->address, conn->port, conn->s,
- (int)(now - conn->timestamp_created));
- conn->or_is_obsolete = 1;
- } else {
- or_connection_t *best =
- connection_or_get_by_identity_digest(or_conn->identity_digest);
- if (best && best != or_conn &&
- (conn->state == OR_CONN_STATE_OPEN ||
- now > conn->timestamp_created + TLS_HANDSHAKE_TIMEOUT)) {
-
- log_info(LD_OR,
- "Marking duplicate conn to %s:%d obsolete "
- "(fd %d, %d secs old).",
- conn->address, conn->port, conn->s,
- (int)(now - conn->timestamp_created));
- conn->or_is_obsolete = 1;
- }
- }
- }
- if (conn->or_is_obsolete && !or_conn->n_circuits) {
-
- log_info(LD_OR,
- "Expiring non-used OR connection to fd %d (%s:%d) [Obsolete].",
- conn->s, conn->address, conn->port);
- connection_mark_for_close(conn);
- conn->hold_open_until_flushed = 1;
- return;
- }
-
- if (now >= conn->timestamp_lastwritten + options->KeepalivePeriod) {
- routerinfo_t *router = router_get_by_digest(or_conn->identity_digest);
- int maxCircuitlessPeriod = options->MaxCircuitDirtiness*3/2;
- if (!connection_state_is_open(conn)) {
-
- log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
- conn->s,conn->address, conn->port);
- connection_mark_for_close(conn);
- conn->hold_open_until_flushed = 1;
- } else if (we_are_hibernating() && !or_conn->n_circuits &&
- !buf_datalen(conn->outbuf)) {
-
- log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
- "[Hibernating or exiting].",
- conn->s,conn->address, conn->port);
- connection_mark_for_close(conn);
- conn->hold_open_until_flushed = 1;
- } else if (!clique_mode(options) && !or_conn->n_circuits &&
- now >= or_conn->timestamp_last_added_nonpadding +
- maxCircuitlessPeriod &&
- (!router || !server_mode(options) ||
- !router_is_clique_mode(router))) {
- log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
- "[Not in clique mode].",
- conn->s,conn->address, conn->port);
- connection_mark_for_close(conn);
- conn->hold_open_until_flushed = 1;
- } else if (
- now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
- now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
- log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
- "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
- "flush; %d seconds since last write)",
- conn->s, conn->address, conn->port,
- (int)buf_datalen(conn->outbuf),
- (int)(now-conn->timestamp_lastwritten));
- connection_mark_for_close(conn);
- } else if (!buf_datalen(conn->outbuf)) {
-
- log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
- conn->address, conn->port);
- memset(&cell,0,sizeof(cell_t));
- cell.command = CELL_PADDING;
- connection_or_write_cell_to_buf(&cell, or_conn);
- }
- }
- }
- static void
- signewnym_impl(time_t now)
- {
- circuit_expire_all_dirty_circs();
- addressmap_clear_transient();
- time_of_last_signewnym = now;
- signewnym_is_pending = 0;
- }
- static void
- run_scheduled_events(time_t now)
- {
- static time_t time_to_fetch_directory = 0;
- static time_t time_to_fetch_running_routers = 0;
- static time_t last_rotated_x509_certificate = 0;
- static time_t time_to_check_v3_certificate = 0;
- static time_t time_to_check_listeners = 0;
- static time_t time_to_check_descriptor = 0;
- static time_t time_to_check_ipaddress = 0;
- static time_t time_to_shrink_memory = 0;
- static time_t time_to_try_getting_descriptors = 0;
- static time_t time_to_reset_descriptor_failures = 0;
- static time_t time_to_add_entropy = 0;
- static time_t time_to_write_hs_statistics = 0;
- static time_t time_to_write_bridge_status_file = 0;
- static time_t time_to_downrate_stability = 0;
- static time_t time_to_save_stability = 0;
- static time_t time_to_clean_caches = 0;
- static time_t time_to_recheck_bandwidth = 0;
- static time_t time_to_check_for_expired_networkstatus = 0;
- or_options_t *options = get_options();
- int i;
- int have_dir_info;
-
- consider_hibernation(now);
-
- if (signewnym_is_pending &&
- time_of_last_signewnym + MAX_SIGNEWNYM_RATE <= now) {
- log(LOG_INFO, LD_CONTROL, "Honoring delayed NEWNYM request");
- signewnym_impl(now);
- }
-
- if (server_mode(options) &&
- get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
- log_info(LD_GENERAL,"Rotating onion key.");
- rotate_onion_key();
- cpuworkers_rotate();
- if (router_rebuild_descriptor(1)<0) {
- log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
- }
- if (advertised_server_mode())
- router_upload_dir_desc_to_dirservers(0);
- }
- if (time_to_try_getting_descriptors < now) {
- update_router_descriptor_downloads(now);
- update_extrainfo_downloads(now);
- if (options->UseBridges)
- fetch_bridge_descriptors(now);
- if (router_have_minimum_dir_info())
- time_to_try_getting_descriptors = now + LAZY_DESCRIPTOR_RETRY_INTERVAL;
- else
- time_to_try_getting_descriptors = now + GREEDY_DESCRIPTOR_RETRY_INTERVAL;
- }
- if (time_to_reset_descriptor_failures < now) {
- router_reset_descriptor_download_failures();
- time_to_reset_descriptor_failures =
- now + DESCRIPTOR_FAILURE_RESET_INTERVAL;
- }
-
- if (!last_rotated_x509_certificate)
- last_rotated_x509_certificate = now;
- if (last_rotated_x509_certificate+MAX_SSL_KEY_LIFETIME < now) {
- log_info(LD_GENERAL,"Rotating tls context.");
- if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
- log_warn(LD_BUG, "Error reinitializing TLS context");
-
- }
- last_rotated_x509_certificate = now;
-
- }
- if (time_to_add_entropy < now) {
- if (time_to_add_entropy) {
-
- crypto_seed_rng(0);
- }
- #define ENTROPY_INTERVAL (60*60)
- time_to_add_entropy = now + ENTROPY_INTERVAL;
- }
-
- if (accounting_is_enabled(options))
- accounting_run_housekeeping(now);
- if (now % 10 == 0 && (authdir_mode_tests_reachability(options)) &&
- !we_are_hibernating()) {
-
- dirserv_test_reachability(now, 0);
- }
-
- if (time_to_downrate_stability < now)
- time_to_downrate_stability = rep_hist_downrate_old_runs(now);
- if (authdir_mode_tests_reachability(options)) {
- if (time_to_save_stability < now) {
- if (time_to_save_stability && rep_hist_record_mtbf_data()<0) {
- log_warn(LD_GENERAL, "Couldn't store mtbf data.");
- }
- #define SAVE_STABILITY_INTERVAL (30*60)
- time_to_save_stability = now + SAVE_STABILITY_INTERVAL;
- }
- }
-
- if (time_to_check_v3_certificate < now) {
- v3_authority_check_key_expiry();
- #define CHECK_V3_CERTIFICATE_INTERVAL (5*60)
- time_to_check_v3_certificate = now + CHECK_V3_CERTIFICATE_INTERVAL;
- }
-
- if (time_to_check_for_expired_networkstatus < now) {
- networkstatus_t *ns = networkstatus_get_latest_consensus();
-
- #define NS_EXPIRY_SLOP (24*60*60)
- if (ns && ns->valid_until < now+NS_EXPIRY_SLOP &&
- router_have_minimum_dir_info()) {
- router_dir_info_changed();
- }
- #define CHECK_EXPIRED_NS_INTERVAL (2*60)
- time_to_check_for_expired_networkstatus = now + CHECK_EXPIRED_NS_INTERVAL;
- }
-
- if (time_to_fetch_directory < now) {
-
- if (directory_fetches_dir_info_early(options) &&
- !authdir_mode_v1(options) && any_trusted_dir_is_v1_authority() &&
- !should_delay_dir_fetches(options))
- directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR,
- ROUTER_PURPOSE_GENERAL, NULL, 1);
- #define V1_DIR_FETCH_PERIOD (12*60*60)
- time_to_fetch_directory = now + V1_DIR_FETCH_PERIOD;
- }
-
- if (time_to_fetch_running_routers < now) {
- if (directory_fetches_dir_info_early(options) &&
- !authdir_mode_v1(options) && any_trusted_dir_is_v1_authority() &&
- !should_delay_dir_fetches(options))
- directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST,
- ROUTER_PURPOSE_GENERAL, NULL, 1);
- #define V1_RUNNINGROUTERS_FETCH_PERIOD (12*60*60)
- time_to_fetch_running_routers = now + V1_RUNNINGROUTERS_FETCH_PERIOD;
- }
-
- if (time_to_clean_caches < now) {
- rep_history_clean(now - options->RephistTrackTime);
- rend_cache_clean();
- rend_cache_clean_v2_descs_as_dir();
- #define CLEAN_CACHES_INTERVAL (30*60)
- time_to_clean_caches = now + CLEAN_CACHES_INTERVAL;
- }
- #define CHECK_DESCRIPTOR_INTERVAL (60)
- #define CHECK_IPADDRESS_INTERVAL (15*60)
-
- if (time_to_check_descriptor < now) {
- static int dirport_reachability_count = 0;
- time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
- check_descriptor_bandwidth_changed(now);
- if (time_to_check_ipaddress < now) {
- time_to_check_ipaddress = now + CHECK_IPADDRESS_INTERVAL;
- check_descriptor_ipaddress_changed(now);
- }
- #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
- mark_my_descriptor_dirty_if_older_than(
- now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL);
- consider_publishable_server(0);
-
- if (server_mode(options) &&
- (has_completed_circuit || !any_predicted_circuits(now)) &&
- !we_are_hibernating()) {
- if (stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
- consider_testing_reachability(1, dirport_reachability_count==0);
- if (++dirport_reachability_count > 5)
- dirport_reachability_count = 0;
- } else if (time_to_recheck_bandwidth < now) {
-
- routerinfo_t *me = router_get_my_routerinfo();
- if (time_to_recheck_bandwidth && me &&
- me->bandwidthcapacity < me->bandwidthrate &&
- me->bandwidthcapacity < 51200) {
- reset_bandwidth_test();
- }
- #define BANDWIDTH_RECHECK_INTERVAL (12*60*60)
- time_to_recheck_bandwidth = now + BANDWIDTH_RECHECK_INTERVAL;
- }
- }
-
-
- networkstatus_v2_list_clean(now);
-
- routerlist_remove_old_routers();
-
- update_networkstatus_downloads(now);
- }
-
- if (authdir_mode_v3(options))
- dirvote_act(options, now);
-
- circuit_expire_building(now);
-
- connection_ap_expire_beginning();
-
- connection_expire_held_open();
-
- if (!we_are_hibernating() && time_to_check_listeners < now) {
- retry_all_listeners(NULL, NULL);
- time_to_check_listeners = now+60;
- }
-
- have_dir_info = router_have_minimum_dir_info();
- if (have_dir_info && !we_are_hibernating())
- circuit_build_needed_circs(now);
-
- for (i=0;i<smartlist_len(connection_array);i++) {
- run_connection_housekeeping(i, now);
- }
- if (time_to_shrink_memory < now) {
- SMARTLIST_FOREACH(connection_array, connection_t *, conn, {
- if (conn->outbuf)
- buf_shrink(conn->outbuf);
- if (conn->inbuf)
- buf_shrink(conn->inbuf);
- });
- clean_cell_pool();
- buf_shrink_freelists(0);
- #define MEM_SHRINK_INTERVAL (60)
- time_to_shrink_memory = now + MEM_SHRINK_INTERVAL;
- }
-
- circuit_close_all_marked();
-
- if (has_completed_circuit && !we_are_hibernating())
- rend_consider_services_upload(now);
-
- close_closeable_connections();
-
- or_state_save(now);
-
- if (server_mode(options) && time_to_check_for_correct_dns < now) {
- if (!time_to_check_for_correct_dns) {
- time_to_check_for_correct_dns = now + 60 + crypto_rand_int(120);
- } else {
- dns_launch_correctness_checks();
- time_to_check_for_correct_dns = now + 12*3600 +
- crypto_rand_int(12*3600);
- }
- }
-
- if (options->HSAuthorityRecordStats && time_to_write_hs_statistics < now) {
- hs_usage_write_statistics_to_file(now);
- #define WRITE_HSUSAGE_INTERVAL (30*60)
- time_to_write_hs_statistics = now+WRITE_HSUSAGE_INTERVAL;
- }
-
- if (options->BridgeAuthoritativeDir &&
- time_to_write_bridge_status_file < now) {
- networkstatus_dump_bridge_status_to_file(now);
- #define BRIDGE_STATUSFILE_INTERVAL (30*60)
- time_to_write_bridge_status_file = now+BRIDGE_STATUSFILE_INTERVAL;
- }
- }
- static struct event *timeout_event = NULL;
- static int n_libevent_errors = 0;
- static void
- second_elapsed_callback(int fd, short event, void *args)
- {
-
- static struct timeval one_second;
- static long current_second = 0;
- struct timeval now;
- size_t bytes_written;
- size_t bytes_read;
- int seconds_elapsed;
- or_options_t *options = get_options();
- (void)fd;
- (void)event;
- (void)args;
- if (!timeout_event) {
- timeout_event = tor_malloc_zero(sizeof(struct event));
- evtimer_set(timeout_event, second_elapsed_callback, NULL);
- one_second.tv_sec = 1;
- one_second.tv_usec = 0;
- }
- n_libevent_errors = 0;
-
- tor_gettimeofday(&now);
-
- bytes_written = stats_prev_global_write_bucket - global_write_bucket;
- bytes_read = stats_prev_global_read_bucket - global_read_bucket;
- seconds_elapsed = current_second ? (int)(now.tv_sec - current_second) : 0;
- stats_n_bytes_read += bytes_read;
- stats_n_bytes_written += bytes_written;
- if (accounting_is_enabled(options) && seconds_elapsed >= 0)
- accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
- control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
- control_event_stream_bandwidth_used();
- if (seconds_elapsed > 0)
- connection_bucket_refill(seconds_elapsed, now.tv_sec);
- stats_prev_global_read_bucket = global_read_bucket;
- stats_prev_global_write_bucket = global_write_bucket;
- if (server_mode(options) &&
- !we_are_hibernating() &&
- seconds_elapsed > 0 &&
- has_completed_circuit &&
- stats_n_seconds_working / TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT !=
- (stats_n_seconds_working+seconds_elapsed) /
- TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
-
- routerinfo_t *me = router_get_my_routerinfo();
- if (me && !check_whether_orport_reachable())
- log_warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that "
- "its ORPort is reachable. Please check your firewalls, ports, "
- "address, /etc/hosts file, etc.",
- me->address, me->or_port);
- if (me && !check_whether_dirport_reachable())
- log_warn(LD_CONFIG,
- "Your server (%s:%d) has not managed to confirm that its "
- "DirPort is reachable. Please check your firewalls, ports, "
- "address, /etc/hosts file, etc.",
- me->address, me->dir_port);
- }
- #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
- if (seconds_elapsed < -NUM_JUMPED_SECONDS_BEFORE_WARN ||
- seconds_elapsed >= NUM_JUMPED_SECONDS_BEFORE_WARN) {
- circuit_note_clock_jumped(seconds_elapsed);
-
- } else if (seconds_elapsed > 0)
- stats_n_seconds_working += seconds_elapsed;
- run_scheduled_events(now.tv_sec);
- current_second = now.tv_sec;
- #if 0
- if (current_second % 300 == 0) {
- rep_history_clean(current_second - options->RephistTrackTime);
- dumpmemusage(get_min_log_level()<LOG_INFO ?
- get_min_log_level() : LOG_INFO);
- }
- #endif
- if (evtimer_add(timeout_event, &one_second))
- log_err(LD_NET,
- "Error from libevent when setting one-second timeout event");
- }
- #ifndef MS_WINDOWS
- static int
- got_libevent_error(void)
- {
- if (++n_libevent_errors > 8) {
- log_err(LD_NET, "Too many libevent errors in one second; dying");
- return -1;
- }
- return 0;
- }
- #endif
- #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
- void
- ip_address_changed(int at_interface)
- {
- int server = server_mode(get_options());
- if (at_interface) {
- if (! server) {
-
- init_keys();
- }
- } else {
- if (server) {
- if (stats_n_seconds_working > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
- reset_bandwidth_test();
- stats_n_seconds_working = 0;
- router_reset_reachability();
- mark_my_descriptor_dirty();
- }
- }
- dns_servers_relaunch_checks();
- }
- void
- dns_servers_relaunch_checks(void)
- {
- if (server_mode(get_options())) {
- dns_reset_correctness_checks();
- time_to_check_for_correct_dns = 0;
- }
- }
- static int
- do_hup(void)
- {
- or_options_t *options = get_options();
- #ifdef USE_DMALLOC
- dmalloc_log_stats();
- dmalloc_log_changed(0, 1, 0, 0);
- #endif
- log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config.");
- if (accounting_is_enabled(options))
- accounting_record_bandwidth_usage(time(NULL), get_or_state());
- router_reset_warnings();
- routerlist_reset_warnings();
- addressmap_clear_transient();
-
-
- if (options_init_from_torrc(0, NULL) < 0) {
- log_err(LD_CONFIG,"Reading config failed--see warnings above. "
- "For usage, try -h.");
- return -1;
- }
- options = get_options();
- if (authdir_mode_handles_descs(options, -1)) {
-
- if (dirserv_load_fingerprint_file() < 0) {
-
- log_info(LD_GENERAL, "Error reloading fingerprints. "
- "Continuing with old list.");
- }
- }
-
- circuit_expire_all_dirty_circs();
-
- router_reset_status_download_failures();
- router_reset_descriptor_download_failures();
- update_networkstatus_downloads(time(NULL));
-
- if (server_mode(options)) {
-
- cpuworkers_rotate();
- dns_reset();
- }
- return 0;
- }
- int
- do_main_loop(void)
- {
- int loop_result;
- time_t now;
-
- if (dns_init() < 0) {
- log_err(LD_GENERAL,"Error initializing dns subsystem; exiting");
- return -1;
- }
- handle_signals(1);
-
- if (! identity_key_is_set()) {
- if (init_keys() < 0) {
- log_err(LD_BUG,"Error initializing keys; exiting");
- return -1;
- }
- }
-
- init_cell_pool();
-
- connection_bucket_init();
- stats_prev_global_read_bucket = global_read_bucket;
- stats_prev_global_write_bucket = global_write_bucket;
- if (trusted_dirs_reload_certs())
- return -1;
- if (router_reload_v2_networkstatus()) {
- return -1;
- }
- if (router_reload_consensus_networkstatus()) {
- return -1;
- }
-
- if (router_reload_router_list()) {
- return -1;
- }
-
- now = time(NULL);
- directory_info_has_arrived(now, 1);
- if (authdir_mode_tests_reachability(get_options())) {
-
- dirserv_test_reachability(now, 1);
- }
- if (server_mode(get_options())) {
-
- cpu_init();
- }
-
- second_elapsed_callback(0,0,NULL);
- for (;;) {
- if (nt_service_is_stopping())
- return 0;
- #ifndef MS_WINDOWS
-
- errno = 0;
- #endif
-
- SMARTLIST_FOREACH(active_linked_connection_lst, connection_t *, conn,
- event_active(conn->read_event, EV_READ, 1));
- called_loop_once = smartlist_len(active_linked_connection_lst) ? 1 : 0;
-
- loop_result = event_loop(called_loop_once ? EVLOOP_ONCE : 0);
-
- if (loop_result < 0) {
- int e = tor_socket_errno(-1);
-
- if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
- #ifdef HAVE_EVENT_GET_METHOD
- log_err(LD_NET,"libevent call with %s failed: %s [%d]",
- event_get_method(), tor_socket_strerror(e), e);
- #else
- log_err(LD_NET,"libevent call failed: %s [%d]",
- tor_socket_strerror(e), e);
- #endif
- return -1;
- #ifndef MS_WINDOWS
- } else if (e == EINVAL) {
- log_warn(LD_NET, "EINVAL from libevent: should you upgrade libevent?");
- if (got_libevent_error())
- return -1;
- #endif
- } else {
- if (ERRNO_IS_EINPROGRESS(e))
- log_warn(LD_BUG,
- "libevent call returned EINPROGRESS? Please report.");
- log_debug(LD_NET,"libevent call interrupted.");
-
- continue;
- }
- }
- }
- }
- void
- control_signal_act(int the_signal)
- {
- switch (the_signal)
- {
- case 1:
- signal_callback(0,0,(void*)(uintptr_t)SIGHUP);
- break;
- case 2:
- signal_callback(0,0,(void*)(uintptr_t)SIGINT);
- break;
- case 10:
- signal_callback(0,0,(void*)(uintptr_t)SIGUSR1);
- break;
- case 12:
- signal_callback(0,0,(void*)(uintptr_t)SIGUSR2);
- break;
- case 15:
- signal_callback(0,0,(void*)(uintptr_t)SIGTERM);
- break;
- case SIGNEWNYM:
- signal_callback(0,0,(void*)(uintptr_t)SIGNEWNYM);
- break;
- case SIGCLEARDNSCACHE:
- signal_callback(0,0,(void*)(uintptr_t)SIGCLEARDNSCACHE);
- break;
- default:
- log_warn(LD_BUG, "Unrecognized signal number %d.", the_signal);
- break;
- }
- }
- static void
- signal_callback(int fd, short events, void *arg)
- {
- uintptr_t sig = (uintptr_t)arg;
- (void)fd;
- (void)events;
- switch (sig)
- {
- case SIGTERM:
- log_notice(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
- tor_cleanup();
- exit(0);
- break;
- case SIGINT:
- if (!server_mode(get_options())) {
- log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
- tor_cleanup();
- exit(0);
- }
- hibernate_begin_shutdown();
- break;
- #ifdef SIGPIPE
- case SIGPIPE:
- log_debug(LD_GENERAL,"Caught sigpipe. Ignoring.");
- break;
- #endif
- case SIGUSR1:
-
- dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
- break;
- case SIGUSR2:
- switch_logs_debug();
- log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
- "Send HUP to change back.");
- break;
- case SIGHUP:
- if (do_hup() < 0) {
- log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
- tor_cleanup();
- exit(1);
- }
- break;
- #ifdef SIGCHLD
- case SIGCHLD:
- while (waitpid(-1,NULL,WNOHANG) > 0) ;
- break;
- #endif
- case SIGNEWNYM: {
- time_t now = time(NULL);
- if (time_of_last_signewnym + MAX_SIGNEWNYM_RATE > now) {
- signewnym_is_pending = 1;
- log(LOG_NOTICE, LD_CONTROL,
- "Rate limiting NEWNYM request: delaying by %d second(s)",
- (int)(MAX_SIGNEWNYM_RATE+time_of_last_signewnym-now));
- } else {
- signewnym_impl(now);
- }
- break;
- }
- case SIGCLEARDNSCACHE:
- addressmap_clear_transient();
- break;
- }
- }
- extern uint64_t rephist_total_alloc;
- extern uint32_t rephist_total_num;
- static void
- dumpmemusage(int severity)
- {
- connection_dump_buffer_mem_stats(severity);
- log(severity, LD_GENERAL, "In rephist: "U64_FORMAT" used by %d Tors.",
- U64_PRINTF_ARG(rephist_total_alloc), rephist_total_num);
- dump_routerlist_mem_usage(severity);
- dump_cell_pool_usage(severity);
- buf_dump_freelist_sizes(severity);
- tor_log_mallinfo(severity);
- }
- static void
- dumpstats(int severity)
- {
- time_t now = time(NULL);
- time_t elapsed;
- log(severity, LD_GENERAL, "Dumping stats:");
- SMARTLIST_FOREACH(connection_array, connection_t *, conn,
- {
- int i = conn_sl_idx;
- log(severity, LD_GENERAL,
- "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
- i, conn->s, conn->type, conn_type_to_string(conn->type),
- conn->state, conn_state_to_string(conn->type, conn->state),
- (int)(now - conn->timestamp_created));
- if (!connection_is_listener(conn)) {
- log(severity,LD_GENERAL,
- "Conn %d is to %s:%d.", i,
- safe_str(conn->address), conn->port);
- log(severity,LD_GENERAL,
- "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
- i,
- (int)buf_datalen(conn->inbuf),
- (int)buf_allocation(conn->inbuf),
- (int)(now - conn->timestamp_lastread));
- log(severity,LD_GENERAL,
- "Conn %d: %d bytes waiting on outbuf "
- "(len %d, last written %d secs ago)",i,
- (int)buf_datalen(conn->outbuf),
- (int)buf_allocation(conn->outbuf),
- (int)(now - conn->timestamp_lastwritten));
- }
- circuit_dump_by_conn(conn, severity);
- });
- log(severity, LD_NET,
- "Cells processed: "U64_FORMAT" padding\n"
- " "U64_FORMAT" create\n"
- " "U64_FORMAT" created\n"
- " "U64_FORMAT" relay\n"
- " ("U64_FORMAT" relayed)\n"
- " ("U64_FORMAT" delivered)\n"
- " "U64_FORMAT" destroy",
- U64_PRINTF_ARG(stats_n_padding_cells_processed),
- U64_PRINTF_ARG(stats_n_create_cells_processed),
- U64_PRINTF_ARG(stats_n_created_cells_processed),
- U64_PRINTF_ARG(stats_n_relay_cells_processed),
- U64_PRINTF_ARG(stats_n_relay_cells_relayed),
- U64_PRINTF_ARG(stats_n_relay_cells_delivered),
- U64_PRINTF_ARG(stats_n_destroy_cells_processed));
- if (stats_n_data_cells_packaged)
- log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
- 100*(U64_TO_DBL(stats_n_data_bytes_packaged) /
- U64_TO_DBL(stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
- if (stats_n_data_cells_received)
- log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
- 100*(U64_TO_DBL(stats_n_data_bytes_received) /
- U64_TO_DBL(stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
- if (now - time_of_process_start >= 0)
- elapsed = now - time_of_process_start;
- else
- elapsed = 0;
- if (elapsed) {
- log(severity, LD_NET,
- "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
- U64_PRINTF_ARG(stats_n_bytes_read),
- (int)elapsed,
- (int) (stats_n_bytes_read/elapsed));
- log(severity, LD_NET,
- "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
- U64_PRINTF_ARG(stats_n_bytes_written),
- (int)elapsed,
- (int) (stats_n_bytes_written/elapsed));
- }
- log(severity, LD_NET, "--------------- Dumping memory information:");
- dumpmemusage(severity);
- rep_hist_dump_stats(now,severity);
- rend_service_dump_stats(severity);
- dump_pk_ops(severity);
- dump_distinct_digest_count(severity);
- }
- static void
- exit_function(void)
- {
-
- #ifdef MS_WINDOWS
- WSACleanup();
- #endif
- }
- void
- handle_signals(int is_parent)
- {
- #ifndef MS_WINDOWS
- int i;
- static int signals[] = {
- SIGINT,
- SIGTERM,
- SIGPIPE,
- SIGUSR1,
- SIGUSR2,
- SIGHUP,
- #ifdef SIGXFSZ
- SIGXFSZ,
- #endif
- SIGCHLD,
- -1 };
- static struct event signal_events[16];
- if (is_parent) {
- for (i = 0; signals[i] >= 0; ++i) {
- signal_set(&signal_events[i], signals[i], signal_callback,
- (void*)(uintptr_t)signals[i]);
- if (signal_add(&signal_events[i], NULL))
- log_warn(LD_BUG, "Error from libevent when adding event for signal %d",
- signals[i]);
- }
- } else {
- struct sigaction action;
- action.sa_flags = 0;
- sigemptyset(&action.sa_mask);
- action.sa_handler = SIG_IGN;
- sigaction(SIGINT, &action, NULL);
- sigaction(SIGTERM, &action, NULL);
- sigaction(SIGPIPE, &action, NULL);
- sigaction(SIGUSR1, &action, NULL);
- sigaction(SIGUSR2, &action, NULL);
- sigaction(SIGHUP, &action, NULL);
- #ifdef SIGXFSZ
- sigaction(SIGXFSZ, &action, NULL);
- #endif
- }
- #else
- (void)is_parent;
- #endif
- }
- int
- tor_init(int argc, char *argv[])
- {
- char buf[256];
- int i, quiet = 0;
- time_of_process_start = time(NULL);
- if (!connection_array)
- connection_array = smartlist_create();
- if (!closeable_connection_lst)
- closeable_connection_lst = smartlist_create();
- if (!active_linked_connection_lst)
- active_linked_connection_lst = smartlist_create();
-
- tor_snprintf(buf, sizeof(buf), "Tor %s", get_version());
- log_set_application_name(buf);
-
- tor_threads_init();
-
- rep_hist_init();
-
- rend_cache_init();
- addressmap_init();
-
- for (i=1;i<argc;++i) {
- if (!strcmp(argv[i], "--quiet"))
- quiet = 1;
- }
- if (!quiet) {
-
- add_temp_log();
- }
- log(LOG_NOTICE, LD_GENERAL, "Tor v%s. This is experimental software. "
- "Do not rely on it for strong anonymity. (Running on %s)",get_version(),
- get_uname());
- if (network_init()<0) {
- log_err(LD_BUG,"Error initializing network; exiting.");
- return -1;
- }
- atexit(exit_function);
- if (options_init_from_torrc(argc,argv) < 0) {
- log_err(LD_CONFIG,"Reading config failed--see warnings above.");
- return -1;
- }
- #ifndef MS_WINDOWS
- if (geteuid()==0)
- log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
- "and you probably shouldn't.");
- #endif
- crypto_global_init(get_options()->HardwareAccel);
- if (crypto_seed_rng(1)) {
- log_err(LD_BUG, "Unable to seed random number generator. Exiting.");
- return -1;
- }
- return 0;
- }
- void
- tor_free_all(int postfork)
- {
- if (!postfork) {
- evdns_shutdown(1);
- }
- geoip_free_all();
- dirvote_free_all();
- routerlist_free_all();
- networkstatus_free_all();
- addressmap_free_all();
- set_exit_redirects(NULL);
- dirserv_free_all();
- rend_service_free_all();
- rend_cache_free_all();
- rep_hist_free_all();
- hs_usage_free_all();
- dns_free_all();
- clear_pending_onions();
- circuit_free_all();
- entry_guards_free_all();
- connection_free_all();
- buf_shrink_freelists(1);
- policies_free_all();
- if (!postfork) {
- config_free_all();
- router_free_all();
- }
- free_cell_pool();
- tor_tls_free_all();
-
- smartlist_free(connection_array);
- smartlist_free(closeable_connection_lst);
- smartlist_free(active_linked_connection_lst);
- tor_free(timeout_event);
-
- if (!postfork) {
- escaped(NULL);
- esc_router_info(NULL);
- logs_free_all();
- }
- }
- void
- tor_cleanup(void)
- {
- or_options_t *options = get_options();
-
- if (options->command == CMD_RUN_TOR) {
- if (options->PidFile)
- unlink(options->PidFile);
- if (accounting_is_enabled(options))
- accounting_record_bandwidth_usage(time(NULL), get_or_state());
- or_state_mark_dirty(get_or_state(), 0);
- or_state_save(time(NULL));
- if (authdir_mode_tests_reachability(options))
- rep_hist_record_mtbf_data();
- }
- #ifdef USE_DMALLOC
- dmalloc_log_stats();
- #endif
- tor_free_all(0);
- crypto_global_cleanup();
- #ifdef USE_DMALLOC
- dmalloc_log_unfreed();
- dmalloc_shutdown();
- #endif
- }
- int
- do_list_fingerprint(void)
- {
- char buf[FINGERPRINT_LEN+1];
- crypto_pk_env_t *k;
- const char *nickname = get_options()->Nickname;
- if (!server_mode(get_options())) {
- log_err(LD_GENERAL,
- "Clients don't have long-term identity keys. Exiting.\n");
- return -1;
- }
- tor_assert(nickname);
- if (init_keys() < 0) {
- log_err(LD_BUG,"Error initializing keys; can't display fingerprint");
- return -1;
- }
- if (!(k = get_identity_key())) {
- log_err(LD_GENERAL,"Error: missing identity key.");
- return -1;
- }
- if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
- log_err(LD_BUG, "Error computing fingerprint");
- return -1;
- }
- printf("%s %s\n", nickname, buf);
- return 0;
- }
- void
- do_hash_password(void)
- {
- char output[256];
- char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
- crypto_rand(key, S2K_SPECIFIER_LEN-1);
- key[S2K_SPECIFIER_LEN-1] = (uint8_t)96;
- secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
- get_options()->command_arg, strlen(get_options()->command_arg),
- key);
- base16_encode(output, sizeof(output), key, sizeof(key));
- printf("16:%s\n",output);
- }
- #ifdef USE_DMALLOC
- #include <openssl/crypto.h>
- static void
- _tor_dmalloc_free(void *p)
- {
- tor_free(p);
- }
- #endif
- int
- tor_main(int argc, char *argv[])
- {
- int result = 0;
- #ifdef USE_DMALLOC
- int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc,
- _tor_dmalloc_free);
- log_notice(LD_CONFIG, "Set up dmalloc; returned %d", r);
- #endif
- init_logging();
- #ifdef NT_SERVICE
- {
- int done = 0;
- result = nt_service_parse_options(argc, argv, &done);
- if (done) return result;
- }
- #endif
- if (tor_init(argc, argv)<0)
- return -1;
- switch (get_options()->command) {
- case CMD_RUN_TOR:
- #ifdef NT_SERVICE
- nt_service_set_state(SERVICE_RUNNING);
- #endif
- result = do_main_loop();
- break;
- case CMD_LIST_FINGERPRINT:
- result = do_list_fingerprint();
- break;
- case CMD_HASH_PASSWORD:
- do_hash_password();
- result = 0;
- break;
- case CMD_VERIFY_CONFIG:
- printf("Configuration was valid\n");
- result = 0;
- break;
- case CMD_RUN_UNITTESTS:
- default:
- log_warn(LD_BUG,"Illegal command number %d: internal error.",
- get_options()->command);
- result = -1;
- }
- tor_cleanup();
- return result;
- }
|