12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606 |
- 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);
- 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 connection_t *connection_array[MAXCONNECTIONS+1] =
- { NULL };
- static smartlist_t *closeable_connection_lst = NULL;
- static smartlist_t *active_linked_connection_lst = NULL;
- static int called_loop_once = 0;
- static int n_conns=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);
- tor_assert(conn->conn_array_index == -1);
- if (n_conns >= MAXCONNECTIONS) {
- log_warn(LD_BUG, "Unable to add a connection; MAXCONNECTIONS is set too "
- "low. This is a bug; tell the developers.");
- return -1;
- }
- conn->conn_array_index = n_conns;
- connection_array[n_conns] = conn;
- 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);
- n_conns++;
- log_debug(LD_NET,"new conn type %s, socket %d, n_conns %d.",
- conn_type_to_string(conn->type), conn->s, n_conns);
- return 0;
- }
- int
- connection_remove(connection_t *conn)
- {
- int current_index;
- tor_assert(conn);
- tor_assert(n_conns>0);
- log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
- conn->s, conn_type_to_string(conn->type), n_conns-1);
- tor_assert(conn->conn_array_index >= 0);
- current_index = conn->conn_array_index;
- connection_unregister_events(conn);
- if (current_index == n_conns-1) {
- n_conns--;
- return 0;
- }
-
- n_conns--;
- connection_array[current_index] = connection_array[n_conns];
- connection_array[current_index]->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)
- {
- int i;
- for (i=0; i<n_conns; ++i) {
- if (conn==connection_array[i])
- return 1;
- }
- return 0;
- }
- void
- get_connection_array(connection_t ***array, int *n)
- {
- *array = connection_array;
- *n = n_conns;
- }
- 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)));
- }
- }
- 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 = 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;
- }
- 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 = 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);
- time_to_try_getting_descriptors = now + 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_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(options) && !we_are_hibernating()) {
-
- dirserv_test_reachability(0);
- }
-
- if (time_to_fetch_directory < now) {
-
- if (options->DirPort && !options->V1AuthoritativeDir) {
-
- if (any_trusted_dir_is_v1_authority())
- 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(options) || !options->V1AuthoritativeDir) {
- 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();
-
- 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(0, 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<n_conns;i++) {
- run_connection_housekeeping(i, now);
- }
- if (time_to_shrink_memory < now) {
- for (i=0;i<n_conns;i++) {
- connection_t *conn = connection_array[i];
- if (conn->outbuf)
- buf_shrink(conn->outbuf);
- if (conn->inbuf)
- buf_shrink(conn->inbuf);
- }
- clean_cell_pool();
- 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(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();
- #if 0
- const char *descriptor;
- char keydir[512];
-
- router_rebuild_descriptor(1);
- descriptor = router_get_my_descriptor();
- if (descriptor) {
- tor_snprintf(keydir,sizeof(keydir),"%s"PATH_SEPARATOR"router.desc",
- options->DataDirectory);
- log_info(LD_OR,"Saving descriptor to \"%s\"...",keydir);
- if (write_str_to_file(keydir, descriptor, 0)) {
- return 0;
- }
- }
- #endif
- }
- 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(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)
- {
- int i;
- connection_t *conn;
- time_t now = time(NULL);
- time_t elapsed;
- log(severity, LD_GENERAL, "Dumping stats:");
- for (i=0;i<n_conns;i++) {
- conn = connection_array[i];
- 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[])
- {
- time_of_process_start = time(NULL);
- if (!closeable_connection_lst)
- closeable_connection_lst = smartlist_create();
- if (!active_linked_connection_lst)
- active_linked_connection_lst = smartlist_create();
-
- 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)",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) do { \
- 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; \
- } \
- } while (0)
- 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;
- }
|