config.c 57 KB

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