config.c 57 KB

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