config.c 70 KB

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