config.c 56 KB

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