config.c 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char config_c_id[] = "$Id$";
  7. /**
  8. * \file config.c
  9. *
  10. * \brief Code to parse and interpret configuration files.
  11. **/
  12. #include "or.h"
  13. #ifdef MS_WINDOWS
  14. #include <shlobj.h>
  15. #endif
  16. #include "../common/aes.h"
  17. /** Enumeration of types which option values can take */
  18. typedef enum config_type_t {
  19. CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
  20. CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
  21. CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
  22. CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
  23. CONFIG_TYPE_DOUBLE, /**< A floating-point value */
  24. CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
  25. CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and optional
  26. * whitespace. */
  27. CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
  28. CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
  29. * mixed with other keywords. */
  30. CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
  31. * context-sensitive config lines when fetching.
  32. */
  33. CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
  34. } config_type_t;
  35. /* An abbreviation for a configuration option allowed on the command line */
  36. typedef struct config_abbrev_t {
  37. const char *abbreviated;
  38. const char *full;
  39. int commandline_only;
  40. } config_abbrev_t;
  41. /* Handy macro for declaring "In the config file or on the command line,
  42. * you can abbreviate <b>tok</b>s as <b>tok</b>". */
  43. #define PLURAL(tok) { #tok, #tok "s", 0 }
  44. /* A list of command-line abbreviations. */
  45. static config_abbrev_t config_abbrevs[] = {
  46. PLURAL(ExitNode),
  47. PLURAL(EntryNode),
  48. PLURAL(ExcludeNode),
  49. PLURAL(FirewallPort),
  50. PLURAL(HiddenServiceNode),
  51. PLURAL(HiddenServiceExcludeNode),
  52. PLURAL(RendNode),
  53. PLURAL(RendExcludeNode),
  54. PLURAL(StrictEntryNode),
  55. PLURAL(StrictExitNode),
  56. { "l", "Log", 1},
  57. { "BandwidthRateBytes", "BandwidthRate", 0},
  58. { "BandwidthBurstBytes", "BandwidthBurst", 0},
  59. { "DirFetchPostPeriod", "StatusFetchPeriod", 0},
  60. { NULL, NULL , 0},
  61. };
  62. #undef PLURAL
  63. /** A variable allowed in the configuration file or on the command line. */
  64. typedef struct config_var_t {
  65. const char *name; /**< The full keyword (case insensitive). */
  66. config_type_t type; /**< How to interpret the type and turn it into a value. */
  67. off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
  68. const char *initvalue; /**< String (or null) describing initial value. */
  69. } config_var_t;
  70. /** Return the offset of <b>member</b> within the type <b>tp</b>, in bytes */
  71. #define STRUCT_OFFSET(tp, member) ((off_t) (((char*)&((tp*)0)->member)-(char*)0))
  72. /** An entry for config_vars: "The option <b>name</b> has type
  73. * CONFIG_TYPE_<b>conftype</b>, and corresponds to
  74. * or_options_t.<b>member</b>"
  75. */
  76. #define VAR(name,conftype,member,initvalue) \
  77. { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), initvalue }
  78. /** An entry for config_vars: "The option <b>name</b> is obsolete." */
  79. #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
  80. /** Array of configuration options. Until we disallow nonstandard
  81. * abbreviations, order is significant, since the first matching option will
  82. * be chosen first.
  83. */
  84. static config_var_t config_vars[] = {
  85. VAR("Address", STRING, Address, NULL),
  86. VAR("AccountingStart", STRING, AccountingStart, NULL),
  87. VAR("AllowUnverifiedNodes",CSV, AllowUnverifiedNodes, "middle,rendezvous"),
  88. VAR("AuthoritativeDirectory",BOOL, AuthoritativeDir, "0"),
  89. VAR("BandwidthRate", MEMUNIT, BandwidthRate, "780 KB"),
  90. VAR("BandwidthBurst", MEMUNIT, BandwidthBurst, "48 MB"),
  91. VAR("ClientOnly", BOOL, ClientOnly, "0"),
  92. VAR("ContactInfo", STRING, ContactInfo, NULL),
  93. VAR("ControlPort", UINT, ControlPort, "0"),
  94. VAR("CookieAuthentication",BOOL, CookieAuthentication, "0"),
  95. VAR("DebugLogFile", STRING, DebugLogFile, NULL),
  96. VAR("DataDirectory", STRING, DataDirectory, NULL),
  97. VAR("DirPort", UINT, DirPort, "0"),
  98. VAR("DirBindAddress", LINELIST, DirBindAddress, NULL),
  99. /* XXX we'd like dirfetchperiod to be higher for people with dirport not
  100. * set, but low for people with dirport set. how to have two defaults? */
  101. VAR("DirFetchPeriod", INTERVAL, DirFetchPeriod, "1 hour"),
  102. VAR("DirPostPeriod", INTERVAL, DirPostPeriod, "20 minutes"),
  103. VAR("RendPostPeriod", INTERVAL, RendPostPeriod, "20 minutes"),
  104. VAR("DirPolicy", LINELIST, DirPolicy, NULL),
  105. VAR("DirServer", LINELIST, DirServers, NULL),
  106. VAR("ExitNodes", STRING, ExitNodes, NULL),
  107. VAR("EntryNodes", STRING, EntryNodes, NULL),
  108. VAR("StrictExitNodes", BOOL, StrictExitNodes, "0"),
  109. VAR("StrictEntryNodes", BOOL, StrictEntryNodes, "0"),
  110. VAR("ExitPolicy", LINELIST, ExitPolicy, NULL),
  111. VAR("ExcludeNodes", STRING, ExcludeNodes, NULL),
  112. VAR("FascistFirewall", BOOL, FascistFirewall, "0"),
  113. VAR("FirewallPorts", CSV, FirewallPorts, "80,443"),
  114. VAR("MyFamily", STRING, MyFamily, NULL),
  115. VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
  116. VAR("Group", STRING, Group, NULL),
  117. VAR("HashedControlPassword",STRING, HashedControlPassword, NULL),
  118. VAR("HttpProxy", STRING, HttpProxy, NULL),
  119. VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
  120. VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
  121. VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
  122. VAR("HiddenServiceNodes", LINELIST_S, RendConfigLines, NULL),
  123. VAR("HiddenServiceExcludeNodes", LINELIST_S, RendConfigLines, NULL),
  124. VAR("IgnoreVersion", BOOL, IgnoreVersion, "0"),
  125. VAR("KeepalivePeriod", INTERVAL, KeepalivePeriod, "5 minutes"),
  126. VAR("Log", LINELIST, Logs, NULL),
  127. VAR("LogLevel", LINELIST_S, OldLogOptions, NULL),
  128. VAR("LogFile", LINELIST_S, OldLogOptions, NULL),
  129. OBSOLETE("LinkPadding"),
  130. VAR("MaxConn", UINT, MaxConn, "1024"),
  131. VAR("MaxOnionsPending", UINT, MaxOnionsPending, "100"),
  132. VAR("MonthlyAccountingStart",UINT, _MonthlyAccountingStart,"0"),
  133. VAR("AccountingMaxKB", UINT, _AccountingMaxKB, "0"),
  134. VAR("AccountingMax", MEMUNIT, AccountingMax, "0 bytes"),
  135. VAR("Nickname", STRING, Nickname, NULL),
  136. VAR("NewCircuitPeriod", INTERVAL, NewCircuitPeriod, "30 seconds"),
  137. VAR("NumCpus", UINT, NumCpus, "1"),
  138. VAR("ORPort", UINT, ORPort, "0"),
  139. VAR("ORBindAddress", LINELIST, ORBindAddress, NULL),
  140. VAR("OutboundBindAddress", STRING, OutboundBindAddress, NULL),
  141. VAR("PidFile", STRING, PidFile, NULL),
  142. VAR("PathlenCoinWeight", DOUBLE, PathlenCoinWeight, "0.3"),
  143. VAR("RedirectExit", LINELIST, RedirectExit, NULL),
  144. OBSOLETE("RouterFile"),
  145. VAR("RunAsDaemon", BOOL, RunAsDaemon, "0"),
  146. VAR("RunTesting", BOOL, RunTesting, "0"),
  147. VAR("RecommendedVersions", LINELIST, RecommendedVersions, NULL),
  148. VAR("RendNodes", STRING, RendNodes, NULL),
  149. VAR("RendExcludeNodes", STRING, RendExcludeNodes, NULL),
  150. VAR("SocksPort", UINT, SocksPort, "9050"),
  151. VAR("SocksBindAddress", LINELIST, SocksBindAddress, NULL),
  152. VAR("SocksPolicy", LINELIST, SocksPolicy, NULL),
  153. /* XXX as with dirfetchperiod, we want this to be 15 minutes for people
  154. * with a dirport open, but higher for people without a dirport open. */
  155. VAR("StatusFetchPeriod", INTERVAL, StatusFetchPeriod, "15 minutes"),
  156. VAR("SysLog", LINELIST_S, OldLogOptions, NULL),
  157. OBSOLETE("TrafficShaping"),
  158. VAR("User", STRING, User, NULL),
  159. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  160. };
  161. #undef VAR
  162. #undef OBSOLETE
  163. /** Largest allowed config line */
  164. #define CONFIG_LINE_T_MAXLEN 4096
  165. static void option_reset(or_options_t *options, config_var_t *var);
  166. static void options_free(or_options_t *options);
  167. static int option_is_same(or_options_t *o1, or_options_t *o2,const char *name);
  168. static or_options_t *options_dup(or_options_t *old);
  169. static int options_validate(or_options_t *options);
  170. static int options_transition_allowed(or_options_t *old, or_options_t *new);
  171. static int check_nickname_list(const char *lst, const char *name);
  172. static int parse_dir_server_line(const char *line, int validate_only);
  173. static int parse_redirect_line(smartlist_t *result,
  174. struct config_line_t *line);
  175. static int parse_log_severity_range(const char *range, int *min_out,
  176. int *max_out);
  177. static int convert_log_option(or_options_t *options,
  178. struct config_line_t *level_opt,
  179. struct config_line_t *file_opt, int isDaemon);
  180. static int add_single_log_option(or_options_t *options, int minSeverity,
  181. int maxSeverity,
  182. const char *type, const char *fname);
  183. static int normalize_log_options(or_options_t *options);
  184. static int validate_data_directory(or_options_t *options);
  185. static int write_configuration_file(const char *fname, or_options_t *options);
  186. static uint64_t config_parse_memunit(const char *s, int *ok);
  187. static int config_parse_interval(const char *s, int *ok);
  188. static void print_cvs_version(void);
  189. /*
  190. * Functions to read and write the global options pointer.
  191. */
  192. /** Command-line and config-file options. */
  193. static or_options_t *global_options=NULL;
  194. /** Name of most recently read torrc file. */
  195. static char *config_fname = NULL;
  196. /** Return the currently configured options. */
  197. or_options_t *
  198. get_options(void) {
  199. tor_assert(global_options);
  200. return global_options;
  201. }
  202. /** Change the current global options to contain <b>new_val</b> instead
  203. * of their current value; free the old value as necessary.
  204. */
  205. void
  206. set_options(or_options_t *new_val) {
  207. if (global_options)
  208. options_free(global_options);
  209. global_options = new_val;
  210. }
  211. /** Fetch the active option list, and take actions based on it. All
  212. * of the things we do should survive being done repeatedly.
  213. * Return 0 if all goes well, return -1 if it's time to die.
  214. *
  215. * Note 1: <b>new_val</b> must have previously been validated with
  216. * options_validate(), or Tor may freak out and exit.
  217. *
  218. * Note 2: We haven't moved all the "act on new configuration" logic
  219. * here yet. Some is still in do_hup() and other places.
  220. */
  221. int
  222. options_act(void) {
  223. struct config_line_t *cl;
  224. or_options_t *options = get_options();
  225. clear_trusted_dir_servers();
  226. for (cl = options->DirServers; cl; cl = cl->next) {
  227. if (parse_dir_server_line(cl->value, 0)<0) {
  228. log_fn(LOG_ERR,
  229. "Bug: Previously validated DirServer line could not be added!");
  230. return -1;
  231. }
  232. }
  233. if (rend_config_services(options, 0)<0) {
  234. log_fn(LOG_ERR,
  235. "Bug: Previously validated hidden services line could not be added!");
  236. return -1;
  237. }
  238. /* Setuid/setgid as appropriate */
  239. if (options->User || options->Group) {
  240. if (switch_id(options->User, options->Group) != 0) {
  241. return -1;
  242. }
  243. }
  244. /* Ensure data directory is private; create if possible. */
  245. if (check_private_dir(options->DataDirectory, CPD_CREATE) != 0) {
  246. log_fn(LOG_ERR, "Couldn't access/create private data directory %s",
  247. options->DataDirectory);
  248. return -1;
  249. }
  250. /* Bail out at this point if we're not going to be a server: we want
  251. * to not fork, and to log stuff to stderr. */
  252. if (options->command != CMD_RUN_TOR)
  253. return 0;
  254. mark_logs_temp(); /* Close current logs once new logs are open. */
  255. if (config_init_logs(options, 0)<0) /* Configure the log(s) */
  256. return -1;
  257. /* Close the temporary log we used while starting up, if it isn't already
  258. * gone. */
  259. close_temp_logs();
  260. add_callback_log(LOG_NOTICE, LOG_ERR, control_event_logmsg);
  261. if (set_max_file_descriptors(options->MaxConn) < 0)
  262. return -1;
  263. {
  264. smartlist_t *sl = smartlist_create();
  265. for (cl = options->RedirectExit; cl; cl = cl->next) {
  266. if (parse_redirect_line(sl, cl)<0)
  267. return -1;
  268. }
  269. set_exit_redirects(sl);
  270. }
  271. /* Start backgrounding the process, if requested. */
  272. /* XXXX009 We once had a reason to separate start_daemon and finish_daemon:
  273. * It let us have the parent process stick around until we were sure Tor
  274. * was started. Should we make start_daemon get called earlier? -NM */
  275. if (options->RunAsDaemon) {
  276. start_daemon(options->DataDirectory);
  277. }
  278. /* Finish backgrounding the process */
  279. if (options->RunAsDaemon) {
  280. /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
  281. finish_daemon();
  282. }
  283. /* Write our pid to the pid file. If we do not have write permissions we
  284. * will log a warning */
  285. if (options->PidFile)
  286. write_pidfile(options->PidFile);
  287. /* Update address policies. */
  288. parse_socks_policy();
  289. parse_dir_policy();
  290. init_cookie_authentication(options->CookieAuthentication);
  291. /* reload keys as needed for rendezvous services. */
  292. if (rend_service_load_keys()<0) {
  293. log_fn(LOG_ERR,"Error loading rendezvous service keys");
  294. return -1;
  295. }
  296. /* Set up accounting */
  297. if (accounting_parse_options(options, 0)<0) {
  298. log_fn(LOG_ERR,"Error in accounting options");
  299. return -1;
  300. }
  301. if (accounting_is_enabled(options))
  302. configure_accounting(time(NULL));
  303. if (!we_are_hibernating() && retry_all_listeners(1) < 0) {
  304. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  305. return -1;
  306. }
  307. #if 0
  308. {
  309. char *smin, *smax;
  310. smin = config_dump_options(options, 1);
  311. smax = config_dump_options(options, 0);
  312. log_fn(LOG_DEBUG, "These are our options:\n%s",smax);
  313. log_fn(LOG_DEBUG, "We changed these options:\n%s",smin);
  314. tor_free(smin);
  315. tor_free(smax);
  316. }
  317. #endif
  318. /* Since our options changed, we might need to regenerate and upload our
  319. * server descriptor. (We could probably be more clever about only calling
  320. * this when something significant changed.)
  321. */
  322. mark_my_descriptor_dirty();
  323. return 0;
  324. }
  325. /*
  326. * Functions to parse config options
  327. */
  328. /** If <b>option</b> is an official abbreviation for a longer option,
  329. * return the longer option. Otherwise return <b>option</b>.
  330. * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
  331. * apply abbreviations that work for the config file and the command line. */
  332. static const char *
  333. expand_abbrev(const char *option, int command_line)
  334. {
  335. int i;
  336. for (i=0; config_abbrevs[i].abbreviated; ++i) {
  337. /* Abbreviations aren't casei. */
  338. if (!strcasecmp(option,config_abbrevs[i].abbreviated) &&
  339. (command_line || !config_abbrevs[i].commandline_only)) {
  340. return config_abbrevs[i].full;
  341. }
  342. }
  343. return option;
  344. }
  345. /** Helper: Read a list of configuration options from the command line. */
  346. static struct config_line_t *
  347. config_get_commandlines(int argc, char **argv)
  348. {
  349. struct config_line_t *new;
  350. struct config_line_t *front = NULL;
  351. char *s;
  352. int i = 1;
  353. while (i < argc-1) {
  354. if (!strcmp(argv[i],"-f") ||
  355. !strcmp(argv[i],"--hash-password")) {
  356. i += 2; /* command-line option with argument. ignore them. */
  357. continue;
  358. } else if (!strcmp(argv[i],"--list-fingerprint")) {
  359. i += 1; /* command-line option. ignore it. */
  360. continue;
  361. }
  362. new = tor_malloc(sizeof(struct config_line_t));
  363. s = argv[i];
  364. while (*s == '-')
  365. s++;
  366. new->key = tor_strdup(expand_abbrev(s, 1));
  367. new->value = tor_strdup(argv[i+1]);
  368. log(LOG_DEBUG,"Commandline: parsed keyword '%s', value '%s'",
  369. new->key, new->value);
  370. new->next = front;
  371. front = new;
  372. i += 2;
  373. }
  374. return front;
  375. }
  376. /** Helper: allocate a new configuration option mapping 'key' to 'val',
  377. * prepend it to 'front', and return the newly allocated config_line_t */
  378. struct config_line_t *
  379. config_line_prepend(struct config_line_t *front,
  380. const char *key,
  381. const char *val)
  382. {
  383. struct config_line_t *newline;
  384. newline = tor_malloc(sizeof(struct config_line_t));
  385. newline->key = tor_strdup(key);
  386. newline->value = tor_strdup(val);
  387. newline->next = front;
  388. return newline;
  389. }
  390. /** Helper: parse the config string and strdup into key/value
  391. * strings. Set *result to the list, or NULL if parsing the string
  392. * failed. Return 0 on success, -1 on failure. Warn and ignore any
  393. * misformatted lines. */
  394. int
  395. config_get_lines(char *string, struct config_line_t **result)
  396. {
  397. struct config_line_t *list = NULL;
  398. char *k, *v;
  399. do {
  400. string = parse_line_from_str(string, &k, &v);
  401. if (!string) {
  402. config_free_lines(list);
  403. return -1;
  404. }
  405. if (k && v)
  406. list = config_line_prepend(list, k, v);
  407. } while (*string);
  408. *result = list;
  409. return 0;
  410. }
  411. /**
  412. * Free all the configuration lines on the linked list <b>front</b>.
  413. */
  414. void
  415. config_free_lines(struct config_line_t *front)
  416. {
  417. struct config_line_t *tmp;
  418. while (front) {
  419. tmp = front;
  420. front = tmp->next;
  421. tor_free(tmp->key);
  422. tor_free(tmp->value);
  423. tor_free(tmp);
  424. }
  425. }
  426. /** If <b>key</b> is a configuration option, return the corresponding
  427. * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
  428. * warn, and return the corresponding config_var_t. Otherwise return NULL.
  429. */
  430. static config_var_t *config_find_option(const char *key)
  431. {
  432. int i;
  433. /* First, check for an exact (case-insensitive) match */
  434. for (i=0; config_vars[i].name; ++i) {
  435. if (!strcasecmp(key, config_vars[i].name))
  436. return &config_vars[i];
  437. }
  438. /* If none, check for an abbreviated match */
  439. for (i=0; config_vars[i].name; ++i) {
  440. if (!strncasecmp(key, config_vars[i].name, strlen(key))) {
  441. log_fn(LOG_WARN, "The abbreviation '%s' is deprecated. "
  442. "Tell Nick and Roger to make it official, or just use '%s' instead",
  443. key, config_vars[i].name);
  444. return &config_vars[i];
  445. }
  446. }
  447. /* Okay, unrecognized options */
  448. return NULL;
  449. }
  450. /** If <b>c</b> is a syntactically valid configuration line, update
  451. * <b>options</b> with its value and return 0. Otherwise return -1 for bad key,
  452. * -2 for bad value.
  453. *
  454. * If 'reset' is set, and we get a line containing no value, restore the
  455. * option to its default value.
  456. */
  457. static int
  458. config_assign_line(or_options_t *options, struct config_line_t *c, int reset)
  459. {
  460. int i, ok;
  461. config_var_t *var;
  462. void *lvalue;
  463. var = config_find_option(c->key);
  464. if (!var) {
  465. log_fn(LOG_WARN, "Unknown option '%s'. Failing.", c->key);
  466. return -1;
  467. }
  468. /* Put keyword into canonical case. */
  469. if (strcmp(var->name, c->key)) {
  470. tor_free(c->key);
  471. c->key = tor_strdup(var->name);
  472. }
  473. if (reset && !strlen(c->value)) {
  474. option_reset(options, var);
  475. return 0;
  476. }
  477. lvalue = ((char*)options) + var->var_offset;
  478. switch (var->type) {
  479. case CONFIG_TYPE_UINT:
  480. i = tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
  481. if (!ok) {
  482. log(LOG_WARN, "Int keyword '%s %s' is malformed or out of bounds.",
  483. c->key,c->value);
  484. return -2;
  485. }
  486. *(int *)lvalue = i;
  487. break;
  488. case CONFIG_TYPE_INTERVAL: {
  489. i = config_parse_interval(c->value, &ok);
  490. if (!ok) {
  491. return -2;
  492. }
  493. *(int *)lvalue = i;
  494. break;
  495. }
  496. case CONFIG_TYPE_MEMUNIT: {
  497. uint64_t u64 = config_parse_memunit(c->value, &ok);
  498. if (!ok) {
  499. return -2;
  500. }
  501. *(uint64_t *)lvalue = u64;
  502. break;
  503. }
  504. case CONFIG_TYPE_BOOL:
  505. i = tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
  506. if (!ok) {
  507. log(LOG_WARN, "Boolean keyword '%s' expects 0 or 1.", c->key);
  508. return -2;
  509. }
  510. *(int *)lvalue = i;
  511. break;
  512. case CONFIG_TYPE_STRING:
  513. tor_free(*(char **)lvalue);
  514. *(char **)lvalue = tor_strdup(c->value);
  515. break;
  516. case CONFIG_TYPE_DOUBLE:
  517. *(double *)lvalue = atof(c->value);
  518. break;
  519. case CONFIG_TYPE_CSV:
  520. if (*(smartlist_t**)lvalue == NULL)
  521. *(smartlist_t**)lvalue = smartlist_create();
  522. smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
  523. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  524. break;
  525. case CONFIG_TYPE_LINELIST:
  526. case CONFIG_TYPE_LINELIST_S:
  527. /* Note: this reverses the order that the lines appear in. That's
  528. * just fine, since we build up the list of lines reversed in the
  529. * first place. */
  530. *(struct config_line_t**)lvalue =
  531. config_line_prepend(*(struct config_line_t**)lvalue, c->key, c->value);
  532. break;
  533. case CONFIG_TYPE_OBSOLETE:
  534. log_fn(LOG_WARN, "Skipping obsolete configuration option '%s'", c->key);
  535. break;
  536. case CONFIG_TYPE_LINELIST_V:
  537. log_fn(LOG_WARN, "Can't provide value for virtual option '%s'", c->key);
  538. return -2;
  539. default:
  540. tor_assert(0);
  541. break;
  542. }
  543. return 0;
  544. }
  545. /** restore the option named <b>key</b> in options to its default value. */
  546. static void
  547. config_reset_line(or_options_t *options, const char *key)
  548. {
  549. config_var_t *var;
  550. var = config_find_option(key);
  551. if (!var)
  552. return; /* give error on next pass. */
  553. option_reset(options, var);
  554. }
  555. /** Return true iff key is a valid configuration option. */
  556. int
  557. config_option_is_recognized(const char *key)
  558. {
  559. config_var_t *var = config_find_option(key);
  560. return (var != NULL);
  561. }
  562. /** Return a canonicalized list of the options assigned for key.
  563. */
  564. struct config_line_t *
  565. config_get_assigned_option(or_options_t *options, const char *key)
  566. {
  567. config_var_t *var;
  568. const void *value;
  569. char buf[32];
  570. struct config_line_t *result;
  571. tor_assert(options && key);
  572. var = config_find_option(key);
  573. if (!var) {
  574. log_fn(LOG_WARN, "Unknown option '%s'. Failing.", key);
  575. return NULL;
  576. } else if (var->type == CONFIG_TYPE_LINELIST_S) {
  577. log_fn(LOG_WARN, "Can't return context-sensitive '%s' on its own", key);
  578. return NULL;
  579. }
  580. value = ((char*)options) + var->var_offset;
  581. if (var->type == CONFIG_TYPE_LINELIST ||
  582. var->type == CONFIG_TYPE_LINELIST_V) {
  583. /* Linelist requires special handling: we just copy and return it. */
  584. const struct config_line_t *next_in = *(const struct config_line_t**)value;
  585. struct config_line_t **next_out = &result;
  586. while (next_in) {
  587. *next_out = tor_malloc(sizeof(struct config_line_t));
  588. (*next_out)->key = tor_strdup(next_in->key);
  589. (*next_out)->value = tor_strdup(next_in->value);
  590. next_in = next_in->next;
  591. next_out = &((*next_out)->next);
  592. }
  593. (*next_out) = NULL;
  594. return result;
  595. }
  596. result = tor_malloc_zero(sizeof(struct config_line_t));
  597. result->key = tor_strdup(var->name);
  598. switch (var->type)
  599. {
  600. case CONFIG_TYPE_STRING:
  601. if (*(char**)value) {
  602. result->value = tor_strdup(*(char**)value);
  603. } else {
  604. tor_free(result->key);
  605. tor_free(result);
  606. return NULL;
  607. }
  608. break;
  609. case CONFIG_TYPE_INTERVAL:
  610. case CONFIG_TYPE_UINT:
  611. /* This means every or_options_t uint or bool element
  612. * needs to be an int. Not, say, a uint16_t or char. */
  613. tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
  614. result->value = tor_strdup(buf);
  615. break;
  616. case CONFIG_TYPE_MEMUNIT:
  617. tor_snprintf(buf, sizeof(buf), U64_FORMAT,
  618. U64_PRINTF_ARG(*(uint64_t*)value));
  619. result->value = tor_strdup(buf);
  620. break;
  621. case CONFIG_TYPE_DOUBLE:
  622. tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
  623. result->value = tor_strdup(buf);
  624. break;
  625. case CONFIG_TYPE_BOOL:
  626. result->value = tor_strdup(*(int*)value ? "1" : "0");
  627. break;
  628. case CONFIG_TYPE_CSV:
  629. if (*(smartlist_t**)value)
  630. result->value = smartlist_join_strings(*(smartlist_t**)value,",",0,NULL);
  631. else
  632. result->value = tor_strdup("");
  633. break;
  634. case CONFIG_TYPE_OBSOLETE:
  635. log_fn(LOG_WARN,"You asked me for the value of an obsolete config option %s.", key);
  636. tor_free(result->key);
  637. tor_free(result);
  638. return NULL;
  639. default:
  640. tor_free(result->key);
  641. tor_free(result);
  642. log_fn(LOG_WARN,"Bug: unknown type %d for known key %s", var->type, key);
  643. return NULL;
  644. }
  645. return result;
  646. }
  647. /** Iterate through the linked list of requested options <b>list</b>.
  648. * For each item, convert as appropriate and assign to <b>options</b>.
  649. * If an item is unrecognized, return -1 immediately,
  650. * else return 0 for success.
  651. *
  652. * If <b>reset</b>, then interpret empty lines as meaning "restore to
  653. * default value", and interpret LINELIST* options as replacing (not
  654. * extending) their previous values. Return 0 on success, -1 on bad key,
  655. * -2 on bad value.
  656. */
  657. static int
  658. config_assign(or_options_t *options, struct config_line_t *list, int reset)
  659. {
  660. struct config_line_t *p;
  661. tor_assert(options);
  662. /* pass 1: normalize keys */
  663. for (p = list; p; p = p->next) {
  664. const char *full = expand_abbrev(p->key, 0);
  665. if (strcmp(full,p->key)) {
  666. tor_free(p->key);
  667. p->key = tor_strdup(full);
  668. }
  669. }
  670. /* pass 2: if we're reading from a resetting source, clear all mentioned
  671. * linelists. */
  672. if (reset) {
  673. for (p = list; p; p = p->next)
  674. config_reset_line(options, p->key);
  675. }
  676. /* pass 3: assign. */
  677. while (list) {
  678. int r;
  679. if ((r=config_assign_line(options, list, reset)))
  680. return r;
  681. list = list->next;
  682. }
  683. return 0;
  684. }
  685. /** Try assigning <b>list</b> to the global options. You do this by duping
  686. * options, assigning list to the new one, then validating it. If it's
  687. * ok, then throw out the old one and stick with the new one. Else,
  688. * revert to old and return failure. Return 0 on success, -1 on bad
  689. * keys, -2 on bad values, -3 on bad transition.
  690. */
  691. int
  692. config_trial_assign(struct config_line_t *list, int reset)
  693. {
  694. int r;
  695. or_options_t *trial_options = options_dup(get_options());
  696. if ((r=config_assign(trial_options, list, reset)) < 0) {
  697. options_free(trial_options);
  698. return r;
  699. }
  700. if (options_validate(trial_options) < 0) {
  701. options_free(trial_options);
  702. return -2;
  703. }
  704. if (options_transition_allowed(get_options(), trial_options) < 0) {
  705. options_free(trial_options);
  706. return -3;
  707. }
  708. set_options(trial_options); /* we liked it. put it in place. */
  709. return 0;
  710. }
  711. /** Replace the option indexed by <b>var</b> in <b>options</b> with its
  712. * default value. */
  713. static void
  714. option_reset(or_options_t *options, config_var_t *var)
  715. {
  716. struct config_line_t *c;
  717. void *lvalue;
  718. lvalue = ((char*)options) + var->var_offset;
  719. switch (var->type) {
  720. case CONFIG_TYPE_STRING:
  721. tor_free(*(char**)lvalue);
  722. break;
  723. case CONFIG_TYPE_DOUBLE:
  724. *(double*)lvalue = 0.0;
  725. break;
  726. case CONFIG_TYPE_INTERVAL:
  727. case CONFIG_TYPE_UINT:
  728. case CONFIG_TYPE_BOOL:
  729. *(int*)lvalue = 0;
  730. break;
  731. case CONFIG_TYPE_MEMUNIT:
  732. *(uint64_t*)lvalue = 0;
  733. break;
  734. case CONFIG_TYPE_CSV:
  735. if (*(smartlist_t**)lvalue) {
  736. SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
  737. smartlist_free(*(smartlist_t **)lvalue);
  738. *(smartlist_t **)lvalue = NULL;
  739. }
  740. break;
  741. case CONFIG_TYPE_LINELIST:
  742. case CONFIG_TYPE_LINELIST_S:
  743. config_free_lines(*(struct config_line_t **)lvalue);
  744. *(struct config_line_t **)lvalue = NULL;
  745. break;
  746. case CONFIG_TYPE_LINELIST_V:
  747. /* handled by linelist_s. */
  748. break;
  749. case CONFIG_TYPE_OBSOLETE:
  750. break;
  751. }
  752. if (var->initvalue) {
  753. c = tor_malloc_zero(sizeof(struct config_line_t));
  754. c->key = tor_strdup(var->name);
  755. c->value = tor_strdup(var->initvalue);
  756. config_assign_line(options,c,0);
  757. config_free_lines(c);
  758. }
  759. }
  760. /** Set <b>options</b>-&gt;DirServers to contain the default directory
  761. * servers. */
  762. static void
  763. add_default_trusted_dirservers(or_options_t *options)
  764. {
  765. /* moria1 */
  766. options->DirServers = config_line_prepend(options->DirServers, "DirServer",
  767. "18.244.0.188:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
  768. /* moria2 */
  769. options->DirServers = config_line_prepend(options->DirServers, "DirServer",
  770. "18.244.0.114:80 719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF");
  771. /* tor26 */
  772. options->DirServers = config_line_prepend(options->DirServers, "DirServer",
  773. "62.116.124.106:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
  774. // "tor.noreply.org:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
  775. }
  776. /** Print a usage message for tor. */
  777. static void
  778. print_usage(void)
  779. {
  780. printf(
  781. "Copyright 2001-2004 Roger Dingledine, Nick Mathewson, Matej Pfajfar.\n\n"
  782. "tor -f <torrc> [args]\n"
  783. "See man page for options, or http://tor.eff.org/ for documentation.\n");
  784. }
  785. /**
  786. * Based on <b>address</b>, guess our public IP address and put it
  787. * in <b>addr</b>.
  788. */
  789. int
  790. resolve_my_address(const char *address, uint32_t *addr)
  791. {
  792. struct in_addr in;
  793. struct hostent *rent;
  794. char hostname[256];
  795. int explicit_ip=1;
  796. tor_assert(addr);
  797. if (address) {
  798. strlcpy(hostname, address, sizeof(hostname));
  799. } else { /* then we need to guess our address */
  800. explicit_ip = 0; /* it's implicit */
  801. if (gethostname(hostname, sizeof(hostname)) < 0) {
  802. log_fn(LOG_WARN,"Error obtaining local hostname");
  803. return -1;
  804. }
  805. log_fn(LOG_DEBUG,"Guessed local host name as '%s'",hostname);
  806. }
  807. /* now we know hostname. resolve it and keep only the IP */
  808. if (tor_inet_aton(hostname, &in) == 0) {
  809. /* then we have to resolve it */
  810. explicit_ip = 0;
  811. rent = (struct hostent *)gethostbyname(hostname);
  812. if (!rent) {
  813. log_fn(LOG_WARN,"Could not resolve local Address %s. Failing.", hostname);
  814. return -1;
  815. }
  816. tor_assert(rent->h_length == 4);
  817. memcpy(&in.s_addr, rent->h_addr, rent->h_length);
  818. }
  819. if (!explicit_ip && is_internal_IP(htonl(in.s_addr))) {
  820. log_fn(LOG_WARN,"Address '%s' resolves to private IP '%s'. "
  821. "Please set the Address config option to be the IP you want to use.",
  822. hostname, inet_ntoa(in));
  823. return -1;
  824. }
  825. log_fn(LOG_DEBUG, "Resolved Address to %s.", inet_ntoa(in));
  826. *addr = ntohl(in.s_addr);
  827. return 0;
  828. }
  829. /** Called when we don't have a nickname set. Try to guess a good
  830. * nickname based on the hostname, and return it in a newly allocated string. */
  831. static char *
  832. get_default_nickname(void)
  833. {
  834. char localhostname[256];
  835. char *cp, *out, *outp;
  836. if (gethostname(localhostname, sizeof(localhostname)) < 0) {
  837. log_fn(LOG_WARN,"Error obtaining local hostname");
  838. return NULL;
  839. }
  840. /* Put it in lowercase; stop at the first dot. */
  841. for (cp = localhostname; *cp; ++cp) {
  842. if (*cp == '.') {
  843. *cp = '\0';
  844. break;
  845. }
  846. *cp = tolower(*cp);
  847. }
  848. /* Strip invalid characters. */
  849. cp = localhostname;
  850. out = outp = tor_malloc(strlen(localhostname) + 1);
  851. while (*cp) {
  852. if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
  853. *outp++ = *cp++;
  854. else
  855. cp++;
  856. }
  857. *outp = '\0';
  858. /* Enforce length. */
  859. if (strlen(out) > MAX_NICKNAME_LEN)
  860. out[MAX_NICKNAME_LEN]='\0';
  861. return out;
  862. }
  863. /** Release storage held by <b>options</b> */
  864. static void
  865. options_free(or_options_t *options)
  866. {
  867. int i;
  868. void *lvalue;
  869. tor_assert(options);
  870. for (i=0; config_vars[i].name; ++i) {
  871. lvalue = ((char*)options) + config_vars[i].var_offset;
  872. switch (config_vars[i].type) {
  873. case CONFIG_TYPE_MEMUNIT:
  874. case CONFIG_TYPE_INTERVAL:
  875. case CONFIG_TYPE_UINT:
  876. case CONFIG_TYPE_BOOL:
  877. case CONFIG_TYPE_DOUBLE:
  878. case CONFIG_TYPE_OBSOLETE:
  879. break; /* nothing to free for these config types */
  880. case CONFIG_TYPE_STRING:
  881. tor_free(*(char **)lvalue);
  882. break;
  883. case CONFIG_TYPE_LINELIST:
  884. case CONFIG_TYPE_LINELIST_V:
  885. config_free_lines(*(struct config_line_t**)lvalue);
  886. *(struct config_line_t**)lvalue = NULL;
  887. break;
  888. case CONFIG_TYPE_CSV:
  889. if (*(smartlist_t**)lvalue) {
  890. SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
  891. smartlist_free(*(smartlist_t**)lvalue);
  892. *(smartlist_t**)lvalue = NULL;
  893. }
  894. break;
  895. case CONFIG_TYPE_LINELIST_S:
  896. /* will be freed by corresponding LINELIST_V. */
  897. break;
  898. }
  899. }
  900. tor_free(options);
  901. }
  902. /** Return true iff the option <b>var</b> has the same value in <b>o1</b>
  903. * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
  904. */
  905. static int
  906. option_is_same(or_options_t *o1, or_options_t *o2, const char *name)
  907. {
  908. struct config_line_t *c1, *c2;
  909. int r = 1;
  910. c1 = config_get_assigned_option(o1, name);
  911. c2 = config_get_assigned_option(o2, name);
  912. while (c1 && c2) {
  913. if (strcasecmp(c1->key, c2->key) ||
  914. strcmp(c1->value, c2->value)) {
  915. r = 0;
  916. break;
  917. }
  918. c1 = c1->next;
  919. c2 = c2->next;
  920. }
  921. if (r && (c1 || c2)) {
  922. r = 0;
  923. }
  924. config_free_lines(c1);
  925. config_free_lines(c2);
  926. return r;
  927. }
  928. /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
  929. static or_options_t *
  930. options_dup(or_options_t *old)
  931. {
  932. or_options_t *newopts;
  933. int i;
  934. struct config_line_t *line;
  935. newopts = tor_malloc_zero(sizeof(or_options_t));
  936. for (i=0; config_vars[i].name; ++i) {
  937. if (config_vars[i].type == CONFIG_TYPE_LINELIST_S)
  938. continue;
  939. if (config_vars[i].type == CONFIG_TYPE_OBSOLETE)
  940. continue;
  941. line = config_get_assigned_option(old, config_vars[i].name);
  942. if (line) {
  943. if (config_assign(newopts, line, 0) < 0) {
  944. log_fn(LOG_WARN,"Bug: config_get_assigned_option() generated "
  945. "something we couldn't config_assign().");
  946. tor_assert(0);
  947. }
  948. }
  949. config_free_lines(line);
  950. }
  951. return newopts;
  952. }
  953. /** Set <b>options</b> to hold reasonable defaults for most options.
  954. * Each option defaults to zero. */
  955. void
  956. options_init(or_options_t *options)
  957. {
  958. int i;
  959. config_var_t *var;
  960. for (i=0; config_vars[i].name; ++i) {
  961. var = &config_vars[i];
  962. if (!var->initvalue)
  963. continue; /* defaults to NULL or 0 */
  964. option_reset(options, var);
  965. }
  966. }
  967. /** Return a string containing a possible configuration file that would give
  968. * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
  969. * include options that are the same as Tor's defaults.
  970. */
  971. char *
  972. config_dump_options(or_options_t *options, int minimal)
  973. {
  974. smartlist_t *elements;
  975. or_options_t *defaults;
  976. struct config_line_t *line;
  977. char *result;
  978. int i;
  979. defaults = tor_malloc_zero(sizeof(or_options_t));
  980. options_init(defaults);
  981. options_validate(defaults); /* ??? will this work? */
  982. elements = smartlist_create();
  983. for (i=0; config_vars[i].name; ++i) {
  984. if (config_vars[i].type == CONFIG_TYPE_OBSOLETE ||
  985. config_vars[i].type == CONFIG_TYPE_LINELIST_S)
  986. continue;
  987. if (minimal && option_is_same(options, defaults, config_vars[i].name))
  988. continue;
  989. line = config_get_assigned_option(options, config_vars[i].name);
  990. for (; line; line = line->next) {
  991. size_t len = strlen(line->key) + strlen(line->value) + 3;
  992. char *tmp;
  993. tmp = tor_malloc(len);
  994. if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
  995. log_fn(LOG_ERR, "Internal error writing log option");
  996. tor_assert(0);
  997. }
  998. smartlist_add(elements, tmp);
  999. }
  1000. config_free_lines(line);
  1001. }
  1002. result = smartlist_join_strings(elements, "", 0, NULL);
  1003. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  1004. smartlist_free(elements);
  1005. return result;
  1006. }
  1007. /** Return 0 if every setting in <b>options</b> is reasonable. Else
  1008. * warn and return -1. Should have no side effects, except for
  1009. * normalizing the contents of <b>options</b>. */
  1010. static int
  1011. options_validate(or_options_t *options)
  1012. {
  1013. int i;
  1014. int result = 0;
  1015. struct config_line_t *cl;
  1016. addr_policy_t *addr_policy=NULL;
  1017. if (options->ORPort < 0 || options->ORPort > 65535) {
  1018. log(LOG_WARN, "ORPort option out of bounds.");
  1019. result = -1;
  1020. }
  1021. /* XXX might similarly want to check the other *BindAddress options */
  1022. if (options->ORPort == 0 && options->ORBindAddress != NULL) {
  1023. log(LOG_WARN, "ORPort must be defined if ORBindAddress is defined.");
  1024. result = -1;
  1025. }
  1026. if (validate_data_directory(options)<0) {
  1027. log(LOG_WARN, "Invalid DataDirectory");
  1028. result = -1;
  1029. }
  1030. if (options->Nickname == NULL) {
  1031. if (server_mode(options)) {
  1032. if (!(options->Nickname = get_default_nickname()))
  1033. return -1;
  1034. log_fn(LOG_NOTICE, "Choosing default nickname %s", options->Nickname);
  1035. }
  1036. } else {
  1037. if (strspn(options->Nickname, LEGAL_NICKNAME_CHARACTERS) !=
  1038. strlen(options->Nickname)) {
  1039. log_fn(LOG_WARN, "Nickname '%s' contains illegal characters.", options->Nickname);
  1040. result = -1;
  1041. }
  1042. if (strlen(options->Nickname) == 0) {
  1043. log_fn(LOG_WARN, "Nickname must have at least one character");
  1044. result = -1;
  1045. }
  1046. if (strlen(options->Nickname) > MAX_NICKNAME_LEN) {
  1047. log_fn(LOG_WARN, "Nickname '%s' has more than %d characters.",
  1048. options->Nickname, MAX_NICKNAME_LEN);
  1049. result = -1;
  1050. }
  1051. }
  1052. if (normalize_log_options(options))
  1053. return -1;
  1054. /* Special case if no options are given. */
  1055. if (!options->Logs) {
  1056. options->Logs = config_line_prepend(NULL, "Log", "notice stdout");
  1057. }
  1058. if (config_init_logs(options, 1)<0) /* Validate the log(s) */
  1059. return -1;
  1060. if (server_mode(options)) {
  1061. /* confirm that our address isn't broken, so we can complain now */
  1062. uint32_t tmp;
  1063. if (resolve_my_address(options->Address, &tmp) < 0)
  1064. result = -1;
  1065. }
  1066. if (options->SocksPort < 0 || options->SocksPort > 65535) {
  1067. log(LOG_WARN, "SocksPort option out of bounds.");
  1068. result = -1;
  1069. }
  1070. if (options->SocksPort == 0 && options->ORPort == 0) {
  1071. log(LOG_WARN, "SocksPort and ORPort are both undefined? Quitting.");
  1072. result = -1;
  1073. }
  1074. if (options->ControlPort < 0 || options->ControlPort > 65535) {
  1075. log(LOG_WARN, "ControlPort option out of bounds.");
  1076. result = -1;
  1077. }
  1078. if (options->DirPort < 0 || options->DirPort > 65535) {
  1079. log(LOG_WARN, "DirPort option out of bounds.");
  1080. result = -1;
  1081. }
  1082. if (options->StrictExitNodes &&
  1083. (!options->ExitNodes || !strlen(options->ExitNodes))) {
  1084. log(LOG_WARN, "StrictExitNodes set, but no ExitNodes listed.");
  1085. }
  1086. if (options->StrictEntryNodes &&
  1087. (!options->EntryNodes || !strlen(options->EntryNodes))) {
  1088. log(LOG_WARN, "StrictEntryNodes set, but no EntryNodes listed.");
  1089. }
  1090. if (options->AuthoritativeDir && options->RecommendedVersions == NULL) {
  1091. log(LOG_WARN, "Directory servers must configure RecommendedVersions.");
  1092. result = -1;
  1093. }
  1094. if (options->AuthoritativeDir && !options->DirPort) {
  1095. log(LOG_WARN, "Running as authoritative directory, but no DirPort set.");
  1096. result = -1;
  1097. }
  1098. if (options->AuthoritativeDir && !options->ORPort) {
  1099. log(LOG_WARN, "Running as authoritative directory, but no ORPort set.");
  1100. result = -1;
  1101. }
  1102. if (options->AuthoritativeDir && options->ClientOnly) {
  1103. log(LOG_WARN, "Running as authoritative directory, but ClientOnly also set.");
  1104. result = -1;
  1105. }
  1106. if (options->_AccountingMaxKB) {
  1107. log(LOG_WARN, "AccountingMaxKB is deprecated. Say 'AccountingMax %d KB' instead.", options->_AccountingMaxKB);
  1108. options->AccountingMax = U64_LITERAL(1024)*options->_AccountingMaxKB;
  1109. options->_AccountingMaxKB = 0;
  1110. }
  1111. if (options->FirewallPorts) {
  1112. SMARTLIST_FOREACH(options->FirewallPorts, const char *, cp,
  1113. {
  1114. i = atoi(cp);
  1115. if (i < 1 || i > 65535) {
  1116. log(LOG_WARN, "Port '%s' out of range in FirewallPorts", cp);
  1117. result=-1;
  1118. }
  1119. });
  1120. }
  1121. options->_AllowUnverified = 0;
  1122. if (options->AllowUnverifiedNodes) {
  1123. SMARTLIST_FOREACH(options->AllowUnverifiedNodes, const char *, cp, {
  1124. if (!strcasecmp(cp, "entry"))
  1125. options->_AllowUnverified |= ALLOW_UNVERIFIED_ENTRY;
  1126. else if (!strcasecmp(cp, "exit"))
  1127. options->_AllowUnverified |= ALLOW_UNVERIFIED_EXIT;
  1128. else if (!strcasecmp(cp, "middle"))
  1129. options->_AllowUnverified |= ALLOW_UNVERIFIED_MIDDLE;
  1130. else if (!strcasecmp(cp, "introduction"))
  1131. options->_AllowUnverified |= ALLOW_UNVERIFIED_INTRODUCTION;
  1132. else if (!strcasecmp(cp, "rendezvous"))
  1133. options->_AllowUnverified |= ALLOW_UNVERIFIED_RENDEZVOUS;
  1134. else {
  1135. log(LOG_WARN, "Unrecognized value '%s' in AllowUnverifiedNodes",
  1136. cp);
  1137. result=-1;
  1138. }
  1139. });
  1140. }
  1141. if (options->SocksPort >= 1 &&
  1142. (options->PathlenCoinWeight < 0.0 || options->PathlenCoinWeight >= 1.0)) {
  1143. log(LOG_WARN, "PathlenCoinWeight option must be >=0.0 and <1.0.");
  1144. result = -1;
  1145. }
  1146. if (options->MaxConn < 1) {
  1147. log(LOG_WARN, "MaxConn option must be a non-zero positive integer.");
  1148. result = -1;
  1149. }
  1150. if (options->MaxConn >= MAXCONNECTIONS) {
  1151. log(LOG_WARN, "MaxConn option must be less than %d.", MAXCONNECTIONS);
  1152. result = -1;
  1153. }
  1154. #define MIN_DIR_FETCH_PERIOD 600
  1155. #define MIN_DIR_POST_PERIOD 300
  1156. #define MIN_REND_POST_PERIOD 300
  1157. #define MIN_STATUS_FETCH_PERIOD 60
  1158. /* After 0.0.8 is dead, change this to MIN_ONION_KEY_LIFETIME. */
  1159. #define MAX_DIR_PERIOD (OLD_MIN_ONION_KEY_LIFETIME/2)
  1160. #define MAX_CACHE_DIR_FETCH_PERIOD 3600
  1161. #define MAX_CACHE_STATUS_FETCH_PERIOD 900
  1162. if (options->DirFetchPeriod < MIN_DIR_FETCH_PERIOD) {
  1163. log(LOG_WARN, "DirFetchPeriod option must be at least %d seconds. Clipping.", MIN_DIR_FETCH_PERIOD);
  1164. options->DirFetchPeriod = MIN_DIR_FETCH_PERIOD;
  1165. }
  1166. if (options->StatusFetchPeriod < MIN_STATUS_FETCH_PERIOD) {
  1167. log(LOG_WARN, "StatusFetchPeriod option must be at least %d seconds. Clipping.", MIN_STATUS_FETCH_PERIOD);
  1168. options->StatusFetchPeriod = MIN_STATUS_FETCH_PERIOD;
  1169. }
  1170. if (options->DirPostPeriod < MIN_DIR_POST_PERIOD) {
  1171. log(LOG_WARN, "DirPostPeriod option must be at least %d seconds. Clipping.",
  1172. MIN_DIR_POST_PERIOD);
  1173. options->DirPostPeriod = MIN_DIR_POST_PERIOD;
  1174. }
  1175. if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
  1176. log(LOG_WARN,"RendPostPeriod option must be at least %d seconds. Clipping.",
  1177. MIN_REND_POST_PERIOD);
  1178. options->RendPostPeriod = MIN_REND_POST_PERIOD;
  1179. }
  1180. if (options->DirPort && ! options->AuthoritativeDir) {
  1181. if (options->DirFetchPeriod > MAX_CACHE_DIR_FETCH_PERIOD) {
  1182. log(LOG_WARN, "Caching directory servers must have DirFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_DIR_FETCH_PERIOD);
  1183. options->DirFetchPeriod = MAX_CACHE_DIR_FETCH_PERIOD;
  1184. }
  1185. if (options->StatusFetchPeriod > MAX_CACHE_STATUS_FETCH_PERIOD) {
  1186. log(LOG_WARN, "Caching directory servers must have StatusFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_STATUS_FETCH_PERIOD);
  1187. options->StatusFetchPeriod = MAX_CACHE_STATUS_FETCH_PERIOD;
  1188. }
  1189. }
  1190. if (options->DirFetchPeriod > MAX_DIR_PERIOD) {
  1191. log(LOG_WARN, "DirFetchPeriod is too large; clipping.");
  1192. options->DirFetchPeriod = MAX_DIR_PERIOD;
  1193. }
  1194. if (options->DirPostPeriod > MAX_DIR_PERIOD) {
  1195. log(LOG_WARN, "DirPostPeriod is too large; clipping.");
  1196. options->DirPostPeriod = MAX_DIR_PERIOD;
  1197. }
  1198. if (options->StatusFetchPeriod > MAX_DIR_PERIOD) {
  1199. log(LOG_WARN, "StatusFetchPeriod is too large; clipping.");
  1200. options->StatusFetchPeriod = MAX_DIR_PERIOD;
  1201. }
  1202. if (options->RendPostPeriod > MAX_DIR_PERIOD) {
  1203. log(LOG_WARN, "RendPostPeriod is too large; clipping.");
  1204. options->RendPostPeriod = MAX_DIR_PERIOD;
  1205. }
  1206. if (options->KeepalivePeriod < 1) {
  1207. log(LOG_WARN,"KeepalivePeriod option must be positive.");
  1208. result = -1;
  1209. }
  1210. if (2*options->BandwidthRate >= options->BandwidthBurst) {
  1211. log(LOG_WARN,"BandwidthBurst must be more than twice BandwidthRate.");
  1212. result = -1;
  1213. }
  1214. if (options->BandwidthRate > INT_MAX) {
  1215. log(LOG_WARN,"BandwidthRate must be less than %d",INT_MAX);
  1216. result = -1;
  1217. }
  1218. if (options->BandwidthBurst > INT_MAX) {
  1219. log(LOG_WARN,"BandwidthBurst must be less than %d",INT_MAX);
  1220. result = -1;
  1221. }
  1222. if (server_mode(options) &&
  1223. options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
  1224. log(LOG_WARN,"BandwidthRate is set to %d bytes/second. For servers, it must be at least %d.", (int)options->BandwidthRate, ROUTER_REQUIRED_MIN_BANDWIDTH);
  1225. result = -1;
  1226. }
  1227. if (options->_MonthlyAccountingStart) {
  1228. if (options->AccountingStart) {
  1229. log(LOG_WARN,"Can't specify AccountingStart and MonthlyAccountingStart");
  1230. result = -1;
  1231. } else {
  1232. options->AccountingStart = tor_malloc(32);
  1233. if (tor_snprintf(options->AccountingStart, 32, "month %d 0:00",
  1234. options->_MonthlyAccountingStart)<0) {
  1235. log_fn(LOG_WARN,"Error translating MonthlyAccountingStart");
  1236. result = -1;
  1237. } else {
  1238. log_fn(LOG_WARN,"MonthlyAccountingStart is deprecated. Use 'AccountingStart %s' instead.", options->AccountingStart);
  1239. }
  1240. }
  1241. }
  1242. if (accounting_parse_options(options, 1)<0) {
  1243. result = -1;
  1244. }
  1245. if (options->HttpProxy) { /* parse it now */
  1246. if (parse_addr_port(options->HttpProxy, NULL,
  1247. &options->HttpProxyAddr, &options->HttpProxyPort) < 0) {
  1248. log(LOG_WARN,"HttpProxy failed to parse or resolve. Please fix.");
  1249. result = -1;
  1250. }
  1251. if (options->HttpProxyPort == 0) { /* give it a default */
  1252. options->HttpProxyPort = 80;
  1253. }
  1254. }
  1255. if (options->HashedControlPassword) {
  1256. if (decode_hashed_password(NULL, options->HashedControlPassword)<0) {
  1257. log_fn(LOG_WARN,"Bad HashedControlPassword: wrong length or bad base64");
  1258. result = -1;
  1259. }
  1260. }
  1261. if (options->HashedControlPassword && options->CookieAuthentication) {
  1262. log_fn(LOG_WARN,"Cannot enable both HashedControlPassword and CookieAuthentication");
  1263. result = -1;
  1264. }
  1265. if (check_nickname_list(options->ExitNodes, "ExitNodes"))
  1266. result = -1;
  1267. if (check_nickname_list(options->EntryNodes, "EntryNodes"))
  1268. result = -1;
  1269. if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes"))
  1270. result = -1;
  1271. if (check_nickname_list(options->RendNodes, "RendNodes"))
  1272. result = -1;
  1273. if (check_nickname_list(options->RendNodes, "RendExcludeNodes"))
  1274. result = -1;
  1275. if (check_nickname_list(options->MyFamily, "MyFamily"))
  1276. result = -1;
  1277. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  1278. if (check_nickname_list(cl->value, "NodeFamily"))
  1279. result = -1;
  1280. }
  1281. if (config_parse_addr_policy(options->ExitPolicy, &addr_policy)) {
  1282. log_fn(LOG_WARN, "Error in Exit Policy entry.");
  1283. result = -1;
  1284. }
  1285. if (config_parse_addr_policy(options->DirPolicy, &addr_policy)) {
  1286. log_fn(LOG_WARN, "Error in DirPolicy entry.");
  1287. result = -1;
  1288. }
  1289. if (config_parse_addr_policy(options->SocksPolicy, &addr_policy)) {
  1290. log_fn(LOG_WARN, "Error in SocksPolicy entry.");
  1291. result = -1;
  1292. }
  1293. addr_policy_free(addr_policy);
  1294. for (cl = options->RedirectExit; cl; cl = cl->next) {
  1295. if (parse_redirect_line(NULL, cl)<0)
  1296. result = -1;
  1297. }
  1298. if (!options->DirServers) {
  1299. add_default_trusted_dirservers(options);
  1300. } else {
  1301. for (cl = options->DirServers; cl; cl = cl->next) {
  1302. if (parse_dir_server_line(cl->value, 1)<0)
  1303. result = -1;
  1304. }
  1305. }
  1306. if (rend_config_services(options, 1) < 0)
  1307. result = -1;
  1308. return result;
  1309. }
  1310. /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
  1311. * equal strings. */
  1312. static int
  1313. opt_streq(const char *s1, const char *s2)
  1314. {
  1315. if (!s1 && !s2)
  1316. return 1;
  1317. else if (s1 && s2 && !strcmp(s1,s2))
  1318. return 1;
  1319. else
  1320. return 0;
  1321. }
  1322. /** Check if any of the previous options have changed but aren't allowed to. */
  1323. static int
  1324. options_transition_allowed(or_options_t *old, or_options_t *new_val) {
  1325. if (!old)
  1326. return 0;
  1327. if (!opt_streq(old->PidFile, new_val->PidFile)) {
  1328. log_fn(LOG_WARN,"PidFile is not allowed to change. Failing.");
  1329. return -1;
  1330. }
  1331. if (old->RunAsDaemon && !new_val->RunAsDaemon) {
  1332. log_fn(LOG_WARN,"During reload, change from RunAsDaemon=1 to =0 not allowed. Failing.");
  1333. return -1;
  1334. }
  1335. if (old->ORPort != new_val->ORPort) {
  1336. log_fn(LOG_WARN,"During reload, changing ORPort is not allowed. Failing.");
  1337. return -1;
  1338. }
  1339. if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
  1340. log_fn(LOG_WARN,"During reload, changing DataDirectory (%s->%s) is not allowed. Failing.", old->DataDirectory, new_val->DataDirectory);
  1341. return -1;
  1342. }
  1343. if (!opt_streq(old->User, new_val->User)) {
  1344. log_fn(LOG_WARN,"During reload, changing User is not allowed. Failing.");
  1345. return -1;
  1346. }
  1347. if (!opt_streq(old->Group, new_val->Group)) {
  1348. log_fn(LOG_WARN,"During reload, changing User is not allowed. Failing.");
  1349. return -1;
  1350. }
  1351. return 0;
  1352. }
  1353. #ifdef MS_WINDOWS
  1354. /** Return the directory on windows where we expect to find our application
  1355. * data. */
  1356. static char *get_windows_conf_root(void)
  1357. {
  1358. static int is_set = 0;
  1359. static char path[MAX_PATH+1];
  1360. LPITEMIDLIST idl;
  1361. IMalloc *m;
  1362. HRESULT result;
  1363. if (is_set)
  1364. return path;
  1365. /* Find X:\documents and settings\username\application data\ .
  1366. * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
  1367. */
  1368. if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
  1369. &idl))) {
  1370. GetCurrentDirectory(MAX_PATH, path);
  1371. is_set = 1;
  1372. log_fn(LOG_WARN, "I couldn't find your application data folder: are you running an ancient version of Windows 95? Defaulting to '%s'", path);
  1373. return path;
  1374. }
  1375. /* Convert the path from an "ID List" (whatever that is!) to a path. */
  1376. result = SHGetPathFromIDList(idl, path);
  1377. /* Now we need to free the */
  1378. SHGetMalloc(&m);
  1379. if (m) {
  1380. m->lpVtbl->Free(m, idl);
  1381. m->lpVtbl->Release(m);
  1382. }
  1383. if (!SUCCEEDED(result)) {
  1384. return NULL;
  1385. }
  1386. strlcat(path,"\\tor",MAX_PATH);
  1387. is_set = 1;
  1388. return path;
  1389. }
  1390. #endif
  1391. /** Return the default location for our torrc file. */
  1392. static char *
  1393. get_default_conf_file(void)
  1394. {
  1395. #ifdef MS_WINDOWS
  1396. char *path = tor_malloc(MAX_PATH);
  1397. strlcpy(path, get_windows_conf_root(), MAX_PATH);
  1398. strlcat(path,"\\torrc",MAX_PATH);
  1399. return path;
  1400. #else
  1401. return tor_strdup(CONFDIR "/torrc");
  1402. #endif
  1403. }
  1404. /** Verify whether lst is a string containing valid-looking space-separated
  1405. * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
  1406. */
  1407. static int check_nickname_list(const char *lst, const char *name)
  1408. {
  1409. int r = 0;
  1410. smartlist_t *sl;
  1411. if (!lst)
  1412. return 0;
  1413. sl = smartlist_create();
  1414. smartlist_split_string(sl, lst, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1415. SMARTLIST_FOREACH(sl, const char *, s,
  1416. {
  1417. if (!is_legal_nickname_or_hexdigest(s)) {
  1418. log_fn(LOG_WARN, "Invalid nickname '%s' in %s line", s, name);
  1419. r = -1;
  1420. }
  1421. });
  1422. SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
  1423. smartlist_free(sl);
  1424. return r;
  1425. }
  1426. /** Read a configuration file into <b>options</b>, finding the configuration
  1427. * file location based on the command line. After loading the options,
  1428. * validate them for consistency, then take actions based on them.
  1429. * Return 0 if success, -1 if failure. */
  1430. int
  1431. init_from_config(int argc, char **argv)
  1432. {
  1433. or_options_t *oldoptions, *newoptions;
  1434. struct config_line_t *cl;
  1435. char *cf=NULL, *fname=NULL;
  1436. int i, retval;
  1437. int using_default_torrc;
  1438. static char **backup_argv;
  1439. static int backup_argc;
  1440. if (argv) { /* first time we're called. save commandline args */
  1441. backup_argv = argv;
  1442. backup_argc = argc;
  1443. oldoptions = NULL;
  1444. } else { /* we're reloading. need to clean up old options first. */
  1445. argv = backup_argv;
  1446. argc = backup_argc;
  1447. oldoptions = get_options();
  1448. }
  1449. if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
  1450. print_usage();
  1451. exit(0);
  1452. }
  1453. if (argc > 1 && (!strcmp(argv[1],"--version"))) {
  1454. printf("Tor version %s.\n",VERSION);
  1455. if (argc > 2 && (!strcmp(argv[2],"--version"))) {
  1456. print_cvs_version();
  1457. }
  1458. exit(0);
  1459. }
  1460. newoptions = tor_malloc_zero(sizeof(or_options_t));
  1461. options_init(newoptions);
  1462. /* learn config file name, get config lines, assign them */
  1463. fname = NULL;
  1464. using_default_torrc = 1;
  1465. newoptions->command = CMD_RUN_TOR;
  1466. for (i = 1; i < argc; ++i) {
  1467. if (i < argc-1 && !strcmp(argv[i],"-f")) {
  1468. if (fname) {
  1469. log(LOG_WARN, "Duplicate -f options on command line.");
  1470. tor_free(fname);
  1471. }
  1472. fname = tor_strdup(argv[i+1]);
  1473. using_default_torrc = 0;
  1474. ++i;
  1475. } else if (!strcmp(argv[i],"--list-fingerprint")) {
  1476. newoptions->command = CMD_LIST_FINGERPRINT;
  1477. } else if (!strcmp(argv[i],"--hash-password")) {
  1478. newoptions->command = CMD_HASH_PASSWORD;
  1479. newoptions->command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
  1480. ++i;
  1481. }
  1482. }
  1483. if (using_default_torrc) {
  1484. /* didn't find one, try CONFDIR */
  1485. char *fn;
  1486. fn = get_default_conf_file();
  1487. if (fn && file_status(fn) == FN_FILE) {
  1488. fname = fn;
  1489. } else {
  1490. tor_free(fn);
  1491. fn = expand_filename("~/.torrc");
  1492. if (fn && file_status(fn) == FN_FILE) {
  1493. fname = fn;
  1494. } else {
  1495. tor_free(fn);
  1496. fname = get_default_conf_file();
  1497. }
  1498. }
  1499. }
  1500. tor_assert(fname);
  1501. log(LOG_DEBUG, "Opening config file '%s'", fname);
  1502. cf = read_file_to_str(fname, 0);
  1503. if (!cf) {
  1504. if (using_default_torrc == 1) {
  1505. log(LOG_NOTICE, "Configuration file '%s' not present, "
  1506. "using reasonable defaults.", fname);
  1507. tor_free(fname); /* sets fname to NULL */
  1508. } else {
  1509. log(LOG_WARN, "Unable to open configuration file '%s'.", fname);
  1510. tor_free(fname);
  1511. goto err;
  1512. }
  1513. } else { /* it opened successfully. use it. */
  1514. retval = config_get_lines(cf, &cl);
  1515. tor_free(cf);
  1516. if (retval < 0)
  1517. goto err;
  1518. retval = config_assign(newoptions, cl, 0);
  1519. config_free_lines(cl);
  1520. if (retval < 0)
  1521. goto err;
  1522. }
  1523. /* Go through command-line variables too */
  1524. cl = config_get_commandlines(argc,argv);
  1525. retval = config_assign(newoptions,cl,0);
  1526. config_free_lines(cl);
  1527. if (retval < 0)
  1528. goto err;
  1529. /* Validate newoptions */
  1530. if (options_validate(newoptions) < 0)
  1531. goto err;
  1532. if (options_transition_allowed(oldoptions, newoptions) < 0)
  1533. goto err;
  1534. set_options(newoptions); /* frees and replaces old options */
  1535. if (options_act() < 0) { /* acting on them failed. die. */
  1536. log_fn(LOG_ERR,"Acting on config options left us in a broken state. Dying.");
  1537. exit(1);
  1538. }
  1539. tor_free(config_fname);
  1540. config_fname = fname;
  1541. return 0;
  1542. err:
  1543. tor_free(fname);
  1544. options_free(newoptions);
  1545. return -1;
  1546. }
  1547. /** If <b>range</b> is of the form MIN-MAX, for MIN and MAX both
  1548. * recognized log severity levels, set *<b>min_out</b> to MIN and
  1549. * *<b>max_out</b> to MAX and return 0. Else, if <b>range<b> is of
  1550. * the form MIN, act as if MIN-err had been specified. Else, warn and
  1551. * return -1.
  1552. */
  1553. static int
  1554. parse_log_severity_range(const char *range, int *min_out, int *max_out)
  1555. {
  1556. int levelMin, levelMax;
  1557. const char *cp;
  1558. cp = strchr(range, '-');
  1559. if (cp) {
  1560. if (cp == range) {
  1561. levelMin = LOG_DEBUG;
  1562. } else {
  1563. char *tmp_sev = tor_strndup(range, cp - range);
  1564. levelMin = parse_log_level(tmp_sev);
  1565. if (levelMin < 0) {
  1566. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  1567. "err|warn|notice|info|debug", tmp_sev);
  1568. tor_free(tmp_sev);
  1569. return -1;
  1570. }
  1571. tor_free(tmp_sev);
  1572. }
  1573. if (!*(cp+1)) {
  1574. levelMax = LOG_ERR;
  1575. } else {
  1576. levelMax = parse_log_level(cp+1);
  1577. if (levelMax < 0) {
  1578. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  1579. "err|warn|notice|info|debug", cp+1);
  1580. return -1;
  1581. }
  1582. }
  1583. } else {
  1584. levelMin = parse_log_level(range);
  1585. if (levelMin < 0) {
  1586. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  1587. "err|warn|notice|info|debug", range);
  1588. return -1;
  1589. }
  1590. levelMax = LOG_ERR;
  1591. }
  1592. *min_out = levelMin;
  1593. *max_out = levelMax;
  1594. return 0;
  1595. }
  1596. /** Try to convert a pair of old-style logging options [LogLevel, and
  1597. * (LogFile/Syslog)] to a new-style option, and add the new option to
  1598. * options->Logs. */
  1599. static int
  1600. convert_log_option(or_options_t *options, struct config_line_t *level_opt,
  1601. struct config_line_t *file_opt, int isDaemon)
  1602. {
  1603. int levelMin = -1, levelMax = -1;
  1604. if (level_opt) {
  1605. if (parse_log_severity_range(level_opt->value, &levelMin, &levelMax))
  1606. return -1;
  1607. }
  1608. if (levelMin < 0 && levelMax < 0) {
  1609. levelMin = LOG_NOTICE;
  1610. levelMax = LOG_ERR;
  1611. } else if (levelMin < 0) {
  1612. levelMin = levelMax;
  1613. } else {
  1614. levelMax = LOG_ERR;
  1615. }
  1616. if (file_opt && !strcasecmp(file_opt->key, "LogFile")) {
  1617. if (add_single_log_option(options, levelMin, levelMax, "file", file_opt->value) < 0) {
  1618. log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", file_opt->value,
  1619. strerror(errno));
  1620. return -1;
  1621. }
  1622. } else if (file_opt && !strcasecmp(file_opt->key, "SysLog")) {
  1623. if (add_single_log_option(options, levelMin, levelMax, "syslog", NULL) < 0)
  1624. return -1;
  1625. } else if (!isDaemon) {
  1626. add_single_log_option(options, levelMin, levelMax, "stdout", NULL);
  1627. }
  1628. return 0;
  1629. }
  1630. /**
  1631. * Initialize the logs based on the configuration file.
  1632. */
  1633. int
  1634. config_init_logs(or_options_t *options, int validate_only)
  1635. {
  1636. struct config_line_t *opt;
  1637. int ok;
  1638. smartlist_t *elts;
  1639. ok = 1;
  1640. elts = smartlist_create();
  1641. for (opt = options->Logs; opt; opt = opt->next) {
  1642. int levelMin=LOG_DEBUG, levelMax=LOG_ERR;
  1643. smartlist_split_string(elts, opt->value, NULL,
  1644. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  1645. if (smartlist_len(elts) == 0) {
  1646. log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
  1647. ok = 0; goto cleanup;
  1648. }
  1649. if (parse_log_severity_range(smartlist_get(elts,0), &levelMin, &levelMax)) {
  1650. ok = 0; goto cleanup;
  1651. }
  1652. if (smartlist_len(elts) < 2) { /* only loglevels were provided */
  1653. if (!validate_only)
  1654. add_stream_log(levelMin, levelMax, "<stdout>", stdout);
  1655. goto cleanup;
  1656. }
  1657. if (!strcasecmp(smartlist_get(elts,1), "file")) {
  1658. if (smartlist_len(elts) != 3) {
  1659. log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
  1660. ok = 0; goto cleanup;
  1661. }
  1662. if (!validate_only)
  1663. add_file_log(levelMin, levelMax, smartlist_get(elts, 2));
  1664. goto cleanup;
  1665. }
  1666. if (smartlist_len(elts) != 2) {
  1667. log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
  1668. ok = 0; goto cleanup;
  1669. }
  1670. if (!strcasecmp(smartlist_get(elts,1), "stdout")) {
  1671. if (!validate_only) {
  1672. add_stream_log(levelMin, levelMax, "<stdout>", stdout);
  1673. close_temp_logs();
  1674. }
  1675. } else if (!strcasecmp(smartlist_get(elts,1), "stderr")) {
  1676. if (!validate_only) {
  1677. add_stream_log(levelMin, levelMax, "<stderr>", stderr);
  1678. close_temp_logs();
  1679. }
  1680. } else if (!strcasecmp(smartlist_get(elts,1), "syslog")) {
  1681. #ifdef HAVE_SYSLOG_H
  1682. if (!validate_only)
  1683. add_syslog_log(levelMin, levelMax);
  1684. #else
  1685. log_fn(LOG_WARN, "Syslog is not supported in this compilation.");
  1686. #endif
  1687. } else {
  1688. log_fn(LOG_WARN, "Unrecognized log type %s",
  1689. (const char*)smartlist_get(elts,1));
  1690. if (strchr(smartlist_get(elts,1), '/')) {
  1691. log_fn(LOG_WARN, "Did you mean to say 'Log file %s' ?",
  1692. (const char *)smartlist_get(elts,1));
  1693. }
  1694. ok = 0; goto cleanup;
  1695. }
  1696. cleanup:
  1697. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  1698. smartlist_clear(elts);
  1699. }
  1700. smartlist_free(elts);
  1701. if (!validate_only)
  1702. close_temp_logs();
  1703. return ok?0:-1;
  1704. }
  1705. /** Add a single option of the form Log min-max <type> [fname] to options. */
  1706. static int
  1707. add_single_log_option(or_options_t *options, int minSeverity, int maxSeverity,
  1708. const char *type, const char *fname)
  1709. {
  1710. char buf[512];
  1711. int n;
  1712. n = tor_snprintf(buf, sizeof(buf), "%s%s%s %s%s%s",
  1713. log_level_to_string(minSeverity),
  1714. maxSeverity == LOG_ERR ? "" : "-",
  1715. maxSeverity == LOG_ERR ? "" : log_level_to_string(maxSeverity),
  1716. type, fname?" ":"", fname?fname:"");
  1717. if (n<0) {
  1718. log_fn(LOG_WARN, "Normalized log option too long.");
  1719. return -1;
  1720. }
  1721. log(LOG_WARN, "The old LogLevel/LogFile/DebugLogFile/SysLog options are deprecated, and will go away soon. Your new torrc line should be: 'Log %s'", buf);
  1722. options->Logs = config_line_prepend(options->Logs, "Log", buf);
  1723. return 0;
  1724. }
  1725. /** Convert all old-style logging options to new-style Log options. Return 0
  1726. * on success, -1 on failure. */
  1727. static int
  1728. normalize_log_options(or_options_t *options)
  1729. {
  1730. /* The order of options is: Level? (File Level?)+
  1731. */
  1732. struct config_line_t *opt = options->OldLogOptions;
  1733. /* Special case for if first option is LogLevel. */
  1734. if (opt && !strcasecmp(opt->key, "LogLevel")) {
  1735. if (opt->next && (!strcasecmp(opt->next->key, "LogFile") ||
  1736. !strcasecmp(opt->next->key, "SysLog"))) {
  1737. if (convert_log_option(options, opt, opt->next, options->RunAsDaemon) < 0)
  1738. return -1;
  1739. opt = opt->next->next;
  1740. } else if (!opt->next) {
  1741. if (convert_log_option(options, opt, NULL, options->RunAsDaemon) < 0)
  1742. return -1;
  1743. opt = opt->next;
  1744. } else {
  1745. ; /* give warning below */
  1746. }
  1747. }
  1748. while (opt) {
  1749. if (!strcasecmp(opt->key, "LogLevel")) {
  1750. log_fn(LOG_WARN, "Two LogLevel options in a row without intervening LogFile or SysLog");
  1751. opt = opt->next;
  1752. } else {
  1753. tor_assert(!strcasecmp(opt->key, "LogFile") ||
  1754. !strcasecmp(opt->key, "SysLog"));
  1755. if (opt->next && !strcasecmp(opt->next->key, "LogLevel")) {
  1756. /* LogFile/SysLog followed by LogLevel */
  1757. if (convert_log_option(options,opt->next,opt, options->RunAsDaemon) < 0)
  1758. return -1;
  1759. opt = opt->next->next;
  1760. } else {
  1761. /* LogFile/SysLog followed by LogFile/SysLog or end of list. */
  1762. if (convert_log_option(options,NULL, opt, options->RunAsDaemon) < 0)
  1763. return -1;
  1764. opt = opt->next;
  1765. }
  1766. }
  1767. }
  1768. if (options->DebugLogFile) {
  1769. if (add_single_log_option(options, LOG_DEBUG, LOG_ERR, "file", options->DebugLogFile) < 0)
  1770. return -1;
  1771. }
  1772. tor_free(options->DebugLogFile);
  1773. config_free_lines(options->OldLogOptions);
  1774. options->OldLogOptions = NULL;
  1775. return 0;
  1776. }
  1777. /**
  1778. * Given a linked list of config lines containing "allow" and "deny" tokens,
  1779. * parse them and append the result to <b>dest</b>. Return -1 if any tokens
  1780. * are malformed, else return 0.
  1781. */
  1782. int
  1783. config_parse_addr_policy(struct config_line_t *cfg,
  1784. addr_policy_t **dest)
  1785. {
  1786. addr_policy_t **nextp;
  1787. smartlist_t *entries;
  1788. int r = 0;
  1789. if (!cfg)
  1790. return 0;
  1791. nextp = dest;
  1792. while (*nextp)
  1793. nextp = &((*nextp)->next);
  1794. entries = smartlist_create();
  1795. for (; cfg; cfg = cfg->next) {
  1796. smartlist_split_string(entries, cfg->value, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1797. SMARTLIST_FOREACH(entries, const char *, ent,
  1798. {
  1799. log_fn(LOG_DEBUG,"Adding new entry '%s'",ent);
  1800. *nextp = router_parse_addr_policy_from_string(ent);
  1801. if (*nextp) {
  1802. nextp = &((*nextp)->next);
  1803. } else {
  1804. log_fn(LOG_WARN,"Malformed policy %s.", ent);
  1805. r = -1;
  1806. }
  1807. });
  1808. SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
  1809. smartlist_clear(entries);
  1810. }
  1811. smartlist_free(entries);
  1812. return r;
  1813. }
  1814. /** Release all storage held by <b>p</b> */
  1815. void
  1816. addr_policy_free(addr_policy_t *p) {
  1817. addr_policy_t *e;
  1818. while (p) {
  1819. e = p;
  1820. p = p->next;
  1821. tor_free(e->string);
  1822. tor_free(e);
  1823. }
  1824. }
  1825. /** Parse a single RedirectExit line's contents from <b>line</b>. If
  1826. * they are valid, and <b>result</b> is not NULL, add an element to
  1827. * <b>result</b> and return 0. Else if they are valid, return 0.
  1828. * Else return -1. */
  1829. static int
  1830. parse_redirect_line(smartlist_t *result, struct config_line_t *line)
  1831. {
  1832. smartlist_t *elements = NULL;
  1833. exit_redirect_t *r;
  1834. tor_assert(line);
  1835. r = tor_malloc_zero(sizeof(exit_redirect_t));
  1836. elements = smartlist_create();
  1837. smartlist_split_string(elements, line->value, NULL,
  1838. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1839. if (smartlist_len(elements) != 2) {
  1840. log_fn(LOG_WARN, "Wrong number of elements in RedirectExit line");
  1841. goto err;
  1842. }
  1843. if (parse_addr_and_port_range(smartlist_get(elements,0),&r->addr,&r->mask,
  1844. &r->port_min,&r->port_max)) {
  1845. log_fn(LOG_WARN, "Error parsing source address in RedirectExit line");
  1846. goto err;
  1847. }
  1848. if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
  1849. r->is_redirect = 0;
  1850. } else {
  1851. if (parse_addr_port(smartlist_get(elements,1),NULL,&r->addr_dest,
  1852. &r->port_dest)) {
  1853. log_fn(LOG_WARN, "Error parsing dest address in RedirectExit line");
  1854. goto err;
  1855. }
  1856. r->is_redirect = 1;
  1857. }
  1858. goto done;
  1859. err:
  1860. tor_free(r);
  1861. done:
  1862. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  1863. smartlist_free(elements);
  1864. if (r) {
  1865. if (result)
  1866. smartlist_add(result, r);
  1867. else
  1868. tor_free(r);
  1869. return 0;
  1870. } else {
  1871. return -1;
  1872. }
  1873. }
  1874. /** Read the contents of a DirServer line from <b>line</b>. Return 0
  1875. * if the line is well-formed, and 0 if it isn't. If
  1876. * <b>validate_only</b> is 0, and the line is well-formed, then add
  1877. * the dirserver described in the line as a valid server. */
  1878. static int
  1879. parse_dir_server_line(const char *line, int validate_only)
  1880. {
  1881. smartlist_t *items = NULL;
  1882. int r;
  1883. char *addrport, *address=NULL;
  1884. uint16_t port;
  1885. char digest[DIGEST_LEN];
  1886. items = smartlist_create();
  1887. smartlist_split_string(items, line, NULL,
  1888. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  1889. if (smartlist_len(items) < 2) {
  1890. log_fn(LOG_WARN, "Too few arguments to DirServer line.");
  1891. goto err;
  1892. }
  1893. addrport = smartlist_get(items, 0);
  1894. if (parse_addr_port(addrport, &address, NULL, &port)<0) {
  1895. log_fn(LOG_WARN, "Error parsing DirServer address '%s'", addrport);
  1896. goto err;
  1897. }
  1898. if (!port) {
  1899. log_fn(LOG_WARN, "Missing port in DirServer address '%s'",addrport);
  1900. goto err;
  1901. }
  1902. tor_strstrip(smartlist_get(items, 1), " ");
  1903. if (strlen(smartlist_get(items, 1)) != HEX_DIGEST_LEN) {
  1904. log_fn(LOG_WARN, "Key digest for DirServer is wrong length.");
  1905. goto err;
  1906. }
  1907. if (base16_decode(digest, DIGEST_LEN,
  1908. smartlist_get(items,1), HEX_DIGEST_LEN)<0) {
  1909. log_fn(LOG_WARN, "Unable to decode DirServer key digest.");
  1910. goto err;
  1911. }
  1912. if (!validate_only) {
  1913. log_fn(LOG_DEBUG, "Trusted dirserver at %s:%d (%s)", address, (int)port,
  1914. (char*)smartlist_get(items,1));
  1915. add_trusted_dir_server(address, port, digest);
  1916. }
  1917. r = 0;
  1918. goto done;
  1919. err:
  1920. r = -1;
  1921. done:
  1922. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  1923. smartlist_free(items);
  1924. tor_free(address);
  1925. return r;
  1926. }
  1927. /** Adjust the value of options->DataDirectory, or fill it in if it's
  1928. * absent. Return 0 on success, -1 on failure. */
  1929. static int
  1930. normalize_data_directory(or_options_t *options) {
  1931. #ifdef MS_WINDOWS
  1932. char *p;
  1933. if (options->DataDirectory)
  1934. return 0; /* all set */
  1935. p = tor_malloc(MAX_PATH);
  1936. strlcpy(p,get_windows_conf_root(),MAX_PATH);
  1937. options->DataDirectory = p;
  1938. return 0;
  1939. #else
  1940. const char *d = options->DataDirectory;
  1941. if (!d)
  1942. d = "~/.tor";
  1943. if (strncmp(d,"~/",2) == 0) {
  1944. char *fn = expand_filename(d);
  1945. if (!fn) {
  1946. log_fn(LOG_ERR,"Failed to expand filename '%s'.", d);
  1947. return -1;
  1948. }
  1949. if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
  1950. /* If our homedir is /, we probably don't want to use it. */
  1951. /* XXXX Default to /var/lib/tor? */
  1952. log_fn(LOG_WARN, "Defaulting to 'DataDirectory %s', which may not be what you want", fn);
  1953. }
  1954. tor_free(options->DataDirectory);
  1955. options->DataDirectory = fn;
  1956. }
  1957. return 0;
  1958. #endif
  1959. }
  1960. /** Check and normalize the value of options->DataDirectory; return 0 if it
  1961. * sane, -1 otherwise. */
  1962. static int
  1963. validate_data_directory(or_options_t *options) {
  1964. if (normalize_data_directory(options) < 0)
  1965. return -1;
  1966. tor_assert(options->DataDirectory);
  1967. if (strlen(options->DataDirectory) > (512-128)) {
  1968. log_fn(LOG_ERR, "DataDirectory is too long.");
  1969. return -1;
  1970. }
  1971. #if 0
  1972. if (check_private_dir(options->DataDirectory, CPD_CHECK != 0)) {
  1973. log_fn(LOG_WARN, "Can't create directory %s", options->DataDirectory);
  1974. return -1;
  1975. }
  1976. #endif
  1977. return 0;
  1978. }
  1979. #define GENERATED_FILE_PREFIX "# This file was generated by Tor; if you edit it, comments will not be preserved"
  1980. /** Save a configuration file for the configuration in <b>options</b>
  1981. * into the file <b>fname</b>. If the file already exists, and
  1982. * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
  1983. * replace it. Return 0 on success, -1 on failure. */
  1984. static int
  1985. write_configuration_file(const char *fname, or_options_t *options)
  1986. {
  1987. char fn_tmp[1024];
  1988. char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
  1989. int rename_old = 0, r;
  1990. size_t len;
  1991. if (fname) {
  1992. switch (file_status(fname)) {
  1993. case FN_FILE:
  1994. old_val = read_file_to_str(fname, 0);
  1995. if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
  1996. rename_old = 1;
  1997. }
  1998. tor_free(old_val);
  1999. break;
  2000. case FN_NOENT:
  2001. break;
  2002. default:
  2003. log_fn(LOG_WARN,"Config file %s is not a file? Failing.", fname);
  2004. return -1;
  2005. }
  2006. }
  2007. if (!(new_conf = config_dump_options(options, 1))) {
  2008. log_fn(LOG_WARN, "Couldn't get configuration string");
  2009. goto err;
  2010. }
  2011. len = strlen(new_conf)+128;
  2012. new_val = tor_malloc(len);
  2013. tor_snprintf(new_val, len, "%s\n\n%s", GENERATED_FILE_PREFIX, new_conf);
  2014. if (rename_old) {
  2015. int i = 1;
  2016. while (1) {
  2017. if (tor_snprintf(fn_tmp, sizeof(fn_tmp), "%s.orig.%d", fname, i)<0) {
  2018. log_fn(LOG_WARN, "Filename too long");
  2019. goto err;
  2020. }
  2021. if (file_status(fn_tmp) == FN_NOENT)
  2022. break;
  2023. ++i;
  2024. }
  2025. log_fn(LOG_NOTICE, "Renaming old configuration file to %s", fn_tmp);
  2026. rename(fname, fn_tmp);
  2027. }
  2028. write_str_to_file(fname, new_val, 0);
  2029. r = 0;
  2030. goto done;
  2031. err:
  2032. r = -1;
  2033. done:
  2034. tor_free(new_val);
  2035. tor_free(new_conf);
  2036. return r;
  2037. }
  2038. /**
  2039. * Save the current configuration file value to disk. Return 0 on
  2040. * success, -1 on failure.
  2041. **/
  2042. int
  2043. save_current_config(void)
  2044. {
  2045. char *fn;
  2046. if (config_fname) {
  2047. /* XXX This fails if we can't write to our configuration file.
  2048. * Arguably, we should try falling back to datadirectory or something.
  2049. * But just as arguably, we shouldn't. */
  2050. return write_configuration_file(config_fname, get_options());
  2051. }
  2052. fn = get_default_conf_file();
  2053. return write_configuration_file(fn, get_options());
  2054. }
  2055. struct unit_table_t {
  2056. const char *unit;
  2057. uint64_t multiplier;
  2058. };
  2059. static struct unit_table_t memory_units[] = {
  2060. { "", 1 },
  2061. { "b", 1<< 0 },
  2062. { "byte", 1<< 0 },
  2063. { "bytes", 1<< 0 },
  2064. { "kb", 1<<10 },
  2065. { "kilobyte", 1<<10 },
  2066. { "kilobytes", 1<<10 },
  2067. { "m", 1<<20 },
  2068. { "mb", 1<<20 },
  2069. { "megabyte", 1<<20 },
  2070. { "megabytes", 1<<20 },
  2071. { "gb", 1<<30 },
  2072. { "gigabyte", 1<<30 },
  2073. { "gigabytes", 1<<30 },
  2074. { "tb", U64_LITERAL(1)<<40 },
  2075. { "terabyte", U64_LITERAL(1)<<40 },
  2076. { "terabytes", U64_LITERAL(1)<<40 },
  2077. { NULL, 0 },
  2078. };
  2079. static struct unit_table_t time_units[] = {
  2080. { "", 1 },
  2081. { "second", 1 },
  2082. { "seconds", 1 },
  2083. { "minute", 60 },
  2084. { "minutes", 60 },
  2085. { "hour", 60*60 },
  2086. { "hours", 60*60 },
  2087. { "day", 24*60*60 },
  2088. { "days", 24*60*60 },
  2089. { "week", 7*24*60*60 },
  2090. { "weeks", 7*24*60*60 },
  2091. { NULL, 0 },
  2092. };
  2093. /** Parse a string <b>val</b> containing a number, zero or more
  2094. * spaces, and an optional unit string. If the unit appears in the
  2095. * table <b>u</b>, then multiply the number by the unit multiplier.
  2096. * On success, set *<b>ok</b> to 1 and return this product.
  2097. * Otherwise, set *<b>ok</b> to 0.
  2098. */
  2099. static uint64_t
  2100. config_parse_units(const char *val, struct unit_table_t *u, int *ok)
  2101. {
  2102. uint64_t v;
  2103. char *cp;
  2104. tor_assert(ok);
  2105. v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
  2106. if (!*ok)
  2107. return 0;
  2108. if (!cp) {
  2109. *ok = 1;
  2110. return v;
  2111. }
  2112. while (TOR_ISSPACE(*cp))
  2113. ++cp;
  2114. for ( ;u->unit;++u) {
  2115. if (!strcasecmp(u->unit, cp)) {
  2116. v *= u->multiplier;
  2117. *ok = 1;
  2118. return v;
  2119. }
  2120. }
  2121. log_fn(LOG_WARN, "Unknown unit '%s'.", cp);
  2122. *ok = 0;
  2123. return 0;
  2124. }
  2125. /** Parse a string in the format "number unit", where unit is a unit of
  2126. * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
  2127. * and return the number of bytes specified. Otherwise, set
  2128. * *<b>ok</b> to false and return 0. */
  2129. static uint64_t
  2130. config_parse_memunit(const char *s, int *ok) {
  2131. return config_parse_units(s, memory_units, ok);
  2132. }
  2133. /** Parse a string in the format "number unit", where unit is a unit of time.
  2134. * On success, set *<b>ok</b> to true and return the number of seconds in
  2135. * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
  2136. */
  2137. static int
  2138. config_parse_interval(const char *s, int *ok) {
  2139. uint64_t r;
  2140. r = config_parse_units(s, time_units, ok);
  2141. if (!ok)
  2142. return -1;
  2143. if (r > INT_MAX) {
  2144. log_fn(LOG_WARN, "Interval '%s' is too long", s);
  2145. *ok = 0;
  2146. return -1;
  2147. }
  2148. return (int)r;
  2149. }
  2150. static void
  2151. print_cvs_version(void)
  2152. {
  2153. extern const char aes_c_id[];
  2154. extern const char compat_c_id[];
  2155. extern const char container_c_id[];
  2156. extern const char crypto_c_id[];
  2157. extern const char fakepoll_c_id[];
  2158. extern const char log_c_id[];
  2159. extern const char torgzip_c_id[];
  2160. extern const char tortls_c_id[];
  2161. extern const char util_c_id[];
  2162. extern const char buffers_c_id[];
  2163. extern const char circuitbuild_c_id[];
  2164. extern const char circuitlist_c_id[];
  2165. extern const char circuituse_c_id[];
  2166. extern const char command_c_id[];
  2167. // extern const char config_c_id[];
  2168. extern const char connection_c_id[];
  2169. extern const char connection_edge_c_id[];
  2170. extern const char connection_or_c_id[];
  2171. extern const char control_c_id[];
  2172. extern const char cpuworker_c_id[];
  2173. extern const char directory_c_id[];
  2174. extern const char dirserv_c_id[];
  2175. extern const char dns_c_id[];
  2176. extern const char hibernate_c_id[];
  2177. extern const char main_c_id[];
  2178. extern const char onion_c_id[];
  2179. extern const char relay_c_id[];
  2180. extern const char rendclient_c_id[];
  2181. extern const char rendcommon_c_id[];
  2182. extern const char rendmid_c_id[];
  2183. extern const char rendservice_c_id[];
  2184. extern const char rephist_c_id[];
  2185. extern const char router_c_id[];
  2186. extern const char routerlist_c_id[];
  2187. extern const char routerparse_c_id[];
  2188. puts(AES_H_ID);
  2189. puts(COMPAT_H_ID);
  2190. puts(CONTAINER_H_ID);
  2191. puts(CRYPTO_H_ID);
  2192. puts(FAKEPOLL_H_ID);
  2193. puts(LOG_H_ID);
  2194. puts(TORGZIP_H_ID);
  2195. puts(TORINT_H_ID);
  2196. puts(TORTLS_H_ID);
  2197. puts(UTIL_H_ID);
  2198. puts(aes_c_id);
  2199. puts(compat_c_id);
  2200. puts(container_c_id);
  2201. puts(crypto_c_id);
  2202. puts(fakepoll_c_id);
  2203. puts(log_c_id);
  2204. puts(torgzip_c_id);
  2205. puts(tortls_c_id);
  2206. puts(util_c_id);
  2207. puts(OR_H_ID);
  2208. puts(buffers_c_id);
  2209. puts(circuitbuild_c_id);
  2210. puts(circuitlist_c_id);
  2211. puts(circuituse_c_id);
  2212. puts(command_c_id);
  2213. puts(config_c_id);
  2214. puts(connection_c_id);
  2215. puts(connection_edge_c_id);
  2216. puts(connection_or_c_id);
  2217. puts(control_c_id);
  2218. puts(cpuworker_c_id);
  2219. puts(directory_c_id);
  2220. puts(dirserv_c_id);
  2221. puts(dns_c_id);
  2222. puts(hibernate_c_id);
  2223. puts(main_c_id);
  2224. puts(onion_c_id);
  2225. puts(relay_c_id);
  2226. puts(rendclient_c_id);
  2227. puts(rendcommon_c_id);
  2228. puts(rendmid_c_id);
  2229. puts(rendservice_c_id);
  2230. puts(rephist_c_id);
  2231. puts(router_c_id);
  2232. puts(routerlist_c_id);
  2233. puts(routerparse_c_id);
  2234. }