1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626 |
- const char main_c_id[] =
- "$Id$";
- #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;
- long time_of_process_start = 0;
- long stats_n_seconds_working = 0;
- static time_t time_to_fetch_directory = 0;
- static time_t time_to_fetch_running_routers = 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;
- #ifdef MS_WINDOWS
- #define MS_WINDOWS_SERVICE
- #endif
- #ifdef MS_WINDOWS_SERVICE
- #include <tchar.h>
- #define GENSRV_SERVICENAME TEXT("tor")
- #define GENSRV_DISPLAYNAME TEXT("Tor Win32 Service")
- #define GENSRV_DESCRIPTION \
- TEXT("Provides an anonymous Internet communication system")
- #define GENSRV_USERACCT TEXT("NT AUTHORITY\\LocalService")
- #define NT_SERVICE_ERROR_TORINIT_FAILED ERROR_EXCEPTION_IN_SERVICE
- SERVICE_STATUS service_status;
- SERVICE_STATUS_HANDLE hStatus;
- static char **backup_argv;
- static int backup_argc;
- static int nt_service_is_stopping(void);
- static char* nt_strerror(uint32_t errnum);
- #else
- #define nt_service_is_stopping() (0)
- #endif
- #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
- #define CHECK_DESCRIPTOR_INTERVAL (60)
- #define CHECK_IPADDRESS_INTERVAL (15*60)
- #define MEM_SHRINK_INTERVAL (60)
- #define DESCRIPTOR_RETRY_INTERVAL (10)
- #define DESCRIPTOR_FAILURE_RESET_INTERVAL (60*60)
- #define ENTROPY_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)
- #define WRITE_HSUSAGE_INTERVAL (900)
- 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)->dns_server_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_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;
- conn = smartlist_get(connection_array, i);
- if (!conn->marked_for_close)
- return 0;
- assert_connection_ok(conn, time(NULL));
- 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)) {
-
- int sz = connection_bucket_write_limit(conn);
- 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_info(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));
-
- 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.");
- update_router_descriptor_downloads(now);
- return;
- } else {
-
- 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);
- 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 &&
- (!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
- run_scheduled_events(time_t now)
- {
- static time_t last_rotated_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;
- 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");
- circuit_expire_all_dirty_circs();
- addressmap_clear_transient();
- time_of_last_signewnym = now;
- signewnym_is_pending = 0;
- }
-
- 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);
- time_to_try_getting_descriptors = now + DESCRIPTOR_RETRY_INTERVAL;
- }
- if (time_to_reset_descriptor_failures < now) {
- router_reset_descriptor_download_failures();
- if (options->UseBridges)
- fetch_bridge_descriptors();
- time_to_reset_descriptor_failures =
- now + DESCRIPTOR_FAILURE_RESET_INTERVAL;
- }
-
- if (!last_rotated_certificate)
- last_rotated_certificate = now;
- if (last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
- log_info(LD_GENERAL,"Rotating tls context.");
- if (tor_tls_context_new(get_identity_key(), options->Nickname,
- MAX_SSL_KEY_LIFETIME) < 0) {
- log_warn(LD_BUG, "Error reinitializing TLS context");
-
- }
- last_rotated_certificate = now;
-
- }
- if (time_to_add_entropy == 0)
- time_to_add_entropy = now + ENTROPY_INTERVAL;
- if (time_to_add_entropy < now) {
-
- crypto_seed_rng();
- 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(0);
- }
-
- if (time_to_fetch_directory < now) {
-
- if (options->DirPort && !authdir_mode_v1(options)) {
-
- if (any_trusted_dir_is_v1_authority() &&
- !should_delay_dir_fetches(options))
- directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
- }
- #define V1_DIR_FETCH_PERIOD (6*60*60)
- time_to_fetch_directory = now + V1_DIR_FETCH_PERIOD;
- }
-
- if (options->DirPort && time_to_fetch_running_routers < now) {
- if (!authdir_mode_v1(options) && !should_delay_dir_fetches(options)) {
- directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST, NULL, 1);
- }
- #define V1_RUNNINGROUTERS_FETCH_PERIOD (30*60)
- time_to_fetch_running_routers = now + V1_RUNNINGROUTERS_FETCH_PERIOD;
-
- rep_history_clean(now - options->RephistTrackTime);
- rend_cache_clean();
-
- }
-
- 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);
- }
- 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)) &&
- stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT &&
- !we_are_hibernating()) {
- consider_testing_reachability(1, dirport_reachability_count==0);
- if (++dirport_reachability_count > 5)
- dirport_reachability_count = 0;
- }
-
-
- routerlist_remove_old_routers();
- networkstatus_list_clean(now);
- networkstatus_list_update_recent(now);
- routers_update_all_from_networkstatus(now);
-
- update_networkstatus_downloads(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();
- 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);
- time_to_write_hs_statistics = now+WRITE_HSUSAGE_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 ? (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);
- 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 &&
- 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();
- 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)) {
-
- 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)) {
- mark_my_descriptor_dirty();
-
- cpuworkers_rotate();
- dns_reset();
- }
- return 0;
- }
- static int
- do_main_loop(void)
- {
- int loop_result;
-
- 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 (router_reload_router_list()) {
- return -1;
- }
-
- if (router_reload_networkstatus()) {
- return -1;
- }
- directory_info_has_arrived(time(NULL),1);
- if (authdir_mode_tests_reachability(get_options())) {
-
- dirserv_test_reachability(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 {
-
- circuit_expire_all_dirty_circs();
- addressmap_clear_transient();
- time_of_last_signewnym = 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);
- }
- 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_capacity(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_capacity(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
- }
- static int
- tor_init(int argc, char *argv[])
- {
- char buf[256];
- 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);
-
- rep_hist_init();
-
- rend_cache_init();
- addressmap_init();
-
- 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()) {
- 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);
- }
- routerlist_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();
- policies_free_all();
- if (!postfork) {
- config_free_all();
- router_free_all();
- }
- free_cell_pool();
- tor_tls_free_all();
-
- smartlist_free(closeable_connection_lst);
- smartlist_free(active_linked_connection_lst);
- tor_free(timeout_event);
-
- escaped(NULL);
- if (!postfork) {
- close_logs();
- }
- }
- 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));
- }
- tor_free_all(0);
- crypto_global_cleanup();
- #ifdef USE_DMALLOC
- dmalloc_log_unfreed();
- dmalloc_shutdown();
- #endif
- }
- static 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;
- }
- static 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 MS_WINDOWS_SERVICE
- void nt_service_control(DWORD request);
- void nt_service_body(int argc, char **argv);
- void nt_service_main(void);
- SC_HANDLE nt_service_open_scm(void);
- SC_HANDLE nt_service_open(SC_HANDLE hSCManager);
- int nt_service_start(SC_HANDLE hService);
- int nt_service_stop(SC_HANDLE hService);
- int nt_service_install(int argc, char **argv);
- int nt_service_remove(void);
- int nt_service_cmd_start(void);
- int nt_service_cmd_stop(void);
- struct service_fns {
- int loaded;
- BOOL (WINAPI *ChangeServiceConfig2A_fn)(
- SC_HANDLE hService,
- DWORD dwInfoLevel,
- LPVOID lpInfo);
- BOOL (WINAPI *CloseServiceHandle_fn)(
- SC_HANDLE hSCObject);
- BOOL (WINAPI *ControlService_fn)(
- SC_HANDLE hService,
- DWORD dwControl,
- LPSERVICE_STATUS lpServiceStatus);
- SC_HANDLE (WINAPI *CreateServiceA_fn)(
- SC_HANDLE hSCManager,
- LPCTSTR lpServiceName,
- LPCTSTR lpDisplayName,
- DWORD dwDesiredAccess,
- DWORD dwServiceType,
- DWORD dwStartType,
- DWORD dwErrorControl,
- LPCTSTR lpBinaryPathName,
- LPCTSTR lpLoadOrderGroup,
- LPDWORD lpdwTagId,
- LPCTSTR lpDependencies,
- LPCTSTR lpServiceStartName,
- LPCTSTR lpPassword);
- BOOL (WINAPI *DeleteService_fn)(
- SC_HANDLE hService);
- SC_HANDLE (WINAPI *OpenSCManagerA_fn)(
- LPCTSTR lpMachineName,
- LPCTSTR lpDatabaseName,
- DWORD dwDesiredAccess);
- SC_HANDLE (WINAPI *OpenServiceA_fn)(
- SC_HANDLE hSCManager,
- LPCTSTR lpServiceName,
- DWORD dwDesiredAccess);
- BOOL (WINAPI *QueryServiceStatus_fn)(
- SC_HANDLE hService,
- LPSERVICE_STATUS lpServiceStatus);
- SERVICE_STATUS_HANDLE (WINAPI *RegisterServiceCtrlHandlerA_fn)(
- LPCTSTR lpServiceName,
- LPHANDLER_FUNCTION lpHandlerProc);
- BOOL (WINAPI *SetServiceStatus_fn)(SERVICE_STATUS_HANDLE,
- LPSERVICE_STATUS);
- BOOL (WINAPI *StartServiceCtrlDispatcherA_fn)(
- const SERVICE_TABLE_ENTRY* lpServiceTable);
- BOOL (WINAPI *StartServiceA_fn)(
- SC_HANDLE hService,
- DWORD dwNumServiceArgs,
- LPCTSTR* lpServiceArgVectors);
- BOOL (WINAPI *LookupAccountNameA_fn)(
- LPCTSTR lpSystemName,
- LPCTSTR lpAccountName,
- PSID Sid,
- LPDWORD cbSid,
- LPTSTR ReferencedDomainName,
- LPDWORD cchReferencedDomainName,
- PSID_NAME_USE peUse);
- } service_fns = { 0,
- NULL, NULL, NULL, NULL, NULL, NULL,
- NULL, NULL, NULL, NULL, NULL, NULL,
- NULL};
- static void
- nt_service_loadlibrary(void)
- {
- HMODULE library = 0;
- void *fn;
- if (service_fns.loaded)
- return;
-
- if (!(library = LoadLibrary("advapi32.dll"))) {
- log_err(LD_GENERAL, "Couldn't open advapi32.dll. Are you trying to use "
- "NT services on Windows 98? That doesn't work.");
- goto err;
- }
- #define LOAD(f) STMT_BEGIN \
- if (!(fn = GetProcAddress(library, #f))) { \
- log_err(LD_BUG, \
- "Couldn't find %s in advapi32.dll! We probably got the " \
- "name wrong.", #f); \
- goto err; \
- } else { \
- service_fns.f ## _fn = fn; \
- } \
- STMT_END
- LOAD(ChangeServiceConfig2A);
- LOAD(CloseServiceHandle);
- LOAD(ControlService);
- LOAD(CreateServiceA);
- LOAD(DeleteService);
- LOAD(OpenSCManagerA);
- LOAD(OpenServiceA);
- LOAD(QueryServiceStatus);
- LOAD(RegisterServiceCtrlHandlerA);
- LOAD(SetServiceStatus);
- LOAD(StartServiceCtrlDispatcherA);
- LOAD(StartServiceA);
- LOAD(LookupAccountNameA);
- service_fns.loaded = 1;
- return;
- err:
- printf("Unable to load library support for NT services: exiting.\n");
- exit(1);
- }
- static int
- nt_service_is_stopping(void)
- {
-
- if (!service_fns.loaded)
- return 0;
- if (service_status.dwCurrentState == SERVICE_STOP_PENDING) {
- service_status.dwWin32ExitCode = 0;
- service_status.dwCurrentState = SERVICE_STOPPED;
- service_fns.SetServiceStatus_fn(hStatus, &service_status);
- return 1;
- } else if (service_status.dwCurrentState == SERVICE_STOPPED) {
- return 1;
- }
- return 0;
- }
- void
- nt_service_control(DWORD request)
- {
- static struct timeval exit_now;
- exit_now.tv_sec = 0;
- exit_now.tv_usec = 0;
- nt_service_loadlibrary();
- switch (request) {
- case SERVICE_CONTROL_STOP:
- case SERVICE_CONTROL_SHUTDOWN:
- log_notice(LD_GENERAL,
- "Got stop/shutdown request; shutting down cleanly.");
- service_status.dwCurrentState = SERVICE_STOP_PENDING;
- event_loopexit(&exit_now);
- return;
- }
- service_fns.SetServiceStatus_fn(hStatus, &service_status);
- }
- void
- nt_service_body(int argc, char **argv)
- {
- int r;
- (void) argc;
- (void) argv;
- nt_service_loadlibrary();
- service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
- service_status.dwCurrentState = SERVICE_START_PENDING;
- service_status.dwControlsAccepted =
- SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
- service_status.dwWin32ExitCode = 0;
- service_status.dwServiceSpecificExitCode = 0;
- service_status.dwCheckPoint = 0;
- service_status.dwWaitHint = 1000;
- hStatus = service_fns.RegisterServiceCtrlHandlerA_fn(GENSRV_SERVICENAME,
- (LPHANDLER_FUNCTION) nt_service_control);
- if (hStatus == 0) {
-
- return;
- }
- r = tor_init(backup_argc, backup_argv);
- if (r) {
-
- r = NT_SERVICE_ERROR_TORINIT_FAILED;
- service_status.dwCurrentState = SERVICE_STOPPED;
- service_status.dwWin32ExitCode = r;
- service_status.dwServiceSpecificExitCode = r;
- service_fns.SetServiceStatus_fn(hStatus, &service_status);
- return;
- }
-
- service_status.dwCurrentState = SERVICE_RUNNING;
- service_fns.SetServiceStatus_fn(hStatus, &service_status);
- do_main_loop();
- tor_cleanup();
- }
- void
- nt_service_main(void)
- {
- SERVICE_TABLE_ENTRY table[2];
- DWORD result = 0;
- char *errmsg;
- nt_service_loadlibrary();
- table[0].lpServiceName = (char*)GENSRV_SERVICENAME;
- table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
- table[1].lpServiceName = NULL;
- table[1].lpServiceProc = NULL;
- if (!service_fns.StartServiceCtrlDispatcherA_fn(table)) {
- result = GetLastError();
- errmsg = nt_strerror(result);
- printf("Service error %d : %s\n", (int) result, errmsg);
- LocalFree(errmsg);
- if (result == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
- if (tor_init(backup_argc, backup_argv) < 0)
- return;
- switch (get_options()->command) {
- case CMD_RUN_TOR:
- do_main_loop();
- break;
- case CMD_LIST_FINGERPRINT:
- do_list_fingerprint();
- break;
- case CMD_HASH_PASSWORD:
- do_hash_password();
- break;
- case CMD_VERIFY_CONFIG:
- printf("Configuration was valid\n");
- break;
- case CMD_RUN_UNITTESTS:
- default:
- log_err(LD_CONFIG, "Illegal command number %d: internal error.",
- get_options()->command);
- }
- tor_cleanup();
- }
- }
- }
- SC_HANDLE
- nt_service_open_scm(void)
- {
- SC_HANDLE hSCManager;
- char *errmsg = NULL;
- nt_service_loadlibrary();
- if ((hSCManager = service_fns.OpenSCManagerA_fn(
- NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
- errmsg = nt_strerror(GetLastError());
- printf("OpenSCManager() failed : %s\n", errmsg);
- LocalFree(errmsg);
- }
- return hSCManager;
- }
- SC_HANDLE
- nt_service_open(SC_HANDLE hSCManager)
- {
- SC_HANDLE hService;
- char *errmsg = NULL;
- nt_service_loadlibrary();
- if ((hService = service_fns.OpenServiceA_fn(hSCManager, GENSRV_SERVICENAME,
- SERVICE_ALL_ACCESS)) == NULL) {
- errmsg = nt_strerror(GetLastError());
- printf("OpenService() failed : %s\n", errmsg);
- LocalFree(errmsg);
- }
- return hService;
- }
- int
- nt_service_start(SC_HANDLE hService)
- {
- char *errmsg = NULL;
- nt_service_loadlibrary();
- service_fns.QueryServiceStatus_fn(hService, &service_status);
- if (service_status.dwCurrentState == SERVICE_RUNNING) {
- printf("Service is already running\n");
- return 0;
- }
- if (service_fns.StartServiceA_fn(hService, 0, NULL)) {
-
- while (service_fns.QueryServiceStatus_fn(hService, &service_status) &&
- (service_status.dwCurrentState == SERVICE_START_PENDING)) {
- Sleep(500);
- }
-
- if (service_status.dwCurrentState == SERVICE_RUNNING) {
- printf("Service started successfully\n");
- return 0;
- } else {
- errmsg = nt_strerror(service_status.dwWin32ExitCode);
- printf("Service failed to start : %s\n", errmsg);
- LocalFree(errmsg);
- }
- } else {
- errmsg = nt_strerror(GetLastError());
- printf("StartService() failed : %s\n", errmsg);
- LocalFree(errmsg);
- }
- return -1;
- }
- int
- nt_service_stop(SC_HANDLE hService)
- {
- #define MAX_SERVICE_WAIT_TIME 10
- int wait_time;
- char *errmsg = NULL;
- nt_service_loadlibrary();
- service_fns.QueryServiceStatus_fn(hService, &service_status);
- if (service_status.dwCurrentState == SERVICE_STOPPED) {
- printf("Service is already stopped\n");
- return 0;
- }
- if (service_fns.ControlService_fn(hService, SERVICE_CONTROL_STOP,
- &service_status)) {
- wait_time = 0;
- while (service_fns.QueryServiceStatus_fn(hService, &service_status) &&
- (service_status.dwCurrentState != SERVICE_STOPPED) &&
- (wait_time < MAX_SERVICE_WAIT_TIME)) {
- Sleep(1000);
- wait_time++;
- }
- if (service_status.dwCurrentState == SERVICE_STOPPED) {
- printf("Service stopped successfully\n");
- return 0;
- } else if (wait_time == MAX_SERVICE_WAIT_TIME) {
- printf("Service did not stop within %d seconds.\n", wait_time);
- } else {
- errmsg = nt_strerror(GetLastError());
- printf("QueryServiceStatus() failed : %s\n",errmsg);
- LocalFree(errmsg);
- }
- } else {
- errmsg = nt_strerror(GetLastError());
- printf("ControlService() failed : %s\n", errmsg);
- LocalFree(errmsg);
- }
- return -1;
- }
- static char *
- nt_service_command_line(int *using_default_torrc)
- {
- TCHAR tor_exe[MAX_PATH+1];
- char *command, *options=NULL;
- smartlist_t *sl;
- int i, cmdlen;
- *using_default_torrc = 1;
-
- if (0 == GetModuleFileName(NULL, tor_exe, MAX_PATH))
- return NULL;
-
- sl = smartlist_create();
- for (i = 1; i < backup_argc; ++i) {
- if (!strcmp(backup_argv[i], "--options") ||
- !strcmp(backup_argv[i], "-options")) {
- while (++i < backup_argc) {
- if (!strcmp(backup_argv[i], "-f"))
- *using_default_torrc = 0;
- smartlist_add(sl, backup_argv[i]);
- }
- }
- }
- if (smartlist_len(sl))
- options = smartlist_join_strings(sl,"\" \"",0,NULL);
- smartlist_free(sl);
-
- cmdlen = strlen(tor_exe) + (options?strlen(options):0) + 32;
- command = tor_malloc(cmdlen);
-
- if (options) {
- if (tor_snprintf(command, cmdlen, "\"%s\" --nt-service \"%s\"",
- tor_exe, options)<0) {
- tor_free(command);
- }
- } else {
- if (tor_snprintf(command, cmdlen, "\"%s\" --nt-service", tor_exe)<0) {
- tor_free(command);
- }
- }
- tor_free(options);
- return command;
- }
- int
- nt_service_install(int argc, char **argv)
- {
-
- SC_HANDLE hSCManager = NULL;
- SC_HANDLE hService = NULL;
- SERVICE_DESCRIPTION sdBuff;
- char *command;
- char *errmsg;
- const char *user_acct = GENSRV_USERACCT;
- const char *password = "";
- int i;
- OSVERSIONINFOEX info;
- SID_NAME_USE sidUse;
- DWORD sidLen = 0, domainLen = 0;
- int is_win2k_or_worse = 0;
- int using_default_torrc = 0;
- nt_service_loadlibrary();
-
- if ((hSCManager = nt_service_open_scm()) == NULL)
- return -1;
-
- if ((command = nt_service_command_line(&using_default_torrc)) == NULL) {
- printf("Unable to build service command line.\n");
- service_fns.CloseServiceHandle_fn(hSCManager);
- return -1;
- }
- for (i=1; i < argc; ++i) {
- if (!strcmp(argv[i], "--user") && i+1<argc) {
- user_acct = argv[i+1];
- ++i;
- }
- if (!strcmp(argv[i], "--password") && i+1<argc) {
- password = argv[i+1];
- ++i;
- }
- }
-
- memset(&info, 0, sizeof(info));
- info.dwOSVersionInfoSize = sizeof(info);
- if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
- printf("Call to GetVersionEx failed.\n");
- is_win2k_or_worse = 1;
- } else {
- if (info.dwMajorVersion < 5 ||
- (info.dwMajorVersion == 5 && info.dwMinorVersion == 0))
- is_win2k_or_worse = 1;
- }
- if (user_acct == GENSRV_USERACCT) {
- if (is_win2k_or_worse) {
-
- printf("Running on Win2K or earlier, so the LocalService account "
- "doesn't exist. Falling back to SYSTEM account.\n");
- user_acct = NULL;
- } else {
-
- printf("Running on a Post-Win2K OS, so we'll assume that the "
- "LocalService account exists.\n");
- }
- } else if (0 && service_fns.LookupAccountNameA_fn(NULL,
- user_acct,
- NULL, &sidLen,
- NULL, &domainLen,
- &sidUse) == 0) {
-
- printf("User \"%s\" doesn't seem to exist.\n", user_acct);
- return -1;
- } else {
- printf("Will try to install service as user \"%s\".\n", user_acct);
- }
-
- if (using_default_torrc)
- printf("IMPORTANT NOTE:\n"
- " The Tor service will run under the account \"%s\". This means\n"
- " that Tor will look for its configuration file under that\n"
- " account's Application Data directory, which is probably not\n"
- " the same as yours.\n", user_acct?user_acct:"<local system>");
-
- if ((hService = service_fns.CreateServiceA_fn(hSCManager, GENSRV_SERVICENAME,
- GENSRV_DISPLAYNAME,
- SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
- SERVICE_AUTO_START, SERVICE_ERROR_IGNORE,
- command, NULL, NULL, NULL,
- user_acct, password)) == NULL) {
- errmsg = nt_strerror(GetLastError());
- printf("CreateService() failed : %s\n", errmsg);
- service_fns.CloseServiceHandle_fn(hSCManager);
- LocalFree(errmsg);
- tor_free(command);
- return -1;
- }
- printf("Done with CreateService.\n");
-
- sdBuff.lpDescription = (char*)GENSRV_DESCRIPTION;
- service_fns.ChangeServiceConfig2A_fn(hService, SERVICE_CONFIG_DESCRIPTION,
- &sdBuff);
- printf("Service installed successfully\n");
-
- nt_service_start(hService);
- service_fns.CloseServiceHandle_fn(hService);
- service_fns.CloseServiceHandle_fn(hSCManager);
- tor_free(command);
- return 0;
- }
- int
- nt_service_remove(void)
- {
- SC_HANDLE hSCManager = NULL;
- SC_HANDLE hService = NULL;
- char *errmsg;
- nt_service_loadlibrary();
- if ((hSCManager = nt_service_open_scm()) == NULL)
- return -1;
- if ((hService = nt_service_open(hSCManager)) == NULL) {
- service_fns.CloseServiceHandle_fn(hSCManager);
- return -1;
- }
- nt_service_stop(hService);
- if (service_fns.DeleteService_fn(hService) == FALSE) {
- errmsg = nt_strerror(GetLastError());
- printf("DeleteService() failed : %s\n", errmsg);
- LocalFree(errmsg);
- service_fns.CloseServiceHandle_fn(hService);
- service_fns.CloseServiceHandle_fn(hSCManager);
- return -1;
- }
- service_fns.CloseServiceHandle_fn(hService);
- service_fns.CloseServiceHandle_fn(hSCManager);
- printf("Service removed successfully\n");
- return 0;
- }
- int
- nt_service_cmd_start(void)
- {
- SC_HANDLE hSCManager;
- SC_HANDLE hService;
- int start;
- if ((hSCManager = nt_service_open_scm()) == NULL)
- return -1;
- if ((hService = nt_service_open(hSCManager)) == NULL) {
- service_fns.CloseServiceHandle_fn(hSCManager);
- return -1;
- }
- start = nt_service_start(hService);
- service_fns.CloseServiceHandle_fn(hService);
- service_fns.CloseServiceHandle_fn(hSCManager);
- return start;
- }
- int
- nt_service_cmd_stop(void)
- {
- SC_HANDLE hSCManager;
- SC_HANDLE hService;
- int stop;
- if ((hSCManager = nt_service_open_scm()) == NULL)
- return -1;
- if ((hService = nt_service_open(hSCManager)) == NULL) {
- service_fns.CloseServiceHandle_fn(hSCManager);
- return -1;
- }
- stop = nt_service_stop(hService);
- service_fns.CloseServiceHandle_fn(hService);
- service_fns.CloseServiceHandle_fn(hSCManager);
- return stop;
- }
- static char*
- nt_strerror(uint32_t errnum)
- {
- char *msgbuf;
- FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
- NULL, errnum, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- (LPSTR)&msgbuf, 0, NULL);
- return msgbuf;
- }
- #endif
- #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
- #ifdef MS_WINDOWS_SERVICE
- backup_argv = argv;
- backup_argc = argc;
- if ((argc >= 3) &&
- (!strcmp(argv[1], "-service") || !strcmp(argv[1], "--service"))) {
- nt_service_loadlibrary();
- if (!strcmp(argv[2], "install"))
- return nt_service_install(argc, argv);
- if (!strcmp(argv[2], "remove"))
- return nt_service_remove();
- if (!strcmp(argv[2], "start"))
- return nt_service_cmd_start();
- if (!strcmp(argv[2], "stop"))
- return nt_service_cmd_stop();
- printf("Unrecognized service command '%s'\n", argv[2]);
- return -1;
- }
- if (argc >= 2) {
- if (!strcmp(argv[1], "-nt-service") || !strcmp(argv[1], "--nt-service")) {
- nt_service_loadlibrary();
- nt_service_main();
- return 0;
- }
-
-
- if (!strcmp(argv[1], "-install") || !strcmp(argv[1], "--install")) {
- nt_service_loadlibrary();
- fprintf(stderr,
- "The %s option is deprecated; use \"--service install\" instead.",
- argv[1]);
- return nt_service_install(argc, argv);
- }
- if (!strcmp(argv[1], "-remove") || !strcmp(argv[1], "--remove")) {
- nt_service_loadlibrary();
- fprintf(stderr,
- "The %s option is deprecated; use \"--service remove\" instead.",
- argv[1]);
- return nt_service_remove();
- }
- }
- #endif
- if (tor_init(argc, argv)<0)
- return -1;
- switch (get_options()->command) {
- case CMD_RUN_TOR:
- #ifdef MS_WINDOWS_SERVICE
- service_status.dwCurrentState = 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;
- }
|