main.c 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char main_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file main.c
  10. * \brief Toplevel module. Handles signals, multiplexes between
  11. * connections, implements main loop, and drives scheduled events.
  12. **/
  13. #include "or.h"
  14. #ifdef USE_DMALLOC
  15. #include <dmalloc.h>
  16. #endif
  17. void evdns_shutdown(int);
  18. /********* PROTOTYPES **********/
  19. static void dumpmemusage(int severity);
  20. static void dumpstats(int severity); /* log stats */
  21. static void conn_read_callback(int fd, short event, void *_conn);
  22. static void conn_write_callback(int fd, short event, void *_conn);
  23. static void signal_callback(int fd, short events, void *arg);
  24. static void second_elapsed_callback(int fd, short event, void *args);
  25. static int conn_close_if_marked(int i);
  26. /********* START VARIABLES **********/
  27. int global_read_bucket; /**< Max number of bytes I can read this second. */
  28. int global_write_bucket; /**< Max number of bytes I can write this second. */
  29. /** Max number of relayed (bandwidth class 1) bytes I can read this second. */
  30. int global_relayed_read_bucket;
  31. /** Max number of relayed (bandwidth class 1) bytes I can write this second. */
  32. int global_relayed_write_bucket;
  33. /** What was the read bucket before the last call to prepare_for_pool?
  34. * (used to determine how many bytes we've read). */
  35. static int stats_prev_global_read_bucket;
  36. /** What was the write bucket before the last call to prepare_for_pool?
  37. * (used to determine how many bytes we've written). */
  38. static int stats_prev_global_write_bucket;
  39. /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
  40. /** How many bytes have we read/written since we started the process? */
  41. static uint64_t stats_n_bytes_read = 0;
  42. static uint64_t stats_n_bytes_written = 0;
  43. /** What time did this process start up? */
  44. long time_of_process_start = 0;
  45. /** How many seconds have we been running? */
  46. long stats_n_seconds_working = 0;
  47. /** When do we next download a directory? */
  48. static time_t time_to_fetch_directory = 0;
  49. /** When do we next download a running-routers summary? */
  50. static time_t time_to_fetch_running_routers = 0;
  51. /** When do we next launch DNS wildcarding checks? */
  52. static time_t time_to_check_for_correct_dns = 0;
  53. /** How often will we honor SIGNEWNYM requests? */
  54. #define MAX_SIGNEWNYM_RATE 10
  55. /** When did we last process a SIGNEWNYM request? */
  56. static time_t time_of_last_signewnym = 0;
  57. /** Is there a signewnym request we're currently waiting to handle? */
  58. static int signewnym_is_pending = 0;
  59. /** Array of all open connections. The first n_conns elements are valid. */
  60. /*XXXX020 Should we just use a smartlist here? */
  61. static connection_t *connection_array[MAXCONNECTIONS+1] =
  62. { NULL };
  63. /** List of connections that have been marked for close and need to be freed
  64. * and removed from connection_array. */
  65. static smartlist_t *closeable_connection_lst = NULL;
  66. /** DOCDOC */
  67. static smartlist_t *active_linked_connection_lst = NULL;
  68. /** DOCDOC */
  69. static int called_loop_once = 0;
  70. static int n_conns=0; /**< Number of connections currently active. */
  71. /** We set this to 1 when we've opened a circuit, so we can print a log
  72. * entry to inform the user that Tor is working. */
  73. int has_completed_circuit=0;
  74. #ifdef MS_WINDOWS
  75. #define MS_WINDOWS_SERVICE
  76. #endif
  77. #ifdef MS_WINDOWS_SERVICE
  78. #include <tchar.h>
  79. #define GENSRV_SERVICENAME TEXT("tor")
  80. #define GENSRV_DISPLAYNAME TEXT("Tor Win32 Service")
  81. #define GENSRV_DESCRIPTION \
  82. TEXT("Provides an anonymous Internet communication system")
  83. #define GENSRV_USERACCT TEXT("NT AUTHORITY\\LocalService")
  84. // Cheating: using the pre-defined error codes, tricks Windows into displaying
  85. // a semi-related human-readable error message if startup fails as
  86. // opposed to simply scaring people with Error: 0xffffffff
  87. #define NT_SERVICE_ERROR_TORINIT_FAILED ERROR_EXCEPTION_IN_SERVICE
  88. SERVICE_STATUS service_status;
  89. SERVICE_STATUS_HANDLE hStatus;
  90. /* XXXX This 'backup argv' and 'backup argc' business is an ugly hack. This
  91. * is a job for arguments, not globals. */
  92. static char **backup_argv;
  93. static int backup_argc;
  94. static int nt_service_is_stopping(void);
  95. static char* nt_strerror(uint32_t errnum);
  96. #else
  97. #define nt_service_is_stopping() (0)
  98. #endif
  99. /** If our router descriptor ever goes this long without being regenerated
  100. * because something changed, we force an immediate regenerate-and-upload. */
  101. #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
  102. /** How often do we check whether part of our router info has changed in a way
  103. * that would require an upload? */
  104. #define CHECK_DESCRIPTOR_INTERVAL (60)
  105. /** How often do we (as a router) check whether our IP address has changed? */
  106. #define CHECK_IPADDRESS_INTERVAL (15*60)
  107. /** How often do we check buffers and pools for empty space that can be
  108. * deallocated? */
  109. #define MEM_SHRINK_INTERVAL (60)
  110. /** How often do we check for router descriptors that we should download? */
  111. #define DESCRIPTOR_RETRY_INTERVAL (10)
  112. /** How often do we 'forgive' undownloadable router descriptors and attempt
  113. * to download them again? */
  114. #define DESCRIPTOR_FAILURE_RESET_INTERVAL (60*60)
  115. /** How often do we add more entropy to OpenSSL's RNG pool? */
  116. #define ENTROPY_INTERVAL (60*60)
  117. /** How long do we let a directory connection stall before expiring it? */
  118. #define DIR_CONN_MAX_STALL (5*60)
  119. /** How old do we let a connection to an OR get before deciding it's
  120. * obsolete? */
  121. #define TIME_BEFORE_OR_CONN_IS_OBSOLETE (60*60*24*7)
  122. /** How long do we let OR connections handshake before we decide that
  123. * they are obsolete? */
  124. #define TLS_HANDSHAKE_TIMEOUT (60)
  125. /** How often do we write hidden service usage statistics to disk? */
  126. #define WRITE_HSUSAGE_INTERVAL (900)
  127. /********* END VARIABLES ************/
  128. /****************************************************************************
  129. *
  130. * This section contains accessors and other methods on the connection_array
  131. * variables (which are global within this file and unavailable outside it).
  132. *
  133. ****************************************************************************/
  134. /** Add <b>conn</b> to the array of connections that we can poll on. The
  135. * connection's socket must be set; the connection starts out
  136. * non-reading and non-writing.
  137. */
  138. int
  139. connection_add(connection_t *conn)
  140. {
  141. tor_assert(conn);
  142. tor_assert(conn->s >= 0 || conn->linked);
  143. tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
  144. if (n_conns >= MAXCONNECTIONS) {
  145. log_warn(LD_BUG, "Unable to add a connection; MAXCONNECTIONS is set too "
  146. "low. This is a bug; tell the developers.");
  147. return -1;
  148. }
  149. conn->conn_array_index = n_conns;
  150. connection_array[n_conns] = conn;
  151. conn->read_event = tor_malloc_zero(sizeof(struct event));
  152. conn->write_event = tor_malloc_zero(sizeof(struct event));
  153. event_set(conn->read_event, conn->s, EV_READ|EV_PERSIST,
  154. conn_read_callback, conn);
  155. event_set(conn->write_event, conn->s, EV_WRITE|EV_PERSIST,
  156. conn_write_callback, conn);
  157. n_conns++;
  158. log_debug(LD_NET,"new conn type %s, socket %d, n_conns %d.",
  159. conn_type_to_string(conn->type), conn->s, n_conns);
  160. return 0;
  161. }
  162. /** Remove the connection from the global list, and remove the
  163. * corresponding poll entry. Calling this function will shift the last
  164. * connection (if any) into the position occupied by conn.
  165. */
  166. int
  167. connection_remove(connection_t *conn)
  168. {
  169. int current_index;
  170. tor_assert(conn);
  171. tor_assert(n_conns>0);
  172. log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
  173. conn->s, conn_type_to_string(conn->type), n_conns-1);
  174. tor_assert(conn->conn_array_index >= 0);
  175. current_index = conn->conn_array_index;
  176. connection_unregister_events(conn); /* This is redundant, but cheap. */
  177. if (current_index == n_conns-1) { /* this is the end */
  178. n_conns--;
  179. return 0;
  180. }
  181. /* replace this one with the one at the end */
  182. n_conns--;
  183. connection_array[current_index] = connection_array[n_conns];
  184. connection_array[current_index]->conn_array_index = current_index;
  185. return 0;
  186. }
  187. /** If <b>conn</b> is an edge conn, remove it from the list
  188. * of conn's on this circuit. If it's not on an edge,
  189. * flush and send destroys for all circuits on this conn.
  190. *
  191. * Remove it from connection_array (if applicable) and
  192. * from closeable_connection_list.
  193. *
  194. * Then free it.
  195. */
  196. static void
  197. connection_unlink(connection_t *conn)
  198. {
  199. connection_about_to_close_connection(conn);
  200. if (conn->conn_array_index >= 0) {
  201. connection_remove(conn);
  202. }
  203. if (conn->linked_conn) {
  204. conn->linked_conn->linked_conn = NULL;
  205. if (! conn->linked_conn->marked_for_close &&
  206. conn->linked_conn->reading_from_linked_conn)
  207. connection_start_reading(conn->linked_conn);
  208. conn->linked_conn = NULL;
  209. }
  210. smartlist_remove(closeable_connection_lst, conn);
  211. smartlist_remove(active_linked_connection_lst, conn);
  212. if (conn->type == CONN_TYPE_EXIT) {
  213. assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
  214. }
  215. if (conn->type == CONN_TYPE_OR) {
  216. if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
  217. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  218. }
  219. connection_free(conn);
  220. }
  221. /** Schedule <b>conn</b> to be closed. **/
  222. void
  223. add_connection_to_closeable_list(connection_t *conn)
  224. {
  225. tor_assert(!smartlist_isin(closeable_connection_lst, conn));
  226. tor_assert(conn->marked_for_close);
  227. assert_connection_ok(conn, time(NULL));
  228. smartlist_add(closeable_connection_lst, conn);
  229. }
  230. /** Return 1 if conn is on the closeable list, else return 0. */
  231. int
  232. connection_is_on_closeable_list(connection_t *conn)
  233. {
  234. return smartlist_isin(closeable_connection_lst, conn);
  235. }
  236. /** Return true iff conn is in the current poll array. */
  237. int
  238. connection_in_array(connection_t *conn)
  239. {
  240. int i;
  241. for (i=0; i<n_conns; ++i) {
  242. if (conn==connection_array[i])
  243. return 1;
  244. }
  245. return 0;
  246. }
  247. /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
  248. * to the length of the array. <b>*array</b> and <b>*n</b> must not
  249. * be modified.
  250. */
  251. void
  252. get_connection_array(connection_t ***array, int *n)
  253. {
  254. *array = connection_array;
  255. *n = n_conns;
  256. }
  257. /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
  258. * mask is a bitmask whose bits are EV_READ and EV_WRITE.)
  259. */
  260. void
  261. connection_watch_events(connection_t *conn, short events)
  262. {
  263. if (events & EV_READ)
  264. connection_start_reading(conn);
  265. else
  266. connection_stop_reading(conn);
  267. if (events & EV_WRITE)
  268. connection_start_writing(conn);
  269. else
  270. connection_stop_writing(conn);
  271. }
  272. /** Return true iff <b>conn</b> is listening for read events. */
  273. int
  274. connection_is_reading(connection_t *conn)
  275. {
  276. tor_assert(conn);
  277. return conn->reading_from_linked_conn ||
  278. (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
  279. }
  280. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  281. void
  282. connection_stop_reading(connection_t *conn)
  283. {
  284. tor_assert(conn);
  285. tor_assert(conn->read_event);
  286. if (conn->linked) {
  287. conn->reading_from_linked_conn = 0;
  288. connection_stop_reading_from_linked_conn(conn);
  289. } else {
  290. if (event_del(conn->read_event))
  291. log_warn(LD_NET, "Error from libevent setting read event state for %d "
  292. "to unwatched: %s",
  293. conn->s,
  294. tor_socket_strerror(tor_socket_errno(conn->s)));
  295. }
  296. }
  297. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  298. void
  299. connection_start_reading(connection_t *conn)
  300. {
  301. tor_assert(conn);
  302. tor_assert(conn->read_event);
  303. if (conn->linked) {
  304. conn->reading_from_linked_conn = 1;
  305. if (connection_should_read_from_linked_conn(conn))
  306. connection_start_reading_from_linked_conn(conn);
  307. } else {
  308. if (event_add(conn->read_event, NULL))
  309. log_warn(LD_NET, "Error from libevent setting read event state for %d "
  310. "to watched: %s",
  311. conn->s,
  312. tor_socket_strerror(tor_socket_errno(conn->s)));
  313. }
  314. }
  315. /** Return true iff <b>conn</b> is listening for write events. */
  316. int
  317. connection_is_writing(connection_t *conn)
  318. {
  319. tor_assert(conn);
  320. return conn->writing_to_linked_conn ||
  321. (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
  322. }
  323. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  324. void
  325. connection_stop_writing(connection_t *conn)
  326. {
  327. tor_assert(conn);
  328. tor_assert(conn->write_event);
  329. if (conn->linked) {
  330. conn->writing_to_linked_conn = 0;
  331. if (conn->linked_conn)
  332. connection_stop_reading_from_linked_conn(conn->linked_conn);
  333. } else {
  334. if (event_del(conn->write_event))
  335. log_warn(LD_NET, "Error from libevent setting write event state for %d "
  336. "to unwatched: %s",
  337. conn->s,
  338. tor_socket_strerror(tor_socket_errno(conn->s)));
  339. }
  340. }
  341. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  342. void
  343. connection_start_writing(connection_t *conn)
  344. {
  345. tor_assert(conn);
  346. tor_assert(conn->write_event);
  347. if (conn->linked) {
  348. conn->writing_to_linked_conn = 1;
  349. if (conn->linked_conn &&
  350. connection_should_read_from_linked_conn(conn->linked_conn))
  351. connection_start_reading_from_linked_conn(conn->linked_conn);
  352. } else {
  353. if (event_add(conn->write_event, NULL))
  354. log_warn(LD_NET, "Error from libevent setting write event state for %d "
  355. "to watched: %s",
  356. conn->s,
  357. tor_socket_strerror(tor_socket_errno(conn->s)));
  358. }
  359. }
  360. /** DOCDOC*/
  361. void
  362. connection_start_reading_from_linked_conn(connection_t *conn)
  363. {
  364. tor_assert(conn);
  365. tor_assert(conn->linked == 1);
  366. if (!conn->active_on_link) {
  367. conn->active_on_link = 1;
  368. smartlist_add(active_linked_connection_lst, conn);
  369. if (!called_loop_once) {
  370. /* This is the first event on the list; we won't be in LOOP_ONCE mode,
  371. * so we need to make sure that the event_loop() actually exits at the
  372. * end of its run through the current connections and
  373. * lets us activate read events for linked connections. */
  374. struct timeval tv = { 0, 0 };
  375. event_loopexit(&tv);
  376. }
  377. } else {
  378. tor_assert(smartlist_isin(active_linked_connection_lst, conn));
  379. }
  380. }
  381. /** DOCDOC*/
  382. void
  383. connection_stop_reading_from_linked_conn(connection_t *conn)
  384. {
  385. tor_assert(conn);
  386. tor_assert(conn->linked == 1);
  387. if (conn->active_on_link) {
  388. conn->active_on_link = 0;
  389. /* XXXX020 maybe we should keep an index here so we can smartlist_del
  390. * cleanly. */
  391. smartlist_remove(active_linked_connection_lst, conn);
  392. } else {
  393. tor_assert(!smartlist_isin(active_linked_connection_lst, conn));
  394. }
  395. }
  396. /** Close all connections that have been scheduled to get closed. */
  397. static void
  398. close_closeable_connections(void)
  399. {
  400. int i;
  401. for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
  402. connection_t *conn = smartlist_get(closeable_connection_lst, i);
  403. if (conn->conn_array_index < 0) {
  404. connection_unlink(conn); /* blow it away right now */
  405. } else {
  406. if (!conn_close_if_marked(conn->conn_array_index))
  407. ++i;
  408. }
  409. }
  410. }
  411. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  412. * some data to read. */
  413. static void
  414. conn_read_callback(int fd, short event, void *_conn)
  415. {
  416. connection_t *conn = _conn;
  417. (void)fd;
  418. (void)event;
  419. log_debug(LD_NET,"socket %d wants to read.",conn->s);
  420. assert_connection_ok(conn, time(NULL));
  421. if (connection_handle_read(conn) < 0) {
  422. if (!conn->marked_for_close) {
  423. #ifndef MS_WINDOWS
  424. log_warn(LD_BUG,"Unhandled error on read for %s connection "
  425. "(fd %d); removing",
  426. conn_type_to_string(conn->type), conn->s);
  427. tor_fragile_assert();
  428. #endif
  429. if (CONN_IS_EDGE(conn))
  430. connection_edge_end_errno(TO_EDGE_CONN(conn));
  431. connection_mark_for_close(conn);
  432. }
  433. }
  434. assert_connection_ok(conn, time(NULL));
  435. if (smartlist_len(closeable_connection_lst))
  436. close_closeable_connections();
  437. }
  438. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  439. * some data to write. */
  440. static void
  441. conn_write_callback(int fd, short events, void *_conn)
  442. {
  443. connection_t *conn = _conn;
  444. (void)fd;
  445. (void)events;
  446. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",conn->s));
  447. assert_connection_ok(conn, time(NULL));
  448. if (connection_handle_write(conn, 0) < 0) {
  449. if (!conn->marked_for_close) {
  450. /* this connection is broken. remove it. */
  451. log_fn(LOG_WARN,LD_BUG,
  452. "unhandled error on write for %s connection (fd %d); removing",
  453. conn_type_to_string(conn->type), conn->s);
  454. tor_fragile_assert();
  455. if (CONN_IS_EDGE(conn)) {
  456. /* otherwise we cry wolf about duplicate close */
  457. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  458. if (!edge_conn->end_reason)
  459. edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
  460. conn->edge_has_sent_end = 1;
  461. }
  462. /* XXX do we need a close-immediate here, so we don't try to flush? */
  463. connection_mark_for_close(conn);
  464. }
  465. }
  466. assert_connection_ok(conn, time(NULL));
  467. if (smartlist_len(closeable_connection_lst))
  468. close_closeable_connections();
  469. }
  470. /** If the connection at connection_array[i] is marked for close, then:
  471. * - If it has data that it wants to flush, try to flush it.
  472. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  473. * true, then leave the connection open and return.
  474. * - Otherwise, remove the connection from connection_array and from
  475. * all other lists, close it, and free it.
  476. * Returns 1 if the connection was closed, 0 otherwise.
  477. */
  478. static int
  479. conn_close_if_marked(int i)
  480. {
  481. connection_t *conn;
  482. int retval;
  483. conn = connection_array[i];
  484. if (!conn->marked_for_close)
  485. return 0; /* nothing to see here, move along */
  486. assert_connection_ok(conn, time(NULL));
  487. assert_all_pending_dns_resolves_ok();
  488. log_debug(LD_NET,"Cleaning up connection (fd %d).",conn->s);
  489. if ((conn->s >= 0 || conn->linked_conn) && connection_wants_to_flush(conn)) {
  490. /* s == -1 means it's an incomplete edge connection, or that the socket
  491. * has already been closed as unflushable. */
  492. int sz = connection_bucket_write_limit(conn);
  493. if (!conn->hold_open_until_flushed)
  494. log_info(LD_NET,
  495. "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
  496. "to flush %d bytes. (Marked at %s:%d)",
  497. escaped_safe_str(conn->address),
  498. conn->s, conn_type_to_string(conn->type), conn->state,
  499. (int)conn->outbuf_flushlen,
  500. conn->marked_for_close_file, conn->marked_for_close);
  501. if (conn->linked_conn) {
  502. retval = move_buf_to_buf(conn->linked_conn->inbuf, conn->outbuf,
  503. &conn->outbuf_flushlen);
  504. if (retval >= 0) {
  505. /* The linked conn will notice that it has data when it notices that
  506. * we're gone. */
  507. connection_start_reading_from_linked_conn(conn->linked_conn);
  508. }
  509. /* XXXX020 Downgrade to debug. */
  510. log_info(LD_GENERAL, "Flushed last %d bytes from a linked conn; "
  511. "%d left; flushlen %d; wants-to-flush==%d", retval,
  512. (int)buf_datalen(conn->outbuf),
  513. (int)conn->outbuf_flushlen,
  514. connection_wants_to_flush(conn));
  515. } else if (connection_speaks_cells(conn)) {
  516. if (conn->state == OR_CONN_STATE_OPEN) {
  517. retval = flush_buf_tls(TO_OR_CONN(conn)->tls, conn->outbuf, sz,
  518. &conn->outbuf_flushlen);
  519. } else
  520. retval = -1; /* never flush non-open broken tls connections */
  521. } else {
  522. retval = flush_buf(conn->s, conn->outbuf, sz, &conn->outbuf_flushlen);
  523. }
  524. if (retval >= 0 && /* Technically, we could survive things like
  525. TLS_WANT_WRITE here. But don't bother for now. */
  526. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  527. if (retval > 0)
  528. LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
  529. "Holding conn (fd %d) open for more flushing.",
  530. conn->s));
  531. /* XXX should we reset timestamp_lastwritten here? */
  532. return 0;
  533. }
  534. if (connection_wants_to_flush(conn)) {
  535. int severity;
  536. if (conn->type == CONN_TYPE_EXIT ||
  537. (conn->type == CONN_TYPE_OR && server_mode(get_options())) ||
  538. (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER))
  539. severity = LOG_INFO;
  540. else
  541. severity = LOG_NOTICE;
  542. /* XXXX Maybe allow this to happen a certain amount per hour; it usually
  543. * is meaningless. */
  544. log_fn(severity, LD_NET, "We stalled too much while trying to write %d "
  545. "bytes to address %s. If this happens a lot, either "
  546. "something is wrong with your network connection, or "
  547. "something is wrong with theirs. "
  548. "(fd %d, type %s, state %d, marked at %s:%d).",
  549. (int)buf_datalen(conn->outbuf),
  550. escaped_safe_str(conn->address), conn->s,
  551. conn_type_to_string(conn->type), conn->state,
  552. conn->marked_for_close_file,
  553. conn->marked_for_close);
  554. }
  555. }
  556. connection_unlink(conn); /* unlink, remove, free */
  557. return 1;
  558. }
  559. /** We've just tried every dirserver we know about, and none of
  560. * them were reachable. Assume the network is down. Change state
  561. * so next time an application connection arrives we'll delay it
  562. * and try another directory fetch. Kill off all the circuit_wait
  563. * streams that are waiting now, since they will all timeout anyway.
  564. */
  565. void
  566. directory_all_unreachable(time_t now)
  567. {
  568. connection_t *conn;
  569. (void)now;
  570. stats_n_seconds_working=0; /* reset it */
  571. while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
  572. AP_CONN_STATE_CIRCUIT_WAIT))) {
  573. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  574. log_notice(LD_NET,
  575. "Is your network connection down? "
  576. "Failing connection to '%s:%d'.",
  577. safe_str(edge_conn->socks_request->address),
  578. edge_conn->socks_request->port);
  579. connection_mark_unattached_ap(edge_conn,
  580. END_STREAM_REASON_NET_UNREACHABLE);
  581. }
  582. control_event_general_status(LOG_ERR, "DIR_ALL_UNREACHABLE");
  583. }
  584. /** This function is called whenever we successfully pull down some new
  585. * network statuses or server descriptors. */
  586. void
  587. directory_info_has_arrived(time_t now, int from_cache)
  588. {
  589. or_options_t *options = get_options();
  590. if (!router_have_minimum_dir_info()) {
  591. log(LOG_NOTICE, LD_DIR,
  592. "I learned some more directory information, but not enough to "
  593. "build a circuit.");
  594. update_router_descriptor_downloads(now);
  595. return;
  596. }
  597. if (server_mode(options) && !we_are_hibernating() && !from_cache &&
  598. (has_completed_circuit || !any_predicted_circuits(now)))
  599. consider_testing_reachability(1, 1);
  600. }
  601. /** Perform regular maintenance tasks for a single connection. This
  602. * function gets run once per second per connection by run_scheduled_events.
  603. */
  604. static void
  605. run_connection_housekeeping(int i, time_t now)
  606. {
  607. cell_t cell;
  608. connection_t *conn = connection_array[i];
  609. or_options_t *options = get_options();
  610. or_connection_t *or_conn;
  611. if (conn->outbuf && !buf_datalen(conn->outbuf) && conn->type == CONN_TYPE_OR)
  612. TO_OR_CONN(conn)->timestamp_lastempty = now;
  613. if (conn->marked_for_close) {
  614. /* nothing to do here */
  615. return;
  616. }
  617. /* Expire any directory connections that haven't been active (sent
  618. * if a server or received if a client) for 5 min */
  619. if (conn->type == CONN_TYPE_DIR &&
  620. ((DIR_CONN_IS_SERVER(conn) &&
  621. conn->timestamp_lastwritten + DIR_CONN_MAX_STALL < now) ||
  622. (!DIR_CONN_IS_SERVER(conn) &&
  623. conn->timestamp_lastread + DIR_CONN_MAX_STALL < now))) {
  624. log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
  625. conn->s, conn->purpose);
  626. /* This check is temporary; it's to let us know whether we should consider
  627. * parsing partial serverdesc responses. */
  628. if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  629. buf_datalen(conn->inbuf)>=1024) {
  630. log_info(LD_DIR,"Trying to extract information from wedged server desc "
  631. "download.");
  632. connection_dir_reached_eof(TO_DIR_CONN(conn));
  633. } else {
  634. connection_mark_for_close(conn);
  635. }
  636. return;
  637. }
  638. if (!connection_speaks_cells(conn))
  639. return; /* we're all done here, the rest is just for OR conns */
  640. or_conn = TO_OR_CONN(conn);
  641. if (!conn->or_is_obsolete) {
  642. if (conn->timestamp_created + TIME_BEFORE_OR_CONN_IS_OBSOLETE < now) {
  643. log_info(LD_OR,
  644. "Marking OR conn to %s:%d obsolete (fd %d, %d secs old).",
  645. conn->address, conn->port, conn->s,
  646. (int)(now - conn->timestamp_created));
  647. conn->or_is_obsolete = 1;
  648. } else {
  649. or_connection_t *best =
  650. connection_or_get_by_identity_digest(or_conn->identity_digest);
  651. if (best && best != or_conn &&
  652. (conn->state == OR_CONN_STATE_OPEN ||
  653. now > conn->timestamp_created + TLS_HANDSHAKE_TIMEOUT)) {
  654. /* We only mark as obsolete connections that already are in
  655. * OR_CONN_STATE_OPEN, i.e. that have finished their TLS handshaking.
  656. * This is necessary because authorities judge whether a router is
  657. * reachable based on whether they were able to TLS handshake with it
  658. * recently. Without this check we would expire connections too
  659. * early for router->last_reachable to be updated.
  660. */
  661. log_info(LD_OR,
  662. "Marking duplicate conn to %s:%d obsolete "
  663. "(fd %d, %d secs old).",
  664. conn->address, conn->port, conn->s,
  665. (int)(now - conn->timestamp_created));
  666. conn->or_is_obsolete = 1;
  667. }
  668. }
  669. }
  670. if (conn->or_is_obsolete && !or_conn->n_circuits) {
  671. /* no unmarked circs -- mark it now */
  672. log_info(LD_OR,
  673. "Expiring non-used OR connection to fd %d (%s:%d) [Obsolete].",
  674. conn->s, conn->address, conn->port);
  675. connection_mark_for_close(conn);
  676. conn->hold_open_until_flushed = 1;
  677. return;
  678. }
  679. /* If we haven't written to an OR connection for a while, then either nuke
  680. the connection or send a keepalive, depending. */
  681. if (now >= conn->timestamp_lastwritten + options->KeepalivePeriod) {
  682. routerinfo_t *router = router_get_by_digest(or_conn->identity_digest);
  683. if (!connection_state_is_open(conn)) {
  684. log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
  685. conn->s,conn->address, conn->port);
  686. connection_mark_for_close(conn);
  687. conn->hold_open_until_flushed = 1;
  688. } else if (we_are_hibernating() && !or_conn->n_circuits &&
  689. !buf_datalen(conn->outbuf)) {
  690. log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
  691. "[Hibernating or exiting].",
  692. conn->s,conn->address, conn->port);
  693. connection_mark_for_close(conn);
  694. conn->hold_open_until_flushed = 1;
  695. } else if (!clique_mode(options) && !or_conn->n_circuits &&
  696. (!router || !server_mode(options) ||
  697. !router_is_clique_mode(router))) {
  698. log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
  699. "[Not in clique mode].",
  700. conn->s,conn->address, conn->port);
  701. connection_mark_for_close(conn);
  702. conn->hold_open_until_flushed = 1;
  703. } else if (
  704. now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
  705. now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
  706. log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
  707. "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
  708. "flush; %d seconds since last write)",
  709. conn->s, conn->address, conn->port,
  710. (int)buf_datalen(conn->outbuf),
  711. (int)(now-conn->timestamp_lastwritten));
  712. connection_mark_for_close(conn);
  713. } else if (!buf_datalen(conn->outbuf)) {
  714. /* either in clique mode, or we've got a circuit. send a padding cell. */
  715. log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
  716. conn->address, conn->port);
  717. memset(&cell,0,sizeof(cell_t));
  718. cell.command = CELL_PADDING;
  719. connection_or_write_cell_to_buf(&cell, or_conn);
  720. }
  721. }
  722. }
  723. /** Perform regular maintenance tasks. This function gets run once per
  724. * second by prepare_for_poll.
  725. */
  726. static void
  727. run_scheduled_events(time_t now)
  728. {
  729. static time_t last_rotated_certificate = 0;
  730. static time_t time_to_check_listeners = 0;
  731. static time_t time_to_check_descriptor = 0;
  732. static time_t time_to_check_ipaddress = 0;
  733. static time_t time_to_shrink_memory = 0;
  734. static time_t time_to_try_getting_descriptors = 0;
  735. static time_t time_to_reset_descriptor_failures = 0;
  736. static time_t time_to_add_entropy = 0;
  737. static time_t time_to_write_hs_statistics = 0;
  738. or_options_t *options = get_options();
  739. int i;
  740. int have_dir_info;
  741. /** 0. See if we've been asked to shut down and our timeout has
  742. * expired; or if our bandwidth limits are exhausted and we
  743. * should hibernate; or if it's time to wake up from hibernation.
  744. */
  745. consider_hibernation(now);
  746. /* 0b. If we've deferred a signewnym, make sure it gets handled
  747. * eventually */
  748. if (signewnym_is_pending &&
  749. time_of_last_signewnym + MAX_SIGNEWNYM_RATE <= now) {
  750. log(LOG_INFO, LD_CONTROL, "Honoring delayed NEWNYM request");
  751. circuit_expire_all_dirty_circs();
  752. addressmap_clear_transient();
  753. time_of_last_signewnym = now;
  754. signewnym_is_pending = 0;
  755. }
  756. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  757. * shut down and restart all cpuworkers, and update the directory if
  758. * necessary.
  759. */
  760. if (server_mode(options) &&
  761. get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  762. log_info(LD_GENERAL,"Rotating onion key.");
  763. rotate_onion_key();
  764. cpuworkers_rotate();
  765. if (router_rebuild_descriptor(1)<0) {
  766. log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
  767. }
  768. if (advertised_server_mode())
  769. router_upload_dir_desc_to_dirservers(0);
  770. }
  771. if (time_to_try_getting_descriptors < now) {
  772. /* XXXX Maybe we should do this every 10sec when not enough info,
  773. * and every 60sec when we have enough info -NM */
  774. update_router_descriptor_downloads(now);
  775. time_to_try_getting_descriptors = now + DESCRIPTOR_RETRY_INTERVAL;
  776. }
  777. if (time_to_reset_descriptor_failures < now) {
  778. router_reset_descriptor_download_failures();
  779. time_to_reset_descriptor_failures =
  780. now + DESCRIPTOR_FAILURE_RESET_INTERVAL;
  781. }
  782. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  783. if (!last_rotated_certificate)
  784. last_rotated_certificate = now;
  785. if (last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
  786. log_info(LD_GENERAL,"Rotating tls context.");
  787. if (tor_tls_context_new(get_identity_key(), options->Nickname,
  788. MAX_SSL_KEY_LIFETIME) < 0) {
  789. log_warn(LD_BUG, "Error reinitializing TLS context");
  790. /* XXX is it a bug here, that we just keep going? */
  791. }
  792. last_rotated_certificate = now;
  793. /* XXXX We should rotate TLS connections as well; this code doesn't change
  794. * them at all. */
  795. }
  796. if (time_to_add_entropy == 0)
  797. time_to_add_entropy = now + ENTROPY_INTERVAL;
  798. if (time_to_add_entropy < now) {
  799. /* We already seeded once, so don't die on failure. */
  800. crypto_seed_rng();
  801. time_to_add_entropy = now + ENTROPY_INTERVAL;
  802. }
  803. /** 1c. If we have to change the accounting interval or record
  804. * bandwidth used in this accounting interval, do so. */
  805. if (accounting_is_enabled(options))
  806. accounting_run_housekeeping(now);
  807. if (now % 10 == 0 && authdir_mode(options) && !we_are_hibernating()) {
  808. /* try to determine reachability of the other Tor servers */
  809. dirserv_test_reachability(0);
  810. }
  811. /** 2. Periodically, we consider getting a new directory, getting a
  812. * new running-routers list, and/or force-uploading our descriptor
  813. * (if we've passed our internal checks). */
  814. if (time_to_fetch_directory < now) {
  815. /* Only caches actually need to fetch directories now. */
  816. if (options->DirPort && !options->V1AuthoritativeDir) {
  817. /* XXX actually, we should only do this if we want to advertise
  818. * our dirport. not simply if we configured one. -RD */
  819. if (any_trusted_dir_is_v1_authority())
  820. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
  821. }
  822. /** How often do we (as a cache) fetch a new V1 directory? */
  823. #define V1_DIR_FETCH_PERIOD (6*60*60)
  824. time_to_fetch_directory = now + V1_DIR_FETCH_PERIOD;
  825. }
  826. /* Caches need to fetch running_routers; directory clients don't. */
  827. if (options->DirPort && time_to_fetch_running_routers < now) {
  828. if (!authdir_mode(options) || !options->V1AuthoritativeDir) {
  829. directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST, NULL, 1);
  830. }
  831. /** How often do we (as a cache) fetch a new V1 runningrouters document? */
  832. #define V1_RUNNINGROUTERS_FETCH_PERIOD (30*60)
  833. time_to_fetch_running_routers = now + V1_RUNNINGROUTERS_FETCH_PERIOD;
  834. /* Also, take this chance to remove old information from rephist
  835. * and the rend cache. */
  836. rep_history_clean(now - options->RephistTrackTime);
  837. rend_cache_clean();
  838. }
  839. /* 2b. Once per minute, regenerate and upload the descriptor if the old
  840. * one is inaccurate. */
  841. if (time_to_check_descriptor < now) {
  842. static int dirport_reachability_count = 0;
  843. time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
  844. check_descriptor_bandwidth_changed(now);
  845. if (time_to_check_ipaddress < now) {
  846. time_to_check_ipaddress = now + CHECK_IPADDRESS_INTERVAL;
  847. check_descriptor_ipaddress_changed(now);
  848. }
  849. mark_my_descriptor_dirty_if_older_than(
  850. now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL);
  851. consider_publishable_server(0);
  852. /* also, check religiously for reachability, if it's within the first
  853. * 20 minutes of our uptime. */
  854. if (server_mode(options) &&
  855. (has_completed_circuit || !any_predicted_circuits(now)) &&
  856. stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT &&
  857. !we_are_hibernating()) {
  858. consider_testing_reachability(1, dirport_reachability_count==0);
  859. if (++dirport_reachability_count > 5)
  860. dirport_reachability_count = 0;
  861. }
  862. /* If any networkstatus documents are no longer recent, we need to
  863. * update all the descriptors' running status. */
  864. /* purge obsolete entries */
  865. routerlist_remove_old_routers();
  866. networkstatus_list_clean(now);
  867. networkstatus_list_update_recent(now);
  868. routers_update_all_from_networkstatus();
  869. /* Also, once per minute, check whether we want to download any
  870. * networkstatus documents.
  871. */
  872. update_networkstatus_downloads(now);
  873. }
  874. /** 3a. Every second, we examine pending circuits and prune the
  875. * ones which have been pending for more than a few seconds.
  876. * We do this before step 4, so it can try building more if
  877. * it's not comfortable with the number of available circuits.
  878. */
  879. circuit_expire_building(now);
  880. /** 3b. Also look at pending streams and prune the ones that 'began'
  881. * a long time ago but haven't gotten a 'connected' yet.
  882. * Do this before step 4, so we can put them back into pending
  883. * state to be picked up by the new circuit.
  884. */
  885. connection_ap_expire_beginning();
  886. /** 3c. And expire connections that we've held open for too long.
  887. */
  888. connection_expire_held_open();
  889. /** 3d. And every 60 seconds, we relaunch listeners if any died. */
  890. if (!we_are_hibernating() && time_to_check_listeners < now) {
  891. /* 0 means "only launch the ones that died." */
  892. retry_all_listeners(0, NULL, NULL);
  893. time_to_check_listeners = now+60;
  894. }
  895. /** 4. Every second, we try a new circuit if there are no valid
  896. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  897. * that became dirty more than MaxCircuitDirtiness seconds ago,
  898. * and we make a new circ if there are no clean circuits.
  899. */
  900. have_dir_info = router_have_minimum_dir_info();
  901. if (have_dir_info && !we_are_hibernating())
  902. circuit_build_needed_circs(now);
  903. /** 5. We do housekeeping for each connection... */
  904. for (i=0;i<n_conns;i++) {
  905. run_connection_housekeeping(i, now);
  906. }
  907. if (time_to_shrink_memory < now) {
  908. for (i=0;i<n_conns;i++) {
  909. connection_t *conn = connection_array[i];
  910. if (conn->outbuf)
  911. buf_shrink(conn->outbuf);
  912. if (conn->inbuf)
  913. buf_shrink(conn->inbuf);
  914. }
  915. clean_cell_pool();
  916. time_to_shrink_memory = now + MEM_SHRINK_INTERVAL;
  917. }
  918. /** 6. And remove any marked circuits... */
  919. circuit_close_all_marked();
  920. /** 7. And upload service descriptors if necessary. */
  921. if (has_completed_circuit && !we_are_hibernating())
  922. rend_consider_services_upload(now);
  923. /** 8. and blow away any connections that need to die. have to do this now,
  924. * because if we marked a conn for close and left its socket -1, then
  925. * we'll pass it to poll/select and bad things will happen.
  926. */
  927. close_closeable_connections();
  928. /** 8b. And if anything in our state is ready to get flushed to disk, we
  929. * flush it. */
  930. or_state_save(now);
  931. /** 9. and if we're a server, check whether our DNS is telling stories to
  932. * us. */
  933. if (server_mode(options) && time_to_check_for_correct_dns < now) {
  934. if (!time_to_check_for_correct_dns) {
  935. time_to_check_for_correct_dns = now + 60 + crypto_rand_int(120);
  936. } else {
  937. dns_launch_correctness_checks();
  938. time_to_check_for_correct_dns = now + 12*3600 +
  939. crypto_rand_int(12*3600);
  940. }
  941. }
  942. /** 10. write hidden service usage statistic to disk */
  943. if (options->HSAuthorityRecordStats && time_to_write_hs_statistics < now) {
  944. hs_usage_write_statistics_to_file(now);
  945. time_to_write_hs_statistics = now+WRITE_HSUSAGE_INTERVAL;
  946. }
  947. }
  948. /** Libevent timer: used to invoke second_elapsed_callback() once per
  949. * second. */
  950. static struct event *timeout_event = NULL;
  951. /** Number of libevent errors in the last second: we die if we get too many. */
  952. static int n_libevent_errors = 0;
  953. /** Libevent callback: invoked once every second. */
  954. static void
  955. second_elapsed_callback(int fd, short event, void *args)
  956. {
  957. /* XXXX This could be sensibly refactored into multiple callbacks, and we
  958. * could use libevent's timers for this rather than checking the current
  959. * time against a bunch of timeouts every second. */
  960. static struct timeval one_second;
  961. static long current_second = 0;
  962. struct timeval now;
  963. size_t bytes_written;
  964. size_t bytes_read;
  965. int seconds_elapsed;
  966. or_options_t *options = get_options();
  967. (void)fd;
  968. (void)event;
  969. (void)args;
  970. if (!timeout_event) {
  971. timeout_event = tor_malloc_zero(sizeof(struct event));
  972. evtimer_set(timeout_event, second_elapsed_callback, NULL);
  973. one_second.tv_sec = 1;
  974. one_second.tv_usec = 0;
  975. }
  976. n_libevent_errors = 0;
  977. /* log_fn(LOG_NOTICE, "Tick."); */
  978. tor_gettimeofday(&now);
  979. /* the second has rolled over. check more stuff. */
  980. bytes_written = stats_prev_global_write_bucket - global_write_bucket;
  981. bytes_read = stats_prev_global_read_bucket - global_read_bucket;
  982. seconds_elapsed = current_second ? (now.tv_sec - current_second) : 0;
  983. stats_n_bytes_read += bytes_read;
  984. stats_n_bytes_written += bytes_written;
  985. if (accounting_is_enabled(options) && seconds_elapsed >= 0)
  986. accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
  987. control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
  988. control_event_stream_bandwidth_used();
  989. if (seconds_elapsed > 0)
  990. connection_bucket_refill(seconds_elapsed);
  991. stats_prev_global_read_bucket = global_read_bucket;
  992. stats_prev_global_write_bucket = global_write_bucket;
  993. if (server_mode(options) &&
  994. !we_are_hibernating() &&
  995. seconds_elapsed > 0 &&
  996. stats_n_seconds_working / TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT !=
  997. (stats_n_seconds_working+seconds_elapsed) /
  998. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
  999. /* every 20 minutes, check and complain if necessary */
  1000. routerinfo_t *me = router_get_my_routerinfo();
  1001. if (me && !check_whether_orport_reachable())
  1002. log_warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that "
  1003. "its ORPort is reachable. Please check your firewalls, ports, "
  1004. "address, /etc/hosts file, etc.",
  1005. me->address, me->or_port);
  1006. if (me && !check_whether_dirport_reachable())
  1007. log_warn(LD_CONFIG,
  1008. "Your server (%s:%d) has not managed to confirm that its "
  1009. "DirPort is reachable. Please check your firewalls, ports, "
  1010. "address, /etc/hosts file, etc.",
  1011. me->address, me->dir_port);
  1012. }
  1013. /** If more than this many seconds have elapsed, probably the clock
  1014. * jumped: doesn't count. */
  1015. #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
  1016. if (seconds_elapsed < -NUM_JUMPED_SECONDS_BEFORE_WARN ||
  1017. seconds_elapsed >= NUM_JUMPED_SECONDS_BEFORE_WARN) {
  1018. circuit_note_clock_jumped(seconds_elapsed);
  1019. /* XXX if the time jumps *back* many months, do our events in
  1020. * run_scheduled_events() recover? I don't think they do. -RD */
  1021. } else if (seconds_elapsed > 0)
  1022. stats_n_seconds_working += seconds_elapsed;
  1023. run_scheduled_events(now.tv_sec);
  1024. current_second = now.tv_sec; /* remember which second it is, for next time */
  1025. #if 0
  1026. if (current_second % 300 == 0) {
  1027. rep_history_clean(current_second - options->RephistTrackTime);
  1028. dumpmemusage(get_min_log_level()<LOG_INFO ?
  1029. get_min_log_level() : LOG_INFO);
  1030. }
  1031. #endif
  1032. if (evtimer_add(timeout_event, &one_second))
  1033. log_err(LD_NET,
  1034. "Error from libevent when setting one-second timeout event");
  1035. }
  1036. #ifndef MS_WINDOWS
  1037. /** Called when a possibly ignorable libevent error occurs; ensures that we
  1038. * don't get into an infinite loop by ignoring too many errors from
  1039. * libevent. */
  1040. static int
  1041. got_libevent_error(void)
  1042. {
  1043. if (++n_libevent_errors > 8) {
  1044. log_err(LD_NET, "Too many libevent errors in one second; dying");
  1045. return -1;
  1046. }
  1047. return 0;
  1048. }
  1049. #endif
  1050. #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
  1051. /** Called when our IP address seems to have changed. <b>at_interface</b>
  1052. * should be true if we detected a change in our interface, and false if we
  1053. * detected a change in our published address. */
  1054. void
  1055. ip_address_changed(int at_interface)
  1056. {
  1057. int server = server_mode(get_options());
  1058. if (at_interface) {
  1059. if (! server) {
  1060. /* Okay, change our keys. */
  1061. init_keys();
  1062. }
  1063. } else {
  1064. if (server) {
  1065. if (stats_n_seconds_working > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
  1066. reset_bandwidth_test();
  1067. stats_n_seconds_working = 0;
  1068. router_reset_reachability();
  1069. mark_my_descriptor_dirty();
  1070. }
  1071. }
  1072. dns_servers_relaunch_checks();
  1073. }
  1074. /** Forget what we've learned about the correctness of our DNS servers, and
  1075. * start learning again. */
  1076. void
  1077. dns_servers_relaunch_checks(void)
  1078. {
  1079. if (server_mode(get_options())) {
  1080. dns_reset_correctness_checks();
  1081. time_to_check_for_correct_dns = 0;
  1082. }
  1083. }
  1084. /** Called when we get a SIGHUP: reload configuration files and keys,
  1085. * retry all connections, re-upload all descriptors, and so on. */
  1086. static int
  1087. do_hup(void)
  1088. {
  1089. or_options_t *options = get_options();
  1090. log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config.");
  1091. if (accounting_is_enabled(options))
  1092. accounting_record_bandwidth_usage(time(NULL), get_or_state());
  1093. router_reset_warnings();
  1094. routerlist_reset_warnings();
  1095. addressmap_clear_transient();
  1096. /* first, reload config variables, in case they've changed */
  1097. /* no need to provide argc/v, they've been cached inside init_from_config */
  1098. if (options_init_from_torrc(0, NULL) < 0) {
  1099. log_err(LD_CONFIG,"Reading config failed--see warnings above. "
  1100. "For usage, try -h.");
  1101. return -1;
  1102. }
  1103. options = get_options(); /* they have changed now */
  1104. if (authdir_mode(options)) {
  1105. /* reload the approved-routers file */
  1106. if (dirserv_load_fingerprint_file() < 0) {
  1107. /* warnings are logged from dirserv_load_fingerprint_file() directly */
  1108. log_info(LD_GENERAL, "Error reloading fingerprints. "
  1109. "Continuing with old list.");
  1110. }
  1111. }
  1112. /* Rotate away from the old dirty circuits. This has to be done
  1113. * after we've read the new options, but before we start using
  1114. * circuits for directory fetches. */
  1115. circuit_expire_all_dirty_circs();
  1116. /* retry appropriate downloads */
  1117. router_reset_status_download_failures();
  1118. router_reset_descriptor_download_failures();
  1119. update_networkstatus_downloads(time(NULL));
  1120. /* We'll retry routerstatus downloads in about 10 seconds; no need to
  1121. * force a retry there. */
  1122. if (server_mode(options)) {
  1123. // const char *descriptor;
  1124. mark_my_descriptor_dirty();
  1125. /* Restart cpuworker and dnsworker processes, so they get up-to-date
  1126. * configuration options. */
  1127. cpuworkers_rotate();
  1128. dns_reset();
  1129. #if 0
  1130. const char *descriptor;
  1131. char keydir[512];
  1132. /* Write out a fresh descriptor, but leave old one on failure. */
  1133. router_rebuild_descriptor(1);
  1134. descriptor = router_get_my_descriptor();
  1135. if (descriptor) {
  1136. tor_snprintf(keydir,sizeof(keydir),"%s"PATH_SEPARATOR"router.desc",
  1137. options->DataDirectory);
  1138. log_info(LD_OR,"Saving descriptor to \"%s\"...",keydir);
  1139. if (write_str_to_file(keydir, descriptor, 0)) {
  1140. return 0;
  1141. }
  1142. }
  1143. #endif
  1144. }
  1145. return 0;
  1146. }
  1147. /** Tor main loop. */
  1148. static int
  1149. do_main_loop(void)
  1150. {
  1151. int loop_result;
  1152. /* initialize dns resolve map, spawn workers if needed */
  1153. if (dns_init() < 0) {
  1154. log_err(LD_GENERAL,"Error initializing dns subsystem; exiting");
  1155. return -1;
  1156. }
  1157. handle_signals(1);
  1158. /* load the private keys, if we're supposed to have them, and set up the
  1159. * TLS context. */
  1160. if (! identity_key_is_set()) {
  1161. if (init_keys() < 0) {
  1162. log_err(LD_BUG,"Error initializing keys; exiting");
  1163. return -1;
  1164. }
  1165. }
  1166. /* DOCDOC */
  1167. init_cell_pool();
  1168. /* Set up our buckets */
  1169. connection_bucket_init();
  1170. stats_prev_global_read_bucket = global_read_bucket;
  1171. stats_prev_global_write_bucket = global_write_bucket;
  1172. /* load the routers file, or assign the defaults. */
  1173. if (router_reload_router_list()) {
  1174. return -1;
  1175. }
  1176. /* load the networkstatuses. (This launches a download for new routers as
  1177. * appropriate.)
  1178. */
  1179. if (router_reload_networkstatus()) {
  1180. return -1;
  1181. }
  1182. directory_info_has_arrived(time(NULL),1);
  1183. if (authdir_mode(get_options())) {
  1184. /* the directory is already here, run startup things */
  1185. dirserv_test_reachability(1);
  1186. }
  1187. if (server_mode(get_options())) {
  1188. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  1189. cpu_init();
  1190. }
  1191. /* set up once-a-second callback. */
  1192. second_elapsed_callback(0,0,NULL);
  1193. for (;;) {
  1194. if (nt_service_is_stopping())
  1195. return 0;
  1196. #ifndef MS_WINDOWS
  1197. /* Make it easier to tell whether libevent failure is our fault or not. */
  1198. errno = 0;
  1199. #endif
  1200. /* All active linked conns should get their read events activated. */
  1201. SMARTLIST_FOREACH(active_linked_connection_lst, connection_t *, conn,
  1202. event_active(conn->read_event, EV_READ, 1));
  1203. called_loop_once = smartlist_len(active_linked_connection_lst) ? 1 : 0;
  1204. /* poll until we have an event, or the second ends, or until we have
  1205. * some active linked connections to trigger events for. */
  1206. loop_result = event_loop(called_loop_once ? EVLOOP_ONCE : 0);
  1207. /* let catch() handle things like ^c, and otherwise don't worry about it */
  1208. if (loop_result < 0) {
  1209. int e = tor_socket_errno(-1);
  1210. /* let the program survive things like ^z */
  1211. if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
  1212. #ifdef HAVE_EVENT_GET_METHOD
  1213. log_err(LD_NET,"libevent call with %s failed: %s [%d]",
  1214. event_get_method(), tor_socket_strerror(e), e);
  1215. #else
  1216. log_err(LD_NET,"libevent call failed: %s [%d]",
  1217. tor_socket_strerror(e), e);
  1218. #endif
  1219. return -1;
  1220. #ifndef MS_WINDOWS
  1221. } else if (e == EINVAL) {
  1222. log_warn(LD_NET, "EINVAL from libevent: should you upgrade libevent?");
  1223. if (got_libevent_error())
  1224. return -1;
  1225. #endif
  1226. } else {
  1227. if (ERRNO_IS_EINPROGRESS(e))
  1228. log_warn(LD_BUG,
  1229. "libevent call returned EINPROGRESS? Please report.");
  1230. log_debug(LD_NET,"libevent call interrupted.");
  1231. /* You can't trust the results of this poll(). Go back to the
  1232. * top of the big for loop. */
  1233. continue;
  1234. }
  1235. }
  1236. /* refilling buckets and sending cells happens at the beginning of the
  1237. * next iteration of the loop, inside prepare_for_poll()
  1238. * XXXX No longer so.
  1239. */
  1240. }
  1241. }
  1242. /** Used to implement the SIGNAL control command: if we accept
  1243. * <b>the_signal</b> as a remote pseudo-signal, act on it. */
  1244. /* We don't re-use catch() here because:
  1245. * 1. We handle a different set of signals than those allowed in catch.
  1246. * 2. Platforms without signal() are unlikely to define SIGfoo.
  1247. * 3. The control spec is defined to use fixed numeric signal values
  1248. * which just happen to match the unix values.
  1249. */
  1250. void
  1251. control_signal_act(int the_signal)
  1252. {
  1253. switch (the_signal)
  1254. {
  1255. case 1:
  1256. signal_callback(0,0,(void*)(uintptr_t)SIGHUP);
  1257. break;
  1258. case 2:
  1259. signal_callback(0,0,(void*)(uintptr_t)SIGINT);
  1260. break;
  1261. case 10:
  1262. signal_callback(0,0,(void*)(uintptr_t)SIGUSR1);
  1263. break;
  1264. case 12:
  1265. signal_callback(0,0,(void*)(uintptr_t)SIGUSR2);
  1266. break;
  1267. case 15:
  1268. signal_callback(0,0,(void*)(uintptr_t)SIGTERM);
  1269. break;
  1270. case SIGNEWNYM:
  1271. signal_callback(0,0,(void*)(uintptr_t)SIGNEWNYM);
  1272. break;
  1273. case SIGCLEARDNSCACHE:
  1274. signal_callback(0,0,(void*)(uintptr_t)SIGCLEARDNSCACHE);
  1275. break;
  1276. default:
  1277. log_warn(LD_BUG, "Unrecognized signal number %d.", the_signal);
  1278. break;
  1279. }
  1280. }
  1281. /** Libevent callback: invoked when we get a signal.
  1282. */
  1283. static void
  1284. signal_callback(int fd, short events, void *arg)
  1285. {
  1286. uintptr_t sig = (uintptr_t)arg;
  1287. (void)fd;
  1288. (void)events;
  1289. switch (sig)
  1290. {
  1291. case SIGTERM:
  1292. log_notice(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
  1293. tor_cleanup();
  1294. exit(0);
  1295. break;
  1296. case SIGINT:
  1297. if (!server_mode(get_options())) { /* do it now */
  1298. log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
  1299. tor_cleanup();
  1300. exit(0);
  1301. }
  1302. hibernate_begin_shutdown();
  1303. break;
  1304. #ifdef SIGPIPE
  1305. case SIGPIPE:
  1306. log_debug(LD_GENERAL,"Caught sigpipe. Ignoring.");
  1307. break;
  1308. #endif
  1309. case SIGUSR1:
  1310. /* prefer to log it at INFO, but make sure we always see it */
  1311. dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
  1312. break;
  1313. case SIGUSR2:
  1314. switch_logs_debug();
  1315. log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
  1316. "Send HUP to change back.");
  1317. break;
  1318. case SIGHUP:
  1319. if (do_hup() < 0) {
  1320. log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
  1321. tor_cleanup();
  1322. exit(1);
  1323. }
  1324. break;
  1325. #ifdef SIGCHLD
  1326. case SIGCHLD:
  1327. while (waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more
  1328. zombies */
  1329. break;
  1330. #endif
  1331. case SIGNEWNYM: {
  1332. time_t now = time(NULL);
  1333. if (time_of_last_signewnym + MAX_SIGNEWNYM_RATE > now) {
  1334. signewnym_is_pending = 1;
  1335. log(LOG_NOTICE, LD_CONTROL,
  1336. "Rate limiting NEWNYM request: delaying by %d second(s)",
  1337. (int)(MAX_SIGNEWNYM_RATE+time_of_last_signewnym-now));
  1338. } else {
  1339. /* XXX refactor someday: these two calls are in
  1340. * run_scheduled_events() above too, and they should be in just
  1341. * one place. */
  1342. circuit_expire_all_dirty_circs();
  1343. addressmap_clear_transient();
  1344. time_of_last_signewnym = now;
  1345. }
  1346. break;
  1347. }
  1348. case SIGCLEARDNSCACHE:
  1349. addressmap_clear_transient();
  1350. break;
  1351. }
  1352. }
  1353. extern uint64_t rephist_total_alloc;
  1354. extern uint32_t rephist_total_num;
  1355. /**
  1356. * Write current memory usage information to the log.
  1357. */
  1358. static void
  1359. dumpmemusage(int severity)
  1360. {
  1361. connection_dump_buffer_mem_stats(severity);
  1362. log(severity, LD_GENERAL, "In rephist: "U64_FORMAT" used by %d Tors.",
  1363. U64_PRINTF_ARG(rephist_total_alloc), rephist_total_num);
  1364. dump_routerlist_mem_usage(severity);
  1365. dump_cell_pool_usage(severity);
  1366. }
  1367. /** Write all statistics to the log, with log level 'severity'. Called
  1368. * in response to a SIGUSR1. */
  1369. static void
  1370. dumpstats(int severity)
  1371. {
  1372. int i;
  1373. connection_t *conn;
  1374. time_t now = time(NULL);
  1375. time_t elapsed;
  1376. log(severity, LD_GENERAL, "Dumping stats:");
  1377. for (i=0;i<n_conns;i++) {
  1378. conn = connection_array[i];
  1379. log(severity, LD_GENERAL,
  1380. "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  1381. i, conn->s, conn->type, conn_type_to_string(conn->type),
  1382. conn->state, conn_state_to_string(conn->type, conn->state),
  1383. (int)(now - conn->timestamp_created));
  1384. if (!connection_is_listener(conn)) {
  1385. log(severity,LD_GENERAL,
  1386. "Conn %d is to %s:%d.", i,
  1387. safe_str(conn->address), conn->port);
  1388. log(severity,LD_GENERAL,
  1389. "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
  1390. i,
  1391. (int)buf_datalen(conn->inbuf),
  1392. (int)buf_capacity(conn->inbuf),
  1393. (int)(now - conn->timestamp_lastread));
  1394. log(severity,LD_GENERAL,
  1395. "Conn %d: %d bytes waiting on outbuf "
  1396. "(len %d, last written %d secs ago)",i,
  1397. (int)buf_datalen(conn->outbuf),
  1398. (int)buf_capacity(conn->outbuf),
  1399. (int)(now - conn->timestamp_lastwritten));
  1400. }
  1401. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits
  1402. * using this conn */
  1403. }
  1404. log(severity, LD_NET,
  1405. "Cells processed: "U64_FORMAT" padding\n"
  1406. " "U64_FORMAT" create\n"
  1407. " "U64_FORMAT" created\n"
  1408. " "U64_FORMAT" relay\n"
  1409. " ("U64_FORMAT" relayed)\n"
  1410. " ("U64_FORMAT" delivered)\n"
  1411. " "U64_FORMAT" destroy",
  1412. U64_PRINTF_ARG(stats_n_padding_cells_processed),
  1413. U64_PRINTF_ARG(stats_n_create_cells_processed),
  1414. U64_PRINTF_ARG(stats_n_created_cells_processed),
  1415. U64_PRINTF_ARG(stats_n_relay_cells_processed),
  1416. U64_PRINTF_ARG(stats_n_relay_cells_relayed),
  1417. U64_PRINTF_ARG(stats_n_relay_cells_delivered),
  1418. U64_PRINTF_ARG(stats_n_destroy_cells_processed));
  1419. if (stats_n_data_cells_packaged)
  1420. log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
  1421. 100*(U64_TO_DBL(stats_n_data_bytes_packaged) /
  1422. U64_TO_DBL(stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  1423. if (stats_n_data_cells_received)
  1424. log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
  1425. 100*(U64_TO_DBL(stats_n_data_bytes_received) /
  1426. U64_TO_DBL(stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  1427. if (now - time_of_process_start >= 0)
  1428. elapsed = now - time_of_process_start;
  1429. else
  1430. elapsed = 0;
  1431. if (elapsed) {
  1432. log(severity, LD_NET,
  1433. "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
  1434. U64_PRINTF_ARG(stats_n_bytes_read),
  1435. (int)elapsed,
  1436. (int) (stats_n_bytes_read/elapsed));
  1437. log(severity, LD_NET,
  1438. "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
  1439. U64_PRINTF_ARG(stats_n_bytes_written),
  1440. (int)elapsed,
  1441. (int) (stats_n_bytes_written/elapsed));
  1442. }
  1443. log(severity, LD_NET, "--------------- Dumping memory information:");
  1444. dumpmemusage(severity);
  1445. rep_hist_dump_stats(now,severity);
  1446. rend_service_dump_stats(severity);
  1447. dump_pk_ops(severity);
  1448. dump_distinct_digest_count(severity);
  1449. }
  1450. /** Called by exit() as we shut down the process.
  1451. */
  1452. static void
  1453. exit_function(void)
  1454. {
  1455. /* NOTE: If we ever daemonize, this gets called immediately. That's
  1456. * okay for now, because we only use this on Windows. */
  1457. #ifdef MS_WINDOWS
  1458. WSACleanup();
  1459. #endif
  1460. }
  1461. /** Set up the signal handlers for either parent or child. */
  1462. void
  1463. handle_signals(int is_parent)
  1464. {
  1465. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  1466. int i;
  1467. static int signals[] = {
  1468. SIGINT, /* do a controlled slow shutdown */
  1469. SIGTERM, /* to terminate now */
  1470. SIGPIPE, /* otherwise sigpipe kills us */
  1471. SIGUSR1, /* dump stats */
  1472. SIGUSR2, /* go to loglevel debug */
  1473. SIGHUP, /* to reload config, retry conns, etc */
  1474. #ifdef SIGXFSZ
  1475. SIGXFSZ, /* handle file-too-big resource exhaustion */
  1476. #endif
  1477. SIGCHLD, /* handle dns/cpu workers that exit */
  1478. -1 };
  1479. static struct event signal_events[16]; /* bigger than it has to be. */
  1480. if (is_parent) {
  1481. for (i = 0; signals[i] >= 0; ++i) {
  1482. signal_set(&signal_events[i], signals[i], signal_callback,
  1483. (void*)(uintptr_t)signals[i]);
  1484. if (signal_add(&signal_events[i], NULL))
  1485. log_warn(LD_BUG, "Error from libevent when adding event for signal %d",
  1486. signals[i]);
  1487. }
  1488. } else {
  1489. struct sigaction action;
  1490. action.sa_flags = 0;
  1491. sigemptyset(&action.sa_mask);
  1492. action.sa_handler = SIG_IGN;
  1493. sigaction(SIGINT, &action, NULL);
  1494. sigaction(SIGTERM, &action, NULL);
  1495. sigaction(SIGPIPE, &action, NULL);
  1496. sigaction(SIGUSR1, &action, NULL);
  1497. sigaction(SIGUSR2, &action, NULL);
  1498. sigaction(SIGHUP, &action, NULL);
  1499. #ifdef SIGXFSZ
  1500. sigaction(SIGXFSZ, &action, NULL);
  1501. #endif
  1502. }
  1503. #else /* MS windows */
  1504. (void)is_parent;
  1505. #endif /* signal stuff */
  1506. }
  1507. /** Main entry point for the Tor command-line client.
  1508. */
  1509. static int
  1510. tor_init(int argc, char *argv[])
  1511. {
  1512. time_of_process_start = time(NULL);
  1513. if (!closeable_connection_lst)
  1514. closeable_connection_lst = smartlist_create();
  1515. if (!active_linked_connection_lst)
  1516. active_linked_connection_lst = smartlist_create();
  1517. /* Initialize the history structures. */
  1518. rep_hist_init();
  1519. /* Initialize the service cache. */
  1520. rend_cache_init();
  1521. addressmap_init(); /* Init the client dns cache. Do it always, since it's
  1522. * cheap. */
  1523. /* give it somewhere to log to initially */
  1524. add_temp_log();
  1525. log(LOG_NOTICE, LD_GENERAL, "Tor v%s. This is experimental software. "
  1526. "Do not rely on it for strong anonymity. (Running on %s)",VERSION,
  1527. get_uname());
  1528. if (network_init()<0) {
  1529. log_err(LD_BUG,"Error initializing network; exiting.");
  1530. return -1;
  1531. }
  1532. atexit(exit_function);
  1533. if (options_init_from_torrc(argc,argv) < 0) {
  1534. log_err(LD_CONFIG,"Reading config failed--see warnings above.");
  1535. return -1;
  1536. }
  1537. #ifndef MS_WINDOWS
  1538. if (geteuid()==0)
  1539. log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
  1540. "and you probably shouldn't.");
  1541. #endif
  1542. crypto_global_init(get_options()->HardwareAccel);
  1543. if (crypto_seed_rng()) {
  1544. log_err(LD_BUG, "Unable to seed random number generator. Exiting.");
  1545. return -1;
  1546. }
  1547. return 0;
  1548. }
  1549. /** Free all memory that we might have allocated somewhere.
  1550. * Helps us find the real leaks with dmalloc and the like.
  1551. *
  1552. * Also valgrind should then report 0 reachable in its
  1553. * leak report */
  1554. void
  1555. tor_free_all(int postfork)
  1556. {
  1557. if (!postfork) {
  1558. evdns_shutdown(1);
  1559. }
  1560. routerlist_free_all();
  1561. addressmap_free_all();
  1562. set_exit_redirects(NULL); /* free the registered exit redirects */
  1563. dirserv_free_all();
  1564. rend_service_free_all();
  1565. rend_cache_free_all();
  1566. rep_hist_free_all();
  1567. hs_usage_free_all();
  1568. dns_free_all();
  1569. clear_pending_onions();
  1570. circuit_free_all();
  1571. entry_guards_free_all();
  1572. connection_free_all();
  1573. policies_free_all();
  1574. if (!postfork) {
  1575. config_free_all();
  1576. router_free_all();
  1577. }
  1578. free_cell_pool();
  1579. tor_tls_free_all();
  1580. /* stuff in main.c */
  1581. smartlist_free(closeable_connection_lst);
  1582. smartlist_free(active_linked_connection_lst);
  1583. tor_free(timeout_event);
  1584. /* Stuff in util.c */
  1585. escaped(NULL);
  1586. if (!postfork) {
  1587. close_logs(); /* free log strings. do this last so logs keep working. */
  1588. }
  1589. }
  1590. /** Do whatever cleanup is necessary before shutting Tor down. */
  1591. void
  1592. tor_cleanup(void)
  1593. {
  1594. or_options_t *options = get_options();
  1595. /* Remove our pid file. We don't care if there was an error when we
  1596. * unlink, nothing we could do about it anyways. */
  1597. if (options->command == CMD_RUN_TOR) {
  1598. if (options->PidFile)
  1599. unlink(options->PidFile);
  1600. if (accounting_is_enabled(options))
  1601. accounting_record_bandwidth_usage(time(NULL), get_or_state());
  1602. or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
  1603. or_state_save(time(NULL));
  1604. }
  1605. tor_free_all(0); /* move tor_free_all back into the ifdef below later. XXX*/
  1606. crypto_global_cleanup();
  1607. #ifdef USE_DMALLOC
  1608. dmalloc_log_unfreed();
  1609. dmalloc_shutdown();
  1610. #endif
  1611. }
  1612. /** Read/create keys as needed, and echo our fingerprint to stdout. */
  1613. static int
  1614. do_list_fingerprint(void)
  1615. {
  1616. char buf[FINGERPRINT_LEN+1];
  1617. crypto_pk_env_t *k;
  1618. const char *nickname = get_options()->Nickname;
  1619. if (!server_mode(get_options())) {
  1620. log_err(LD_GENERAL,
  1621. "Clients don't have long-term identity keys. Exiting.\n");
  1622. return -1;
  1623. }
  1624. tor_assert(nickname);
  1625. if (init_keys() < 0) {
  1626. log_err(LD_BUG,"Error initializing keys; can't display fingerprint");
  1627. return -1;
  1628. }
  1629. if (!(k = get_identity_key())) {
  1630. log_err(LD_GENERAL,"Error: missing identity key.");
  1631. return -1;
  1632. }
  1633. if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
  1634. log_err(LD_BUG, "Error computing fingerprint");
  1635. return -1;
  1636. }
  1637. printf("%s %s\n", nickname, buf);
  1638. return 0;
  1639. }
  1640. /** Entry point for password hashing: take the desired password from
  1641. * the command line, and print its salted hash to stdout. **/
  1642. static void
  1643. do_hash_password(void)
  1644. {
  1645. char output[256];
  1646. char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
  1647. crypto_rand(key, S2K_SPECIFIER_LEN-1);
  1648. key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
  1649. secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
  1650. get_options()->command_arg, strlen(get_options()->command_arg),
  1651. key);
  1652. base16_encode(output, sizeof(output), key, sizeof(key));
  1653. printf("16:%s\n",output);
  1654. }
  1655. #ifdef MS_WINDOWS_SERVICE
  1656. /* XXXX can some/all these functions become static? without breaking NT
  1657. * services? -NM */
  1658. /* XXXX I'd also like to move much of the NT service stuff into its own
  1659. * file. -RD */
  1660. void nt_service_control(DWORD request);
  1661. void nt_service_body(int argc, char **argv);
  1662. void nt_service_main(void);
  1663. SC_HANDLE nt_service_open_scm(void);
  1664. SC_HANDLE nt_service_open(SC_HANDLE hSCManager);
  1665. int nt_service_start(SC_HANDLE hService);
  1666. int nt_service_stop(SC_HANDLE hService);
  1667. int nt_service_install(int argc, char **argv);
  1668. int nt_service_remove(void);
  1669. int nt_service_cmd_start(void);
  1670. int nt_service_cmd_stop(void);
  1671. struct service_fns {
  1672. int loaded;
  1673. BOOL (WINAPI *ChangeServiceConfig2A_fn)(
  1674. SC_HANDLE hService,
  1675. DWORD dwInfoLevel,
  1676. LPVOID lpInfo);
  1677. BOOL (WINAPI *CloseServiceHandle_fn)(
  1678. SC_HANDLE hSCObject);
  1679. BOOL (WINAPI *ControlService_fn)(
  1680. SC_HANDLE hService,
  1681. DWORD dwControl,
  1682. LPSERVICE_STATUS lpServiceStatus);
  1683. SC_HANDLE (WINAPI *CreateServiceA_fn)(
  1684. SC_HANDLE hSCManager,
  1685. LPCTSTR lpServiceName,
  1686. LPCTSTR lpDisplayName,
  1687. DWORD dwDesiredAccess,
  1688. DWORD dwServiceType,
  1689. DWORD dwStartType,
  1690. DWORD dwErrorControl,
  1691. LPCTSTR lpBinaryPathName,
  1692. LPCTSTR lpLoadOrderGroup,
  1693. LPDWORD lpdwTagId,
  1694. LPCTSTR lpDependencies,
  1695. LPCTSTR lpServiceStartName,
  1696. LPCTSTR lpPassword);
  1697. BOOL (WINAPI *DeleteService_fn)(
  1698. SC_HANDLE hService);
  1699. SC_HANDLE (WINAPI *OpenSCManagerA_fn)(
  1700. LPCTSTR lpMachineName,
  1701. LPCTSTR lpDatabaseName,
  1702. DWORD dwDesiredAccess);
  1703. SC_HANDLE (WINAPI *OpenServiceA_fn)(
  1704. SC_HANDLE hSCManager,
  1705. LPCTSTR lpServiceName,
  1706. DWORD dwDesiredAccess);
  1707. BOOL (WINAPI *QueryServiceStatus_fn)(
  1708. SC_HANDLE hService,
  1709. LPSERVICE_STATUS lpServiceStatus);
  1710. SERVICE_STATUS_HANDLE (WINAPI *RegisterServiceCtrlHandlerA_fn)(
  1711. LPCTSTR lpServiceName,
  1712. LPHANDLER_FUNCTION lpHandlerProc);
  1713. BOOL (WINAPI *SetServiceStatus_fn)(SERVICE_STATUS_HANDLE,
  1714. LPSERVICE_STATUS);
  1715. BOOL (WINAPI *StartServiceCtrlDispatcherA_fn)(
  1716. const SERVICE_TABLE_ENTRY* lpServiceTable);
  1717. BOOL (WINAPI *StartServiceA_fn)(
  1718. SC_HANDLE hService,
  1719. DWORD dwNumServiceArgs,
  1720. LPCTSTR* lpServiceArgVectors);
  1721. BOOL (WINAPI *LookupAccountNameA_fn)(
  1722. LPCTSTR lpSystemName,
  1723. LPCTSTR lpAccountName,
  1724. PSID Sid,
  1725. LPDWORD cbSid,
  1726. LPTSTR ReferencedDomainName,
  1727. LPDWORD cchReferencedDomainName,
  1728. PSID_NAME_USE peUse);
  1729. } service_fns = { 0,
  1730. NULL, NULL, NULL, NULL, NULL, NULL,
  1731. NULL, NULL, NULL, NULL, NULL, NULL,
  1732. NULL};
  1733. /** Loads functions used by NT services. Returns on success, or prints a
  1734. * complaint to stdout and exits on error. */
  1735. static void
  1736. nt_service_loadlibrary(void)
  1737. {
  1738. HMODULE library = 0;
  1739. void *fn;
  1740. if (service_fns.loaded)
  1741. return;
  1742. /* XXXX Possibly, we should hardcode the location of this DLL. */
  1743. if (!(library = LoadLibrary("advapi32.dll"))) {
  1744. log_err(LD_GENERAL, "Couldn't open advapi32.dll. Are you trying to use "
  1745. "NT services on Windows 98? That doesn't work.");
  1746. goto err;
  1747. }
  1748. #define LOAD(f) do { \
  1749. if (!(fn = GetProcAddress(library, #f))) { \
  1750. log_err(LD_BUG, \
  1751. "Couldn't find %s in advapi32.dll! We probably got the " \
  1752. "name wrong.", #f); \
  1753. goto err; \
  1754. } else { \
  1755. service_fns.f ## _fn = fn; \
  1756. } \
  1757. } while (0)
  1758. LOAD(ChangeServiceConfig2A);
  1759. LOAD(CloseServiceHandle);
  1760. LOAD(ControlService);
  1761. LOAD(CreateServiceA);
  1762. LOAD(DeleteService);
  1763. LOAD(OpenSCManagerA);
  1764. LOAD(OpenServiceA);
  1765. LOAD(QueryServiceStatus);
  1766. LOAD(RegisterServiceCtrlHandlerA);
  1767. LOAD(SetServiceStatus);
  1768. LOAD(StartServiceCtrlDispatcherA);
  1769. LOAD(StartServiceA);
  1770. LOAD(LookupAccountNameA);
  1771. service_fns.loaded = 1;
  1772. return;
  1773. err:
  1774. printf("Unable to load library support for NT services: exiting.\n");
  1775. exit(1);
  1776. }
  1777. /** If we're compiled to run as an NT service, and the service wants to
  1778. * shut down, then change our current status and return 1. Else
  1779. * return 0.
  1780. */
  1781. static int
  1782. nt_service_is_stopping(void)
  1783. /* XXXX this function would probably _love_ to be inline, in 0.2.0. */
  1784. {
  1785. /* If we haven't loaded the function pointers, we can't possibly be an NT
  1786. * service trying to shut down. */
  1787. if (!service_fns.loaded)
  1788. return 0;
  1789. if (service_status.dwCurrentState == SERVICE_STOP_PENDING) {
  1790. service_status.dwWin32ExitCode = 0;
  1791. service_status.dwCurrentState = SERVICE_STOPPED;
  1792. service_fns.SetServiceStatus_fn(hStatus, &service_status);
  1793. return 1;
  1794. } else if (service_status.dwCurrentState == SERVICE_STOPPED) {
  1795. return 1;
  1796. }
  1797. return 0;
  1798. }
  1799. /** Handles service control requests, such as stopping or starting the
  1800. * Tor service. */
  1801. void
  1802. nt_service_control(DWORD request)
  1803. {
  1804. static struct timeval exit_now;
  1805. exit_now.tv_sec = 0;
  1806. exit_now.tv_usec = 0;
  1807. nt_service_loadlibrary();
  1808. switch (request) {
  1809. case SERVICE_CONTROL_STOP:
  1810. case SERVICE_CONTROL_SHUTDOWN:
  1811. log_notice(LD_GENERAL,
  1812. "Got stop/shutdown request; shutting down cleanly.");
  1813. service_status.dwCurrentState = SERVICE_STOP_PENDING;
  1814. event_loopexit(&exit_now);
  1815. return;
  1816. }
  1817. service_fns.SetServiceStatus_fn(hStatus, &service_status);
  1818. }
  1819. /** Called when the service is started via the system's service control
  1820. * manager. This calls tor_init() and starts the main event loop. If
  1821. * tor_init() fails, the service will be stopped and exit code set to
  1822. * NT_SERVICE_ERROR_TORINIT_FAILED. */
  1823. void
  1824. nt_service_body(int argc, char **argv)
  1825. {
  1826. int r;
  1827. (void) argc; /* unused */
  1828. (void) argv; /* unused */
  1829. nt_service_loadlibrary();
  1830. service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  1831. service_status.dwCurrentState = SERVICE_START_PENDING;
  1832. service_status.dwControlsAccepted =
  1833. SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
  1834. service_status.dwWin32ExitCode = 0;
  1835. service_status.dwServiceSpecificExitCode = 0;
  1836. service_status.dwCheckPoint = 0;
  1837. service_status.dwWaitHint = 1000;
  1838. hStatus = service_fns.RegisterServiceCtrlHandlerA_fn(GENSRV_SERVICENAME,
  1839. (LPHANDLER_FUNCTION) nt_service_control);
  1840. if (hStatus == 0) {
  1841. /* Failed to register the service control handler function */
  1842. return;
  1843. }
  1844. r = tor_init(backup_argc, backup_argv);
  1845. if (r) {
  1846. /* Failed to start the Tor service */
  1847. r = NT_SERVICE_ERROR_TORINIT_FAILED;
  1848. service_status.dwCurrentState = SERVICE_STOPPED;
  1849. service_status.dwWin32ExitCode = r;
  1850. service_status.dwServiceSpecificExitCode = r;
  1851. service_fns.SetServiceStatus_fn(hStatus, &service_status);
  1852. return;
  1853. }
  1854. /* Set the service's status to SERVICE_RUNNING and start the main
  1855. * event loop */
  1856. service_status.dwCurrentState = SERVICE_RUNNING;
  1857. service_fns.SetServiceStatus_fn(hStatus, &service_status);
  1858. do_main_loop();
  1859. tor_cleanup();
  1860. }
  1861. /** Main service entry point. Starts the service control dispatcher and waits
  1862. * until the service status is set to SERVICE_STOPPED. */
  1863. void
  1864. nt_service_main(void)
  1865. {
  1866. SERVICE_TABLE_ENTRY table[2];
  1867. DWORD result = 0;
  1868. char *errmsg;
  1869. nt_service_loadlibrary();
  1870. table[0].lpServiceName = (char*)GENSRV_SERVICENAME;
  1871. table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)nt_service_body;
  1872. table[1].lpServiceName = NULL;
  1873. table[1].lpServiceProc = NULL;
  1874. if (!service_fns.StartServiceCtrlDispatcherA_fn(table)) {
  1875. result = GetLastError();
  1876. errmsg = nt_strerror(result);
  1877. printf("Service error %d : %s\n", (int) result, errmsg);
  1878. LocalFree(errmsg);
  1879. if (result == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
  1880. if (tor_init(backup_argc, backup_argv) < 0)
  1881. return;
  1882. switch (get_options()->command) {
  1883. case CMD_RUN_TOR:
  1884. do_main_loop();
  1885. break;
  1886. case CMD_LIST_FINGERPRINT:
  1887. do_list_fingerprint();
  1888. break;
  1889. case CMD_HASH_PASSWORD:
  1890. do_hash_password();
  1891. break;
  1892. case CMD_VERIFY_CONFIG:
  1893. printf("Configuration was valid\n");
  1894. break;
  1895. case CMD_RUN_UNITTESTS:
  1896. default:
  1897. log_err(LD_CONFIG, "Illegal command number %d: internal error.",
  1898. get_options()->command);
  1899. }
  1900. tor_cleanup();
  1901. }
  1902. }
  1903. }
  1904. /** Return a handle to the service control manager on success, or NULL on
  1905. * failure. */
  1906. SC_HANDLE
  1907. nt_service_open_scm(void)
  1908. {
  1909. SC_HANDLE hSCManager;
  1910. char *errmsg = NULL;
  1911. nt_service_loadlibrary();
  1912. if ((hSCManager = service_fns.OpenSCManagerA_fn(
  1913. NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
  1914. errmsg = nt_strerror(GetLastError());
  1915. printf("OpenSCManager() failed : %s\n", errmsg);
  1916. LocalFree(errmsg);
  1917. }
  1918. return hSCManager;
  1919. }
  1920. /** Open a handle to the Tor service using <b>hSCManager</b>. Return NULL
  1921. * on failure. */
  1922. SC_HANDLE
  1923. nt_service_open(SC_HANDLE hSCManager)
  1924. {
  1925. SC_HANDLE hService;
  1926. char *errmsg = NULL;
  1927. nt_service_loadlibrary();
  1928. if ((hService = service_fns.OpenServiceA_fn(hSCManager, GENSRV_SERVICENAME,
  1929. SERVICE_ALL_ACCESS)) == NULL) {
  1930. errmsg = nt_strerror(GetLastError());
  1931. printf("OpenService() failed : %s\n", errmsg);
  1932. LocalFree(errmsg);
  1933. }
  1934. return hService;
  1935. }
  1936. /** Start the Tor service. Return 0 if the service is started or was
  1937. * previously running. Return -1 on error. */
  1938. int
  1939. nt_service_start(SC_HANDLE hService)
  1940. {
  1941. char *errmsg = NULL;
  1942. nt_service_loadlibrary();
  1943. service_fns.QueryServiceStatus_fn(hService, &service_status);
  1944. if (service_status.dwCurrentState == SERVICE_RUNNING) {
  1945. printf("Service is already running\n");
  1946. return 0;
  1947. }
  1948. if (service_fns.StartServiceA_fn(hService, 0, NULL)) {
  1949. /* Loop until the service has finished attempting to start */
  1950. while (service_fns.QueryServiceStatus_fn(hService, &service_status) &&
  1951. (service_status.dwCurrentState == SERVICE_START_PENDING)) {
  1952. Sleep(500);
  1953. }
  1954. /* Check if it started successfully or not */
  1955. if (service_status.dwCurrentState == SERVICE_RUNNING) {
  1956. printf("Service started successfully\n");
  1957. return 0;
  1958. } else {
  1959. errmsg = nt_strerror(service_status.dwWin32ExitCode);
  1960. printf("Service failed to start : %s\n", errmsg);
  1961. LocalFree(errmsg);
  1962. }
  1963. } else {
  1964. errmsg = nt_strerror(GetLastError());
  1965. printf("StartService() failed : %s\n", errmsg);
  1966. LocalFree(errmsg);
  1967. }
  1968. return -1;
  1969. }
  1970. /** Stop the Tor service. Return 0 if the service is stopped or was not
  1971. * previously running. Return -1 on error. */
  1972. int
  1973. nt_service_stop(SC_HANDLE hService)
  1974. {
  1975. /** Wait at most 10 seconds for the service to stop. */
  1976. #define MAX_SERVICE_WAIT_TIME 10
  1977. int wait_time;
  1978. char *errmsg = NULL;
  1979. nt_service_loadlibrary();
  1980. service_fns.QueryServiceStatus_fn(hService, &service_status);
  1981. if (service_status.dwCurrentState == SERVICE_STOPPED) {
  1982. printf("Service is already stopped\n");
  1983. return 0;
  1984. }
  1985. if (service_fns.ControlService_fn(hService, SERVICE_CONTROL_STOP,
  1986. &service_status)) {
  1987. wait_time = 0;
  1988. while (service_fns.QueryServiceStatus_fn(hService, &service_status) &&
  1989. (service_status.dwCurrentState != SERVICE_STOPPED) &&
  1990. (wait_time < MAX_SERVICE_WAIT_TIME)) {
  1991. Sleep(1000);
  1992. wait_time++;
  1993. }
  1994. if (service_status.dwCurrentState == SERVICE_STOPPED) {
  1995. printf("Service stopped successfully\n");
  1996. return 0;
  1997. } else if (wait_time == MAX_SERVICE_WAIT_TIME) {
  1998. printf("Service did not stop within %d seconds.\n", wait_time);
  1999. } else {
  2000. errmsg = nt_strerror(GetLastError());
  2001. printf("QueryServiceStatus() failed : %s\n",errmsg);
  2002. LocalFree(errmsg);
  2003. }
  2004. } else {
  2005. errmsg = nt_strerror(GetLastError());
  2006. printf("ControlService() failed : %s\n", errmsg);
  2007. LocalFree(errmsg);
  2008. }
  2009. return -1;
  2010. }
  2011. /** Build a formatted command line used for the NT service. Return a
  2012. * pointer to the formatted string on success, or NULL on failure. Set
  2013. * *<b>using_default_torrc</b> to true if we're going to use the default
  2014. * location to torrc, or 1 if an option was specified on the command line.
  2015. */
  2016. static char *
  2017. nt_service_command_line(int *using_default_torrc)
  2018. {
  2019. TCHAR tor_exe[MAX_PATH+1];
  2020. char *command, *options=NULL;
  2021. smartlist_t *sl;
  2022. int i, cmdlen;
  2023. *using_default_torrc = 1;
  2024. /* Get the location of tor.exe */
  2025. if (0 == GetModuleFileName(NULL, tor_exe, MAX_PATH))
  2026. return NULL;
  2027. /* Get the service arguments */
  2028. sl = smartlist_create();
  2029. for (i = 1; i < backup_argc; ++i) {
  2030. if (!strcmp(backup_argv[i], "--options") ||
  2031. !strcmp(backup_argv[i], "-options")) {
  2032. while (++i < backup_argc) {
  2033. if (!strcmp(backup_argv[i], "-f"))
  2034. *using_default_torrc = 0;
  2035. smartlist_add(sl, backup_argv[i]);
  2036. }
  2037. }
  2038. }
  2039. if (smartlist_len(sl))
  2040. options = smartlist_join_strings(sl,"\" \"",0,NULL);
  2041. smartlist_free(sl);
  2042. /* Allocate a string for the NT service command line */
  2043. cmdlen = strlen(tor_exe) + (options?strlen(options):0) + 32;
  2044. command = tor_malloc(cmdlen);
  2045. /* Format the service command */
  2046. if (options) {
  2047. if (tor_snprintf(command, cmdlen, "\"%s\" --nt-service \"%s\"",
  2048. tor_exe, options)<0) {
  2049. tor_free(command); /* sets command to NULL. */
  2050. }
  2051. } else { /* ! options */
  2052. if (tor_snprintf(command, cmdlen, "\"%s\" --nt-service", tor_exe)<0) {
  2053. tor_free(command); /* sets command to NULL. */
  2054. }
  2055. }
  2056. tor_free(options);
  2057. return command;
  2058. }
  2059. /** Creates a Tor NT service, set to start on boot. The service will be
  2060. * started if installation succeeds. Returns 0 on success, or -1 on
  2061. * failure. */
  2062. int
  2063. nt_service_install(int argc, char **argv)
  2064. {
  2065. /* Notes about developing NT services:
  2066. *
  2067. * 1. Don't count on your CWD. If an absolute path is not given, the
  2068. * fopen() function goes wrong.
  2069. * 2. The parameters given to the nt_service_body() function differ
  2070. * from those given to main() function.
  2071. */
  2072. SC_HANDLE hSCManager = NULL;
  2073. SC_HANDLE hService = NULL;
  2074. SERVICE_DESCRIPTION sdBuff;
  2075. char *command;
  2076. char *errmsg;
  2077. const char *user_acct = GENSRV_USERACCT;
  2078. const char *password = "";
  2079. int i;
  2080. OSVERSIONINFOEX info;
  2081. SID_NAME_USE sidUse;
  2082. DWORD sidLen = 0, domainLen = 0;
  2083. int is_win2k_or_worse = 0;
  2084. int using_default_torrc = 0;
  2085. nt_service_loadlibrary();
  2086. /* Open the service control manager so we can create a new service */
  2087. if ((hSCManager = nt_service_open_scm()) == NULL)
  2088. return -1;
  2089. /* Build the command line used for the service */
  2090. if ((command = nt_service_command_line(&using_default_torrc)) == NULL) {
  2091. printf("Unable to build service command line.\n");
  2092. service_fns.CloseServiceHandle_fn(hSCManager);
  2093. return -1;
  2094. }
  2095. for (i=1; i < argc; ++i) {
  2096. if (!strcmp(argv[i], "--user") && i+1<argc) {
  2097. user_acct = argv[i+1];
  2098. ++i;
  2099. }
  2100. if (!strcmp(argv[i], "--password") && i+1<argc) {
  2101. password = argv[i+1];
  2102. ++i;
  2103. }
  2104. }
  2105. /* Compute our version and see whether we're running win2k or earlier. */
  2106. memset(&info, 0, sizeof(info));
  2107. info.dwOSVersionInfoSize = sizeof(info);
  2108. if (! GetVersionEx((LPOSVERSIONINFO)&info)) {
  2109. printf("Call to GetVersionEx failed.\n");
  2110. is_win2k_or_worse = 1;
  2111. } else {
  2112. if (info.dwMajorVersion < 5 ||
  2113. (info.dwMajorVersion == 5 && info.dwMinorVersion == 0))
  2114. is_win2k_or_worse = 1;
  2115. }
  2116. if (user_acct == GENSRV_USERACCT) {
  2117. if (is_win2k_or_worse) {
  2118. /* On Win2k, there is no LocalService account, so we actually need to
  2119. * fall back on NULL (the system account). */
  2120. printf("Running on Win2K or earlier, so the LocalService account "
  2121. "doesn't exist. Falling back to SYSTEM account.\n");
  2122. user_acct = NULL;
  2123. } else {
  2124. /* Genericity is apparently _so_ last year in Redmond, where some
  2125. * accounts are accounts that you can look up, and some accounts
  2126. * are magic and undetectable via the security subsystem. See
  2127. * http://msdn2.microsoft.com/en-us/library/ms684188.aspx
  2128. */
  2129. printf("Running on a Post-Win2K OS, so we'll assume that the "
  2130. "LocalService account exists.\n");
  2131. }
  2132. } else if (0 && service_fns.LookupAccountNameA_fn(NULL, // On this system
  2133. user_acct,
  2134. NULL, &sidLen, // Don't care about the SID
  2135. NULL, &domainLen, // Don't care about the domain
  2136. &sidUse) == 0) {
  2137. /* XXXX For some reason, the above test segfaults. Fix that. */
  2138. printf("User \"%s\" doesn't seem to exist.\n", user_acct);
  2139. return -1;
  2140. } else {
  2141. printf("Will try to install service as user \"%s\".\n", user_acct);
  2142. }
  2143. /* XXXX This warning could be better about explaining how to resolve the
  2144. * situation. */
  2145. if (using_default_torrc)
  2146. printf("IMPORTANT NOTE:\n"
  2147. " The Tor service will run under the account \"%s\". This means\n"
  2148. " that Tor will look for its configuration file under that\n"
  2149. " account's Application Data directory, which is probably not\n"
  2150. " the same as yours.\n", user_acct?user_acct:"<local system>");
  2151. /* Create the Tor service, set to auto-start on boot */
  2152. if ((hService = service_fns.CreateServiceA_fn(hSCManager, GENSRV_SERVICENAME,
  2153. GENSRV_DISPLAYNAME,
  2154. SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
  2155. SERVICE_AUTO_START, SERVICE_ERROR_IGNORE,
  2156. command, NULL, NULL, NULL,
  2157. user_acct, password)) == NULL) {
  2158. errmsg = nt_strerror(GetLastError());
  2159. printf("CreateService() failed : %s\n", errmsg);
  2160. service_fns.CloseServiceHandle_fn(hSCManager);
  2161. LocalFree(errmsg);
  2162. tor_free(command);
  2163. return -1;
  2164. }
  2165. printf("Done with CreateService.\n");
  2166. /* Set the service's description */
  2167. sdBuff.lpDescription = (char*)GENSRV_DESCRIPTION;
  2168. service_fns.ChangeServiceConfig2A_fn(hService, SERVICE_CONFIG_DESCRIPTION,
  2169. &sdBuff);
  2170. printf("Service installed successfully\n");
  2171. /* Start the service initially */
  2172. nt_service_start(hService);
  2173. service_fns.CloseServiceHandle_fn(hService);
  2174. service_fns.CloseServiceHandle_fn(hSCManager);
  2175. tor_free(command);
  2176. return 0;
  2177. }
  2178. /** Removes the Tor NT service. Returns 0 if the service was successfully
  2179. * removed, or -1 on error. */
  2180. int
  2181. nt_service_remove(void)
  2182. {
  2183. SC_HANDLE hSCManager = NULL;
  2184. SC_HANDLE hService = NULL;
  2185. char *errmsg;
  2186. nt_service_loadlibrary();
  2187. if ((hSCManager = nt_service_open_scm()) == NULL)
  2188. return -1;
  2189. if ((hService = nt_service_open(hSCManager)) == NULL) {
  2190. service_fns.CloseServiceHandle_fn(hSCManager);
  2191. return -1;
  2192. }
  2193. nt_service_stop(hService);
  2194. if (service_fns.DeleteService_fn(hService) == FALSE) {
  2195. errmsg = nt_strerror(GetLastError());
  2196. printf("DeleteService() failed : %s\n", errmsg);
  2197. LocalFree(errmsg);
  2198. service_fns.CloseServiceHandle_fn(hService);
  2199. service_fns.CloseServiceHandle_fn(hSCManager);
  2200. return -1;
  2201. }
  2202. service_fns.CloseServiceHandle_fn(hService);
  2203. service_fns.CloseServiceHandle_fn(hSCManager);
  2204. printf("Service removed successfully\n");
  2205. return 0;
  2206. }
  2207. /** Starts the Tor service. Returns 0 on success, or -1 on error. */
  2208. int
  2209. nt_service_cmd_start(void)
  2210. {
  2211. SC_HANDLE hSCManager;
  2212. SC_HANDLE hService;
  2213. int start;
  2214. if ((hSCManager = nt_service_open_scm()) == NULL)
  2215. return -1;
  2216. if ((hService = nt_service_open(hSCManager)) == NULL) {
  2217. service_fns.CloseServiceHandle_fn(hSCManager);
  2218. return -1;
  2219. }
  2220. start = nt_service_start(hService);
  2221. service_fns.CloseServiceHandle_fn(hService);
  2222. service_fns.CloseServiceHandle_fn(hSCManager);
  2223. return start;
  2224. }
  2225. /** Stops the Tor service. Returns 0 on success, or -1 on error. */
  2226. int
  2227. nt_service_cmd_stop(void)
  2228. {
  2229. SC_HANDLE hSCManager;
  2230. SC_HANDLE hService;
  2231. int stop;
  2232. if ((hSCManager = nt_service_open_scm()) == NULL)
  2233. return -1;
  2234. if ((hService = nt_service_open(hSCManager)) == NULL) {
  2235. service_fns.CloseServiceHandle_fn(hSCManager);
  2236. return -1;
  2237. }
  2238. stop = nt_service_stop(hService);
  2239. service_fns.CloseServiceHandle_fn(hService);
  2240. service_fns.CloseServiceHandle_fn(hSCManager);
  2241. return stop;
  2242. }
  2243. /** Given a Win32 error code, this attempts to make Windows
  2244. * return a human-readable error message. The char* returned
  2245. * is allocated by Windows, but should be freed with LocalFree()
  2246. * when finished with it. */
  2247. static char*
  2248. nt_strerror(uint32_t errnum)
  2249. {
  2250. char *msgbuf;
  2251. FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  2252. NULL, errnum, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  2253. (LPSTR)&msgbuf, 0, NULL);
  2254. return msgbuf;
  2255. }
  2256. #endif
  2257. #ifdef USE_DMALLOC
  2258. #include <openssl/crypto.h>
  2259. static void
  2260. _tor_dmalloc_free(void *p)
  2261. {
  2262. tor_free(p);
  2263. }
  2264. #endif
  2265. /** Main entry point for the Tor process. Called from main(). */
  2266. /* This function is distinct from main() only so we can link main.c into
  2267. * the unittest binary without conflicting with the unittests' main. */
  2268. int
  2269. tor_main(int argc, char *argv[])
  2270. {
  2271. int result = 0;
  2272. #ifdef USE_DMALLOC
  2273. int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc,
  2274. _tor_dmalloc_free);
  2275. log_notice(LD_CONFIG, "Set up dmalloc; returned %d", r);
  2276. #endif
  2277. #ifdef MS_WINDOWS_SERVICE
  2278. backup_argv = argv;
  2279. backup_argc = argc;
  2280. if ((argc >= 3) &&
  2281. (!strcmp(argv[1], "-service") || !strcmp(argv[1], "--service"))) {
  2282. nt_service_loadlibrary();
  2283. if (!strcmp(argv[2], "install"))
  2284. return nt_service_install(argc, argv);
  2285. if (!strcmp(argv[2], "remove"))
  2286. return nt_service_remove();
  2287. if (!strcmp(argv[2], "start"))
  2288. return nt_service_cmd_start();
  2289. if (!strcmp(argv[2], "stop"))
  2290. return nt_service_cmd_stop();
  2291. printf("Unrecognized service command '%s'\n", argv[2]);
  2292. return -1;
  2293. }
  2294. if (argc >= 2) {
  2295. if (!strcmp(argv[1], "-nt-service") || !strcmp(argv[1], "--nt-service")) {
  2296. nt_service_loadlibrary();
  2297. nt_service_main();
  2298. return 0;
  2299. }
  2300. // These values have been deprecated since 0.1.1.2-alpha; we've warned
  2301. // about them since 0.1.2.7-alpha.
  2302. if (!strcmp(argv[1], "-install") || !strcmp(argv[1], "--install")) {
  2303. nt_service_loadlibrary();
  2304. fprintf(stderr,
  2305. "The %s option is deprecated; use \"--service install\" instead.",
  2306. argv[1]);
  2307. return nt_service_install(argc, argv);
  2308. }
  2309. if (!strcmp(argv[1], "-remove") || !strcmp(argv[1], "--remove")) {
  2310. nt_service_loadlibrary();
  2311. fprintf(stderr,
  2312. "The %s option is deprecated; use \"--service remove\" instead.",
  2313. argv[1]);
  2314. return nt_service_remove();
  2315. }
  2316. }
  2317. #endif
  2318. if (tor_init(argc, argv)<0)
  2319. return -1;
  2320. switch (get_options()->command) {
  2321. case CMD_RUN_TOR:
  2322. #ifdef MS_WINDOWS_SERVICE
  2323. service_status.dwCurrentState = SERVICE_RUNNING;
  2324. #endif
  2325. result = do_main_loop();
  2326. break;
  2327. case CMD_LIST_FINGERPRINT:
  2328. result = do_list_fingerprint();
  2329. break;
  2330. case CMD_HASH_PASSWORD:
  2331. do_hash_password();
  2332. result = 0;
  2333. break;
  2334. case CMD_VERIFY_CONFIG:
  2335. printf("Configuration was valid\n");
  2336. result = 0;
  2337. break;
  2338. case CMD_RUN_UNITTESTS: /* only set by test.c */
  2339. default:
  2340. log_warn(LD_BUG,"Illegal command number %d: internal error.",
  2341. get_options()->command);
  2342. result = -1;
  2343. }
  2344. tor_cleanup();
  2345. return result;
  2346. }