config.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * /file config.c
  6. *
  7. * /brief Code to parse and interpret configuration files.
  8. *
  9. **/
  10. #include "or.h"
  11. #ifdef MS_WINDOWS
  12. #include <shlobj.h>
  13. #endif
  14. /** Enumeration of types which option values can take */
  15. typedef enum config_type_t {
  16. CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
  17. CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
  18. CONFIG_TYPE_DOUBLE, /**< A floating-point value */
  19. CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
  20. CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and optional
  21. * whitespace. */
  22. CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
  23. CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
  24. * mixed with other keywords. */
  25. CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
  26. * context-sensitive config lines when fetching.
  27. */
  28. CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
  29. } config_type_t;
  30. /* An abbreviation for a configuration option allowed on the command line */
  31. typedef struct config_abbrev_t {
  32. const char *abbreviated;
  33. const char *full;
  34. int commandline_only;
  35. } config_abbrev_t;
  36. /* Handy macro for declaring "In the config file or on the command line,
  37. * you can abbreviate <b>tok</b>s as <b>tok</b>". */
  38. #define PLURAL(tok) { #tok, #tok "s", 0 }
  39. /* A list of command-line abbreviations. */
  40. static config_abbrev_t config_abbrevs[] = {
  41. PLURAL(ExitNode),
  42. PLURAL(EntryNodes),
  43. PLURAL(ExcludeNode),
  44. PLURAL(FirewallPort),
  45. PLURAL(HiddenServiceNode),
  46. PLURAL(HiddenServiceExcludeNode),
  47. PLURAL(RendNode),
  48. PLURAL(RendExcludeNode),
  49. { "l", "LogLevel", 1},
  50. { "BandwidthRate", "BandwidthRateBytes", 1},
  51. { "BandwidthBurst", "BandwidthBurstBytes", 1},
  52. { NULL, NULL , 0},
  53. };
  54. #undef PLURAL
  55. /** A variable allowed in the configuration file or on the command line. */
  56. typedef struct config_var_t {
  57. const char *name; /**< The full keyword (case insensitive). */
  58. config_type_t type; /**< How to interpret the type and turn it into a value. */
  59. off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
  60. const char *initvalue; /**< String (or null) describing initial value. */
  61. } config_var_t;
  62. /** Return the offset of <b>member</b> within the type <b>tp</b>, in bytes */
  63. #define STRUCT_OFFSET(tp, member) ((off_t) (((char*)&((tp*)0)->member)-(char*)0))
  64. /** An entry for config_vars: "The option <b>name</b> has type
  65. * CONFIG_TYPE_<b>conftype</b>, and corresponds to
  66. * or_options_t.<b>member</b>"
  67. */
  68. #define VAR(name,conftype,member,initvalue) \
  69. { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), initvalue }
  70. /** An entry for config_vars: "The option <b>name</b> is obsolete." */
  71. #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
  72. /** Array of configuration options. Until we disallow nonstandard
  73. * abbreviations, order is significant, since the first matching option will
  74. * be chosen first.
  75. */
  76. static config_var_t config_vars[] = {
  77. VAR("Address", STRING, Address, NULL),
  78. VAR("AllowUnverifiedNodes",CSV, AllowUnverifiedNodes, "middle,rendezvous"),
  79. VAR("AuthoritativeDirectory",BOOL, AuthoritativeDir, "0"),
  80. VAR("BandwidthRateBytes", UINT, BandwidthRateBytes, "800000"),
  81. VAR("BandwidthBurstBytes", UINT, BandwidthBurstBytes, "50000000"),
  82. VAR("ClientOnly", BOOL, ClientOnly, "0"),
  83. VAR("ContactInfo", STRING, ContactInfo, NULL),
  84. VAR("ControlPort", UINT, ControlPort, "0"),
  85. VAR("DebugLogFile", STRING, DebugLogFile, NULL),
  86. VAR("DataDirectory", STRING, DataDirectory, NULL),
  87. VAR("DirPort", UINT, DirPort, "0"),
  88. VAR("DirBindAddress", LINELIST, DirBindAddress, NULL),
  89. VAR("DirFetchPostPeriod", UINT, DirFetchPostPeriod, "600"),
  90. VAR("DirPolicy", LINELIST, DirPolicy, NULL),
  91. VAR("DirServer", LINELIST, DirServers, NULL),
  92. VAR("ExitNodes", STRING, ExitNodes, NULL),
  93. VAR("EntryNodes", STRING, EntryNodes, NULL),
  94. VAR("StrictExitNodes", BOOL, StrictExitNodes, "0"),
  95. VAR("StrictEntryNodes", BOOL, StrictEntryNodes, "0"),
  96. VAR("ExitPolicy", LINELIST, ExitPolicy, NULL),
  97. VAR("ExcludeNodes", STRING, ExcludeNodes, NULL),
  98. VAR("FascistFirewall", BOOL, FascistFirewall, "0"),
  99. VAR("FirewallPorts", CSV, FirewallPorts, "80,443"),
  100. VAR("MyFamily", STRING, MyFamily, NULL),
  101. VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
  102. VAR("Group", STRING, Group, NULL),
  103. VAR("HashedControlPassword",STRING, HashedControlPassword, NULL),
  104. VAR("HttpProxy", STRING, HttpProxy, NULL),
  105. VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
  106. VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
  107. VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
  108. VAR("HiddenServiceNodes", LINELIST_S, RendConfigLines, NULL),
  109. VAR("HiddenServiceExcludeNodes", LINELIST_S, RendConfigLines, NULL),
  110. VAR("IgnoreVersion", BOOL, IgnoreVersion, "0"),
  111. VAR("KeepalivePeriod", UINT, KeepalivePeriod, "300"),
  112. VAR("LogOptions", LINELIST_V, LogOptions, NULL),
  113. VAR("LogLevel", LINELIST_S, LogOptions, NULL),
  114. VAR("LogFile", LINELIST_S, LogOptions, NULL),
  115. OBSOLETE("LinkPadding"),
  116. VAR("MaxConn", UINT, MaxConn, "1024"),
  117. VAR("MaxOnionsPending", UINT, MaxOnionsPending, "100"),
  118. VAR("MonthlyAccountingStart",UINT, AccountingStart, "0"),
  119. VAR("AccountingMaxKB", UINT, AccountingMaxKB, "0"),
  120. VAR("Nickname", STRING, Nickname, NULL),
  121. VAR("NewCircuitPeriod", UINT, NewCircuitPeriod, "30"),
  122. VAR("NumCpus", UINT, NumCpus, "1"),
  123. VAR("ORPort", UINT, ORPort, "0"),
  124. VAR("ORBindAddress", LINELIST, ORBindAddress, NULL),
  125. VAR("OutboundBindAddress", STRING, OutboundBindAddress, NULL),
  126. VAR("PidFile", STRING, PidFile, NULL),
  127. VAR("PathlenCoinWeight", DOUBLE, PathlenCoinWeight, "0.3"),
  128. VAR("RedirectExit", LINELIST, RedirectExit, NULL),
  129. OBSOLETE("RouterFile"),
  130. VAR("RunAsDaemon", BOOL, RunAsDaemon, "0"),
  131. VAR("RunTesting", BOOL, RunTesting, "0"),
  132. VAR("RecommendedVersions", LINELIST, RecommendedVersions, NULL),
  133. VAR("RendNodes", STRING, RendNodes, NULL),
  134. VAR("RendExcludeNodes", STRING, RendExcludeNodes, NULL),
  135. VAR("SocksPort", UINT, SocksPort, "9050"),
  136. VAR("SocksBindAddress", LINELIST, SocksBindAddress, NULL),
  137. VAR("SocksPolicy", LINELIST, SocksPolicy, NULL),
  138. VAR("SysLog", LINELIST_S, LogOptions, NULL),
  139. OBSOLETE("TrafficShaping"),
  140. VAR("User", STRING, User, NULL),
  141. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  142. };
  143. #undef VAR
  144. #undef OBSOLETE
  145. /** Largest allowed config line */
  146. #define CONFIG_LINE_T_MAXLEN 4096
  147. static struct config_line_t *config_get_commandlines(int argc, char **argv);
  148. static int config_get_lines(FILE *f, struct config_line_t **result);
  149. static void config_free_lines(struct config_line_t *front);
  150. static int config_assign_line(or_options_t *options, struct config_line_t *c,
  151. int reset);
  152. static int config_assign(or_options_t *options, struct config_line_t *list,
  153. int reset);
  154. static int parse_dir_server_line(const char *line);
  155. static int parse_redirect_line(or_options_t *options,
  156. struct config_line_t *line);
  157. static const char *expand_abbrev(const char *option, int commandline_only);
  158. static config_var_t *config_find_option(const char *key);
  159. static void reset_option(or_options_t *options, config_var_t *var);
  160. /** If <b>option</b> is an official abbreviation for a longer option,
  161. * return the longer option. Otherwise return <b>option</b>.
  162. * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
  163. * apply abbreviations that work for the config file and the command line. */
  164. static const char *
  165. expand_abbrev(const char *option, int command_line)
  166. {
  167. int i;
  168. for (i=0; config_abbrevs[i].abbreviated; ++i) {
  169. /* Abbreviations aren't casei. */
  170. if (!strcmp(option,config_abbrevs[i].abbreviated) &&
  171. (command_line || !config_abbrevs[i].commandline_only)) {
  172. return config_abbrevs[i].full;
  173. }
  174. }
  175. return option;
  176. }
  177. /** Helper: Read a list of configuration options from the command line. */
  178. static struct config_line_t *
  179. config_get_commandlines(int argc, char **argv)
  180. {
  181. struct config_line_t *new;
  182. struct config_line_t *front = NULL;
  183. char *s;
  184. int i = 1;
  185. while (i < argc-1) {
  186. if (!strcmp(argv[i],"-f") ||
  187. !strcmp(argv[i],"--hash-password")) {
  188. i += 2; /* command-line option with argument. ignore them. */
  189. continue;
  190. } else if (!strcmp(argv[i],"--list-fingerprint")) {
  191. i += 1; /* command-line option. ignore it. */
  192. continue;
  193. }
  194. new = tor_malloc(sizeof(struct config_line_t));
  195. s = argv[i];
  196. while(*s == '-')
  197. s++;
  198. new->key = tor_strdup(expand_abbrev(s, 1));
  199. new->value = tor_strdup(argv[i+1]);
  200. log(LOG_DEBUG,"Commandline: parsed keyword '%s', value '%s'",
  201. new->key, new->value);
  202. new->next = front;
  203. front = new;
  204. i += 2;
  205. }
  206. return front;
  207. }
  208. /** Helper: allocate a new configuration option mapping 'key' to 'val',
  209. * prepend it to 'front', and return the newly allocated config_line_t */
  210. struct config_line_t *
  211. config_line_prepend(struct config_line_t *front,
  212. const char *key,
  213. const char *val)
  214. {
  215. struct config_line_t *newline;
  216. newline = tor_malloc(sizeof(struct config_line_t));
  217. newline->key = tor_strdup(key);
  218. newline->value = tor_strdup(val);
  219. newline->next = front;
  220. return newline;
  221. }
  222. /** Helper: parse the config file and strdup into key/value
  223. * strings. Set *result to the list, or NULL if parsing the file
  224. * failed. Return 0 on success, -1 on failure. Warn and ignore any
  225. * misformatted lines. */
  226. static int
  227. config_get_lines(FILE *f, struct config_line_t **result)
  228. {
  229. struct config_line_t *front = NULL;
  230. char line[CONFIG_LINE_T_MAXLEN];
  231. int r;
  232. char *key, *value;
  233. while ((r = parse_line_from_file(line, sizeof(line), f, &key, &value)) > 0) {
  234. front = config_line_prepend(front, key, value);
  235. }
  236. if (r < 0) {
  237. *result = NULL;
  238. return -1;
  239. }
  240. *result = front;
  241. return 0;
  242. }
  243. /**
  244. * Free all the configuration lines on the linked list <b>front</b>.
  245. */
  246. static void
  247. config_free_lines(struct config_line_t *front)
  248. {
  249. struct config_line_t *tmp;
  250. while (front) {
  251. tmp = front;
  252. front = tmp->next;
  253. tor_free(tmp->key);
  254. tor_free(tmp->value);
  255. tor_free(tmp);
  256. }
  257. }
  258. /** If <b>key</b> is a configuration option, return the corresponding
  259. * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
  260. * warn, and return the corresponding config_var_t. Otherwise return NULL.
  261. */
  262. static config_var_t *config_find_option(const char *key)
  263. {
  264. int i;
  265. /* First, check for an exact (case-insensitive) match */
  266. for (i=0; config_vars[i].name; ++i) {
  267. if (!strcasecmp(key, config_vars[i].name))
  268. return &config_vars[i];
  269. }
  270. /* If none, check for an abbreviated match */
  271. for (i=0; config_vars[i].name; ++i) {
  272. if (!strncasecmp(key, config_vars[i].name, strlen(key))) {
  273. log_fn(LOG_WARN, "The abbreviation '%s' is deprecated. "
  274. "Tell Nick and Roger to make it official, or just use '%s' instead",
  275. key, config_vars[i].name);
  276. return &config_vars[i];
  277. }
  278. }
  279. /* Okay, unrecogized options */
  280. return NULL;
  281. }
  282. /** If <b>c</b> is a syntactically valid configuration line, update
  283. * <b>options</b> with its value and return 0. Otherwise return -1.
  284. *
  285. * If 'reset' is set, and we get a line containing no value, restore the
  286. * option to its default value.
  287. */
  288. static int
  289. config_assign_line(or_options_t *options, struct config_line_t *c, int reset)
  290. {
  291. int i, ok;
  292. config_var_t *var;
  293. void *lvalue;
  294. var = config_find_option(c->key);
  295. if (!var) {
  296. log_fn(LOG_WARN, "Unknown option '%s'. Failing.", c->key);
  297. return -1;
  298. }
  299. /* Put keyword into canonical case. */
  300. if (strcmp(var->name, c->key)) {
  301. tor_free(c->key);
  302. c->key = tor_strdup(var->name);
  303. }
  304. if (reset && !strlen(c->value)) {
  305. reset_option(options, var);
  306. return 0;
  307. }
  308. lvalue = ((char*)options) + var->var_offset;
  309. switch(var->type) {
  310. case CONFIG_TYPE_UINT:
  311. i = tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
  312. if (!ok) {
  313. log(LOG_WARN, "Int keyword '%s %s' is malformed or out of bounds. Skipping.",
  314. c->key,c->value);
  315. return 0;
  316. }
  317. *(int *)lvalue = i;
  318. break;
  319. case CONFIG_TYPE_BOOL:
  320. i = tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
  321. if (!ok) {
  322. log(LOG_WARN, "Boolean keyword '%s' expects 0 or 1. Skipping.", c->key);
  323. return 0;
  324. }
  325. *(int *)lvalue = i;
  326. break;
  327. case CONFIG_TYPE_STRING:
  328. tor_free(*(char **)lvalue);
  329. *(char **)lvalue = tor_strdup(c->value);
  330. break;
  331. case CONFIG_TYPE_DOUBLE:
  332. *(double *)lvalue = atof(c->value);
  333. break;
  334. case CONFIG_TYPE_CSV:
  335. if (*(smartlist_t**)lvalue == NULL)
  336. *(smartlist_t**)lvalue = smartlist_create();
  337. smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
  338. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  339. break;
  340. case CONFIG_TYPE_LINELIST:
  341. case CONFIG_TYPE_LINELIST_S:
  342. /* Note: this reverses the order that the lines appear in. That's
  343. * just fine, since we build up the list of lines reversed in the
  344. * first place. */
  345. *(struct config_line_t**)lvalue =
  346. config_line_prepend(*(struct config_line_t**)lvalue, c->key, c->value);
  347. break;
  348. case CONFIG_TYPE_OBSOLETE:
  349. log_fn(LOG_WARN, "Skipping obsolete configuration option '%s'", c->key);
  350. break;
  351. case CONFIG_TYPE_LINELIST_V:
  352. log_fn(LOG_WARN, "Can't provide value for virtual option '%s'", c->key);
  353. return -1;
  354. default:
  355. tor_assert(0);
  356. break;
  357. }
  358. return 0;
  359. }
  360. /** restore the option named <b>key</b> in options to its default value. */
  361. static void
  362. config_reset_line(or_options_t *options, const char *key)
  363. {
  364. config_var_t *var;
  365. var = config_find_option(key);
  366. if (!var)
  367. return; /* give error on next pass. */
  368. reset_option(options, var);
  369. }
  370. /** Return a canonicalized list of the options assigned for key.
  371. */
  372. struct config_line_t *
  373. config_get_assigned_option(or_options_t *options, const char *key)
  374. {
  375. config_var_t *var;
  376. const void *value;
  377. char buf[32];
  378. struct config_line_t *result;
  379. var = config_find_option(key);
  380. if (!var) {
  381. log_fn(LOG_WARN, "Unknown option '%s'. Failing.", key);
  382. return NULL;
  383. } else if (var->type == CONFIG_TYPE_LINELIST_S) {
  384. log_fn(LOG_WARN, "Can't return context-sensitive '%s' on its own", key);
  385. return NULL;
  386. }
  387. value = ((char*)options) + var->var_offset;
  388. if (var->type == CONFIG_TYPE_LINELIST ||
  389. var->type == CONFIG_TYPE_LINELIST_V) {
  390. /* Linelist requires special handling: we just copy and return it. */
  391. const struct config_line_t *next_in = value;
  392. struct config_line_t **next_out = &result;
  393. while (next_in) {
  394. *next_out = tor_malloc(sizeof(struct config_line_t));
  395. (*next_out)->key = tor_strdup(next_in->key);
  396. (*next_out)->value = tor_strdup(next_in->value);
  397. next_in = next_in->next;
  398. next_out = &((*next_out)->next);
  399. }
  400. (*next_out) = NULL;
  401. return result;
  402. }
  403. result = tor_malloc_zero(sizeof(struct config_line_t));
  404. result->key = tor_strdup(var->name);
  405. switch(var->type)
  406. {
  407. case CONFIG_TYPE_STRING:
  408. result->value = tor_strdup(value ? (char*)value : "");
  409. break;
  410. case CONFIG_TYPE_UINT:
  411. tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
  412. result->value = tor_strdup(buf);
  413. break;
  414. case CONFIG_TYPE_DOUBLE:
  415. tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
  416. result->value = tor_strdup(buf);
  417. break;
  418. case CONFIG_TYPE_BOOL:
  419. result->value = tor_strdup(*(int*)value ? "1" : "0");
  420. break;
  421. case CONFIG_TYPE_CSV:
  422. if (value)
  423. result->value = smartlist_join_strings((smartlist_t*)value,",",0,NULL);
  424. else
  425. result->value = tor_strdup("");
  426. break;
  427. default:
  428. tor_free(result->key);
  429. tor_free(result);
  430. log_fn(LOG_WARN,"Bug: unknown type %d for known key %s", var->type, key);
  431. return NULL;
  432. }
  433. return result;
  434. }
  435. /** Iterate through the linked list of requested options <b>list</b>.
  436. * For each item, convert as appropriate and assign to <b>options</b>.
  437. * If an item is unrecognized, return -1 immediately,
  438. * else return 0 for success.
  439. *
  440. * If <b>reset</b>, then interpret empty lines as meaning "restore to
  441. * default value", and interpret LINELIST* options as replacing (not
  442. * extending) their previous values.
  443. */
  444. static int
  445. config_assign(or_options_t *options, struct config_line_t *list, int reset)
  446. {
  447. struct config_line_t *p;
  448. /* pass 1: normalize keys */
  449. for (p = list; p; p = p->next) {
  450. const char *full = expand_abbrev(p->key, 0);
  451. if (strcmp(full,p->key)) {
  452. tor_free(p->key);
  453. p->key = tor_strdup(full);
  454. }
  455. }
  456. /* pass 2: if we're reading from a resetting souurce, clear all mentioned
  457. * linelists. */
  458. if (reset) {
  459. for (p = list; p; p = p->next)
  460. config_reset_line(options, p->key);
  461. }
  462. /* pass 3: assign. */
  463. while (list) {
  464. if (config_assign_line(options, list, reset))
  465. return -1;
  466. list = list->next;
  467. }
  468. return 0;
  469. }
  470. static void
  471. add_default_trusted_dirservers(void)
  472. {
  473. /* moria1 */
  474. parse_dir_server_line("18.244.0.188:9031 "
  475. "FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
  476. /* moria2 */
  477. parse_dir_server_line("18.244.0.114:80 "
  478. "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF");
  479. /* tor26 */
  480. parse_dir_server_line("62.116.124.106:9030 "
  481. "847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
  482. }
  483. /** Print a usage message for tor. */
  484. static void
  485. print_usage(void)
  486. {
  487. printf("tor -f <torrc> [args]\n"
  488. "See man page for more options. This -h is obsolete.\n");
  489. #if 0
  490. "-b <bandwidth>\t\tbytes/second rate limiting\n"
  491. "-d <file>\t\tDebug file\n"
  492. "-l <level>\t\tLog level\n"
  493. "-r <file>\t\tList of known routers\n");
  494. printf("\nClient options:\n"
  495. "-e \"nick1 nick2 ...\"\t\tExit nodes\n"
  496. "-s <IP>\t\t\tPort to bind to for Socks\n");
  497. printf("\nServer options:\n"
  498. "-n <nick>\t\tNickname of router\n"
  499. "-o <port>\t\tOR port to bind to\n"
  500. "-p <file>\t\tPID file\n");
  501. #endif
  502. }
  503. /**
  504. * Based on <b>address</b>, guess our public IP address and put it
  505. * in <b>addr</b>.
  506. */
  507. int
  508. resolve_my_address(const char *address, uint32_t *addr)
  509. {
  510. struct in_addr in;
  511. struct hostent *rent;
  512. char hostname[256];
  513. int explicit_ip=1;
  514. tor_assert(addr);
  515. if (address) {
  516. strlcpy(hostname, address, sizeof(hostname));
  517. } else { /* then we need to guess our address */
  518. explicit_ip = 0; /* it's implicit */
  519. if (gethostname(hostname, sizeof(hostname)) < 0) {
  520. log_fn(LOG_WARN,"Error obtaining local hostname");
  521. return -1;
  522. }
  523. log_fn(LOG_DEBUG,"Guessed local host name as '%s'",hostname);
  524. }
  525. /* now we know hostname. resolve it and keep only the IP */
  526. if (tor_inet_aton(hostname, &in) == 0) {
  527. /* then we have to resolve it */
  528. explicit_ip = 0;
  529. rent = (struct hostent *)gethostbyname(hostname);
  530. if (!rent) {
  531. log_fn(LOG_WARN,"Could not resolve local Address %s. Failing.", hostname);
  532. return -1;
  533. }
  534. tor_assert(rent->h_length == 4);
  535. memcpy(&in.s_addr, rent->h_addr, rent->h_length);
  536. }
  537. if (!explicit_ip && is_internal_IP(htonl(in.s_addr))) {
  538. log_fn(LOG_WARN,"Address '%s' resolves to private IP '%s'. "
  539. "Please set the Address config option to be the IP you want to use.",
  540. hostname, inet_ntoa(in));
  541. return -1;
  542. }
  543. log_fn(LOG_DEBUG, "Resolved Address to %s.", inet_ntoa(in));
  544. *addr = ntohl(in.s_addr);
  545. return 0;
  546. }
  547. static char *
  548. get_default_nickname(void)
  549. {
  550. char localhostname[256];
  551. char *cp, *out, *outp;
  552. if (gethostname(localhostname, sizeof(localhostname)) < 0) {
  553. log_fn(LOG_WARN,"Error obtaining local hostname");
  554. return NULL;
  555. }
  556. /* Put it in lowercase; stop at the first dot. */
  557. for (cp = localhostname; *cp; ++cp) {
  558. if (*cp == '.') {
  559. *cp = '\0';
  560. break;
  561. }
  562. *cp = tolower(*cp);
  563. }
  564. /* Strip invalid characters. */
  565. cp = localhostname;
  566. out = outp = tor_malloc(strlen(localhostname) + 1);
  567. while (*cp) {
  568. if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
  569. *outp++ = *cp++;
  570. else
  571. cp++;
  572. }
  573. *outp = '\0';
  574. /* Enforce length. */
  575. if (strlen(out) > MAX_NICKNAME_LEN)
  576. out[MAX_NICKNAME_LEN]='\0';
  577. return out;
  578. }
  579. /** Release storage held by <b>options</b> */
  580. static void
  581. free_options(or_options_t *options)
  582. {
  583. int i;
  584. void *lvalue;
  585. for (i=0; config_vars[i].name; ++i) {
  586. lvalue = ((char*)options) + config_vars[i].var_offset;
  587. switch(config_vars[i].type) {
  588. case CONFIG_TYPE_UINT:
  589. case CONFIG_TYPE_BOOL:
  590. case CONFIG_TYPE_DOUBLE:
  591. case CONFIG_TYPE_OBSOLETE:
  592. break; /* nothing to free for these config types */
  593. case CONFIG_TYPE_STRING:
  594. tor_free(*(char **)lvalue);
  595. break;
  596. case CONFIG_TYPE_LINELIST:
  597. case CONFIG_TYPE_LINELIST_V:
  598. config_free_lines(*(struct config_line_t**)lvalue);
  599. *(struct config_line_t**)lvalue = NULL;
  600. break;
  601. case CONFIG_TYPE_CSV:
  602. if (*(smartlist_t**)lvalue) {
  603. SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
  604. smartlist_free(*(smartlist_t**)lvalue);
  605. *(smartlist_t**)lvalue = NULL;
  606. }
  607. break;
  608. case CONFIG_TYPE_LINELIST_S:
  609. /* will be freed by corresponding LINELIST_V. */
  610. break;
  611. }
  612. }
  613. /* XXX this last part is an exception. can we make it not needed? */
  614. if (options->RedirectExitList) {
  615. SMARTLIST_FOREACH(options->RedirectExitList,
  616. exit_redirect_t *, p, tor_free(p));
  617. smartlist_free(options->RedirectExitList);
  618. options->RedirectExitList = NULL;
  619. }
  620. }
  621. /** Replace the option indexed by <b>var</b> in <b>options</b> with its
  622. * default value. */
  623. static void
  624. reset_option(or_options_t *options, config_var_t *var)
  625. {
  626. struct config_line_t *c;
  627. void *lvalue;
  628. lvalue = ((char*)options) + var->var_offset;
  629. switch (var->type) {
  630. case CONFIG_TYPE_STRING:
  631. tor_free(*(char**)lvalue);
  632. break;
  633. case CONFIG_TYPE_DOUBLE:
  634. *(double*)lvalue = 0.0;
  635. break;
  636. case CONFIG_TYPE_UINT:
  637. case CONFIG_TYPE_BOOL:
  638. *(int*)lvalue = 0;
  639. break;
  640. case CONFIG_TYPE_CSV:
  641. if (*(smartlist_t**)lvalue) {
  642. SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
  643. smartlist_free(*(smartlist_t **)lvalue);
  644. *(smartlist_t **)lvalue = NULL;
  645. }
  646. break;
  647. case CONFIG_TYPE_LINELIST:
  648. case CONFIG_TYPE_LINELIST_S:
  649. config_free_lines(*(struct config_line_t **)lvalue);
  650. *(struct config_line_t **)lvalue = NULL;
  651. break;
  652. case CONFIG_TYPE_LINELIST_V:
  653. /* handled by linelist_s. */
  654. break;
  655. case CONFIG_TYPE_OBSOLETE:
  656. break;
  657. }
  658. if (var->initvalue) {
  659. c = tor_malloc(sizeof(struct config_line_t));
  660. c->key = tor_strdup(var->name);
  661. c->value = tor_strdup(var->initvalue);
  662. config_assign_line(options,c,0);
  663. config_free_lines(c);
  664. }
  665. }
  666. /** Set <b>options</b> to hold reasonable defaults for most options.
  667. * Each option defaults to zero. */
  668. static void
  669. init_options(or_options_t *options)
  670. {
  671. int i;
  672. config_var_t *var;
  673. memset(options,0,sizeof(or_options_t));
  674. for (i=0; config_vars[i].name; ++i) {
  675. var = &config_vars[i];
  676. if(!var->initvalue)
  677. continue; /* defaults to NULL or 0 */
  678. reset_option(options, var);
  679. }
  680. }
  681. #ifdef MS_WINDOWS
  682. static char *get_windows_conf_root(void)
  683. {
  684. static int is_set = 0;
  685. static char path[MAX_PATH+1];
  686. LPITEMIDLIST idl;
  687. IMalloc *m;
  688. HRESULT result;
  689. if (is_set)
  690. return path;
  691. /* Find X:\documents and settings\username\applicatation data\ .
  692. * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
  693. */
  694. if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
  695. &idl))) {
  696. GetCurrentDirectory(MAX_PATH, path);
  697. is_set = 1;
  698. 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);
  699. return path;
  700. }
  701. /* Convert the path from an "ID List" (whatever that is!) to a path. */
  702. result = SHGetPathFromIDList(idl, path);
  703. /* Now we need to free the */
  704. SHGetMalloc(&m);
  705. if (m) {
  706. m->lpVtbl->Free(m, idl);
  707. m->lpVtbl->Release(m);
  708. }
  709. if (!SUCCEEDED(result)) {
  710. return NULL;
  711. }
  712. strlcat(path,"\\tor",MAX_PATH);
  713. is_set = 1;
  714. return path;
  715. }
  716. #endif
  717. static char *
  718. get_default_conf_file(void)
  719. {
  720. #ifdef MS_WINDOWS
  721. char *path = tor_malloc(MAX_PATH);
  722. strlcpy(path, get_windows_conf_root(), MAX_PATH);
  723. strlcat(path,"\\torrc",MAX_PATH);
  724. return path;
  725. #else
  726. return tor_strdup(CONFDIR "/torrc");
  727. #endif
  728. }
  729. /** Verify whether lst is a string containing valid-looking space-separated
  730. * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
  731. */
  732. static int check_nickname_list(const char *lst, const char *name)
  733. {
  734. int r = 0;
  735. smartlist_t *sl;
  736. if (!lst)
  737. return 0;
  738. sl = smartlist_create();
  739. smartlist_split_string(sl, lst, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  740. SMARTLIST_FOREACH(sl, const char *, s,
  741. {
  742. if (!is_legal_nickname_or_hexdigest(s)) {
  743. log_fn(LOG_WARN, "Invalid nickname '%s' in %s line", s, name);
  744. r = -1;
  745. }
  746. });
  747. SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
  748. smartlist_free(sl);
  749. return r;
  750. }
  751. static int
  752. validate_options(or_options_t *options)
  753. {
  754. int i;
  755. int result = 0;
  756. struct config_line_t *cl;
  757. if (options->ORPort < 0 || options->ORPort > 65535) {
  758. log(LOG_WARN, "ORPort option out of bounds.");
  759. result = -1;
  760. }
  761. if (options->Nickname == NULL) {
  762. if (server_mode()) {
  763. if (!(options->Nickname = get_default_nickname()))
  764. return -1;
  765. log_fn(LOG_NOTICE, "Choosing default nickname %s", options->Nickname);
  766. }
  767. } else {
  768. if (strspn(options->Nickname, LEGAL_NICKNAME_CHARACTERS) !=
  769. strlen(options->Nickname)) {
  770. log_fn(LOG_WARN, "Nickname '%s' contains illegal characters.", options->Nickname);
  771. result = -1;
  772. }
  773. if (strlen(options->Nickname) == 0) {
  774. log_fn(LOG_WARN, "Nickname must have at least one character");
  775. result = -1;
  776. }
  777. if (strlen(options->Nickname) > MAX_NICKNAME_LEN) {
  778. log_fn(LOG_WARN, "Nickname '%s' has more than %d characters.",
  779. options->Nickname, MAX_NICKNAME_LEN);
  780. result = -1;
  781. }
  782. }
  783. if (server_mode()) {
  784. /* confirm that our address isn't broken, so we can complain now */
  785. uint32_t tmp;
  786. if (resolve_my_address(options->Address, &tmp) < 0)
  787. result = -1;
  788. }
  789. if (options->SocksPort < 0 || options->SocksPort > 65535) {
  790. log(LOG_WARN, "SocksPort option out of bounds.");
  791. result = -1;
  792. }
  793. if (options->SocksPort == 0 && options->ORPort == 0) {
  794. log(LOG_WARN, "SocksPort and ORPort are both undefined? Quitting.");
  795. result = -1;
  796. }
  797. if (options->ControlPort < 0 || options->ControlPort > 65535) {
  798. log(LOG_WARN, "ControlPort option out of bounds.");
  799. result = -1;
  800. }
  801. if (options->DirPort < 0 || options->DirPort > 65535) {
  802. log(LOG_WARN, "DirPort option out of bounds.");
  803. result = -1;
  804. }
  805. if (options->StrictExitNodes &&
  806. (!options->ExitNodes || !strlen(options->ExitNodes))) {
  807. log(LOG_WARN, "StrictExitNodes set, but no ExitNodes listed.");
  808. }
  809. if (options->StrictEntryNodes &&
  810. (!options->EntryNodes || !strlen(options->EntryNodes))) {
  811. log(LOG_WARN, "StrictEntryNodes set, but no EntryNodes listed.");
  812. }
  813. if (options->AuthoritativeDir && options->RecommendedVersions == NULL) {
  814. log(LOG_WARN, "Directory servers must configure RecommendedVersions.");
  815. result = -1;
  816. }
  817. if (options->AuthoritativeDir && !options->DirPort) {
  818. log(LOG_WARN, "Running as authoritative directory, but no DirPort set.");
  819. result = -1;
  820. }
  821. if (options->AuthoritativeDir && !options->ORPort) {
  822. log(LOG_WARN, "Running as authoritative directory, but no ORPort set.");
  823. result = -1;
  824. }
  825. if (options->AuthoritativeDir && options->ClientOnly) {
  826. log(LOG_WARN, "Running as authoritative directory, but ClientOnly also set.");
  827. result = -1;
  828. }
  829. if (options->FirewallPorts) {
  830. SMARTLIST_FOREACH(options->FirewallPorts, const char *, cp,
  831. {
  832. i = atoi(cp);
  833. if (i < 1 || i > 65535) {
  834. log(LOG_WARN, "Port '%s' out of range in FirewallPorts", cp);
  835. result=-1;
  836. }
  837. });
  838. }
  839. options->_AllowUnverified = 0;
  840. if (options->AllowUnverifiedNodes) {
  841. SMARTLIST_FOREACH(options->AllowUnverifiedNodes, const char *, cp, {
  842. if (!strcasecmp(cp, "entry"))
  843. options->_AllowUnverified |= ALLOW_UNVERIFIED_ENTRY;
  844. else if (!strcasecmp(cp, "exit"))
  845. options->_AllowUnverified |= ALLOW_UNVERIFIED_EXIT;
  846. else if (!strcasecmp(cp, "middle"))
  847. options->_AllowUnverified |= ALLOW_UNVERIFIED_MIDDLE;
  848. else if (!strcasecmp(cp, "introduction"))
  849. options->_AllowUnverified |= ALLOW_UNVERIFIED_INTRODUCTION;
  850. else if (!strcasecmp(cp, "rendezvous"))
  851. options->_AllowUnverified |= ALLOW_UNVERIFIED_RENDEZVOUS;
  852. else {
  853. log(LOG_WARN, "Unrecognized value '%s' in AllowUnverifiedNodes",
  854. cp);
  855. result=-1;
  856. }
  857. });
  858. }
  859. if (options->SocksPort >= 1 &&
  860. (options->PathlenCoinWeight < 0.0 || options->PathlenCoinWeight >= 1.0)) {
  861. log(LOG_WARN, "PathlenCoinWeight option must be >=0.0 and <1.0.");
  862. result = -1;
  863. }
  864. if (options->MaxConn < 1) {
  865. log(LOG_WARN, "MaxConn option must be a non-zero positive integer.");
  866. result = -1;
  867. }
  868. if (options->MaxConn >= MAXCONNECTIONS) {
  869. log(LOG_WARN, "MaxConn option must be less than %d.", MAXCONNECTIONS);
  870. result = -1;
  871. }
  872. #define MIN_DIRFETCHPOSTPERIOD 60
  873. if (options->DirFetchPostPeriod < MIN_DIRFETCHPOSTPERIOD) {
  874. log(LOG_WARN, "DirFetchPostPeriod option must be at least %d.", MIN_DIRFETCHPOSTPERIOD);
  875. result = -1;
  876. }
  877. if (options->DirFetchPostPeriod > MIN_ONION_KEY_LIFETIME / 2) {
  878. log(LOG_WARN, "DirFetchPostPeriod is too large; clipping.");
  879. options->DirFetchPostPeriod = MIN_ONION_KEY_LIFETIME / 2;
  880. }
  881. if (options->KeepalivePeriod < 1) {
  882. log(LOG_WARN,"KeepalivePeriod option must be positive.");
  883. result = -1;
  884. }
  885. if (options->AccountingStart < 0 || options->AccountingStart > 31) {
  886. log(LOG_WARN,"Monthly accounting must start on a day of the month, and no months have %d days.",
  887. options->AccountingStart);
  888. result = -1;
  889. } else if (options->AccountingStart > 28) {
  890. log(LOG_WARN,"Not every month has %d days.",options->AccountingStart);
  891. result = -1;
  892. }
  893. if (options->HttpProxy) { /* parse it now */
  894. if (parse_addr_port(options->HttpProxy, NULL,
  895. &options->HttpProxyAddr, &options->HttpProxyPort) < 0) {
  896. log(LOG_WARN,"HttpProxy failed to parse or resolve. Please fix.");
  897. result = -1;
  898. }
  899. if (options->HttpProxyPort == 0) { /* give it a default */
  900. options->HttpProxyPort = 80;
  901. }
  902. }
  903. if (check_nickname_list(options->ExitNodes, "ExitNodes"))
  904. result = -1;
  905. if (check_nickname_list(options->EntryNodes, "EntryNodes"))
  906. result = -1;
  907. if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes"))
  908. result = -1;
  909. if (check_nickname_list(options->RendNodes, "RendNodes"))
  910. result = -1;
  911. if (check_nickname_list(options->RendNodes, "RendExcludeNodes"))
  912. result = -1;
  913. if (check_nickname_list(options->MyFamily, "MyFamily"))
  914. result = -1;
  915. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  916. if (check_nickname_list(cl->value, "NodeFamily"))
  917. result = -1;
  918. }
  919. if (!options->RedirectExitList)
  920. options->RedirectExitList = smartlist_create();
  921. /* XXX need to free the old one if it's there, else they just keep piling up */
  922. for (cl = options->RedirectExit; cl; cl = cl->next) {
  923. if (parse_redirect_line(options, cl)<0)
  924. result = -1;
  925. }
  926. clear_trusted_dir_servers();
  927. if (!options->DirServers) {
  928. add_default_trusted_dirservers();
  929. } else {
  930. for (cl = options->DirServers; cl; cl = cl->next) {
  931. if (parse_dir_server_line(cl->value)<0)
  932. result = -1;
  933. }
  934. }
  935. return result;
  936. }
  937. /** Read a configuration file into <b>options</b>, finding the configuration
  938. * file location based on the command line. After loading the options,
  939. * validate them for consistency. Return 0 if success, <0 if failure. */
  940. int
  941. getconfig(int argc, char **argv, or_options_t *options)
  942. {
  943. struct config_line_t *cl;
  944. FILE *cf;
  945. char *fname;
  946. int i;
  947. int result = 0;
  948. int using_default_torrc;
  949. static char **backup_argv;
  950. static int backup_argc;
  951. char *previous_pidfile = NULL;
  952. int previous_runasdaemon = 0;
  953. int previous_orport = -1;
  954. if (argv) { /* first time we're called. save commandline args */
  955. backup_argv = argv;
  956. backup_argc = argc;
  957. } else { /* we're reloading. need to clean up old options first. */
  958. argv = backup_argv;
  959. argc = backup_argc;
  960. /* record some previous values, so we can fail if they change */
  961. if (options->PidFile)
  962. previous_pidfile = tor_strdup(options->PidFile);
  963. previous_runasdaemon = options->RunAsDaemon;
  964. previous_orport = options->ORPort;
  965. free_options(options);
  966. }
  967. init_options(options);
  968. if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
  969. print_usage();
  970. exit(0);
  971. }
  972. if (argc > 1 && (!strcmp(argv[1],"--version"))) {
  973. printf("Tor version %s.\n",VERSION);
  974. exit(0);
  975. }
  976. /* learn config file name, get config lines, assign them */
  977. fname = NULL;
  978. using_default_torrc = 1;
  979. options->command = CMD_RUN_TOR;
  980. for (i = 1; i < argc; ++i) {
  981. if (i < argc-1 && !strcmp(argv[i],"-f")) {
  982. if (fname) {
  983. log(LOG_WARN, "Duplicate -f options on command line.");
  984. tor_free(fname);
  985. }
  986. fname = tor_strdup(argv[i+1]);
  987. using_default_torrc = 0;
  988. ++i;
  989. } else if (!strcmp(argv[i],"--list-fingerprint")) {
  990. options->command = CMD_LIST_FINGERPRINT;
  991. } else if (!strcmp(argv[i],"--hash-password")) {
  992. options->command = CMD_HASH_PASSWORD;
  993. options->command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
  994. ++i;
  995. }
  996. }
  997. if (using_default_torrc) {
  998. /* didn't find one, try CONFDIR */
  999. char *fn;
  1000. fn = get_default_conf_file();
  1001. if (fn && file_status(fn) == FN_FILE) {
  1002. fname = fn;
  1003. } else {
  1004. tor_free(fn);
  1005. fn = expand_filename("~/.torrc");
  1006. if (fn && file_status(fn) == FN_FILE) {
  1007. fname = fn;
  1008. } else {
  1009. tor_free(fn);
  1010. fname = get_default_conf_file();
  1011. }
  1012. }
  1013. }
  1014. tor_assert(fname);
  1015. log(LOG_DEBUG, "Opening config file '%s'", fname);
  1016. cf = fopen(fname, "r");
  1017. if (!cf) {
  1018. if (using_default_torrc == 1) {
  1019. log(LOG_NOTICE, "Configuration file '%s' not present, "
  1020. "using reasonable defaults.", fname);
  1021. tor_free(fname);
  1022. } else {
  1023. log(LOG_WARN, "Unable to open configuration file '%s'.", fname);
  1024. tor_free(fname);
  1025. return -1;
  1026. }
  1027. } else { /* it opened successfully. use it. */
  1028. tor_free(fname);
  1029. if (config_get_lines(cf, &cl)<0)
  1030. return -1;
  1031. if (config_assign(options,cl, 0) < 0)
  1032. return -1;
  1033. config_free_lines(cl);
  1034. fclose(cf);
  1035. }
  1036. /* go through command-line variables too */
  1037. cl = config_get_commandlines(argc,argv);
  1038. if (config_assign(options,cl,0) < 0)
  1039. return -1;
  1040. config_free_lines(cl);
  1041. /* Validate options */
  1042. /* first check if any of the previous options have changed but aren't allowed to */
  1043. if (previous_pidfile && strcmp(previous_pidfile,options->PidFile)) {
  1044. log_fn(LOG_WARN,"During reload, PidFile changed from %s to %s. Failing.",
  1045. previous_pidfile, options->PidFile);
  1046. return -1;
  1047. }
  1048. tor_free(previous_pidfile);
  1049. if (previous_runasdaemon && !options->RunAsDaemon) {
  1050. log_fn(LOG_WARN,"During reload, change from RunAsDaemon=1 to =0 not allowed. Failing.");
  1051. return -1;
  1052. }
  1053. if (previous_orport == 0 && options->ORPort > 0) {
  1054. log_fn(LOG_WARN,"During reload, change from ORPort=0 to >0 not allowed. Failing.");
  1055. return -1;
  1056. }
  1057. if (validate_options(options) < 0)
  1058. result = -1;
  1059. if (rend_config_services(options) < 0) {
  1060. result = -1;
  1061. }
  1062. return result;
  1063. }
  1064. static int
  1065. add_single_log(struct config_line_t *level_opt,
  1066. struct config_line_t *file_opt, int isDaemon)
  1067. {
  1068. int levelMin = -1, levelMax = -1;
  1069. char *cp, *tmp_sev;
  1070. if (level_opt) {
  1071. cp = strchr(level_opt->value, '-');
  1072. if (cp) {
  1073. tmp_sev = tor_strndup(level_opt->value, cp - level_opt->value);
  1074. levelMin = parse_log_level(tmp_sev);
  1075. if (levelMin < 0) {
  1076. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  1077. "err|warn|notice|info|debug", tmp_sev);
  1078. return -1;
  1079. }
  1080. tor_free(tmp_sev);
  1081. levelMax = parse_log_level(cp+1);
  1082. if (levelMax < 0) {
  1083. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  1084. "err|warn|notice|info|debug", cp+1);
  1085. return -1;
  1086. }
  1087. } else {
  1088. levelMin = parse_log_level(level_opt->value);
  1089. if (levelMin < 0) {
  1090. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  1091. "err|warn|notice|info|debug", level_opt->value);
  1092. return -1;
  1093. }
  1094. }
  1095. }
  1096. if (levelMin < 0 && levelMax < 0) {
  1097. levelMin = LOG_NOTICE;
  1098. levelMax = LOG_ERR;
  1099. } else if (levelMin < 0) {
  1100. levelMin = levelMax;
  1101. } else {
  1102. levelMax = LOG_ERR;
  1103. }
  1104. if (file_opt && !strcasecmp(file_opt->key, "LogFile")) {
  1105. if (add_file_log(levelMin, levelMax, file_opt->value) < 0) {
  1106. log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", file_opt->value,
  1107. strerror(errno));
  1108. return -1;
  1109. }
  1110. log_fn(LOG_NOTICE, "Successfully opened LogFile '%s', redirecting output.",
  1111. file_opt->value);
  1112. } else if (file_opt && !strcasecmp(file_opt->key, "SysLog")) {
  1113. #ifdef HAVE_SYSLOG_H
  1114. if (add_syslog_log(levelMin, levelMax) < 0) {
  1115. log_fn(LOG_WARN, "Cannot open system log facility");
  1116. return -1;
  1117. }
  1118. log_fn(LOG_NOTICE, "Successfully opened system log, redirecting output.");
  1119. #else
  1120. log_fn(LOG_WARN, "Tor was compiled without system logging enabled; can't enable SysLog.");
  1121. #endif
  1122. } else if (!isDaemon) {
  1123. add_stream_log(levelMin, levelMax, "<stdout>", stdout);
  1124. close_temp_logs();
  1125. }
  1126. return 0;
  1127. }
  1128. /**
  1129. * Initialize the logs based on the configuration file.
  1130. */
  1131. int
  1132. config_init_logs(or_options_t *options)
  1133. {
  1134. /* The order of options is: Level? (File Level?)+
  1135. */
  1136. struct config_line_t *opt = options->LogOptions;
  1137. /* Special case if no options are given. */
  1138. if (!opt) {
  1139. add_stream_log(LOG_NOTICE, LOG_ERR, "<stdout>", stdout);
  1140. close_temp_logs();
  1141. /* don't return yet, in case we want to do a debuglogfile below */
  1142. }
  1143. /* Special case for if first option is LogLevel. */
  1144. if (opt && !strcasecmp(opt->key, "LogLevel")) {
  1145. if (opt->next && (!strcasecmp(opt->next->key, "LogFile") ||
  1146. !strcasecmp(opt->next->key, "SysLog"))) {
  1147. if (add_single_log(opt, opt->next, options->RunAsDaemon) < 0)
  1148. return -1;
  1149. opt = opt->next->next;
  1150. } else if (!opt->next) {
  1151. if (add_single_log(opt, NULL, options->RunAsDaemon) < 0)
  1152. return -1;
  1153. opt = opt->next;
  1154. } else {
  1155. ; /* give warning below */
  1156. }
  1157. }
  1158. while (opt) {
  1159. if (!strcasecmp(opt->key, "LogLevel")) {
  1160. log_fn(LOG_WARN, "Two LogLevel options in a row without intervening LogFile or SysLog");
  1161. opt = opt->next;
  1162. } else {
  1163. tor_assert(!strcasecmp(opt->key, "LogFile") ||
  1164. !strcasecmp(opt->key, "SysLog"));
  1165. if (opt->next && !strcasecmp(opt->next->key, "LogLevel")) {
  1166. /* LogFile/SysLog followed by LogLevel */
  1167. if (add_single_log(opt->next, opt, options->RunAsDaemon) < 0)
  1168. return -1;
  1169. opt = opt->next->next;
  1170. } else {
  1171. /* LogFile/SysLog followed by LogFile/SysLog or end of list. */
  1172. if (add_single_log(NULL, opt, options->RunAsDaemon) < 0)
  1173. return -1;
  1174. opt = opt->next;
  1175. }
  1176. }
  1177. }
  1178. if (options->DebugLogFile) {
  1179. log_fn(LOG_WARN, "DebugLogFile is deprecated; use LogFile and LogLevel instead");
  1180. if (add_file_log(LOG_DEBUG, LOG_ERR, options->DebugLogFile) < 0)
  1181. return -1;
  1182. }
  1183. return 0;
  1184. }
  1185. /**
  1186. * Given a linked list of config lines containing "allow" and "deny" tokens,
  1187. * parse them and place the result in <b>dest</b>. Skip malformed lines.
  1188. */
  1189. void
  1190. config_parse_exit_policy(struct config_line_t *cfg,
  1191. struct exit_policy_t **dest)
  1192. {
  1193. struct exit_policy_t **nextp;
  1194. smartlist_t *entries;
  1195. if (!cfg)
  1196. return;
  1197. nextp = dest;
  1198. while (*nextp)
  1199. nextp = &((*nextp)->next);
  1200. entries = smartlist_create();
  1201. for (; cfg; cfg = cfg->next) {
  1202. smartlist_split_string(entries, cfg->value, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1203. SMARTLIST_FOREACH(entries, const char *, ent,
  1204. {
  1205. log_fn(LOG_DEBUG,"Adding new entry '%s'",ent);
  1206. *nextp = router_parse_exit_policy_from_string(ent);
  1207. if (*nextp) {
  1208. nextp = &((*nextp)->next);
  1209. } else {
  1210. log_fn(LOG_WARN,"Malformed exit policy %s; skipping.", ent);
  1211. }
  1212. });
  1213. SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
  1214. smartlist_clear(entries);
  1215. }
  1216. smartlist_free(entries);
  1217. }
  1218. void exit_policy_free(struct exit_policy_t *p) {
  1219. struct exit_policy_t *e;
  1220. while (p) {
  1221. e = p;
  1222. p = p->next;
  1223. tor_free(e->string);
  1224. tor_free(e);
  1225. }
  1226. }
  1227. static int parse_redirect_line(or_options_t *options,
  1228. struct config_line_t *line)
  1229. {
  1230. smartlist_t *elements = NULL;
  1231. exit_redirect_t *r;
  1232. tor_assert(options);
  1233. tor_assert(options->RedirectExitList);
  1234. tor_assert(line);
  1235. r = tor_malloc_zero(sizeof(exit_redirect_t));
  1236. elements = smartlist_create();
  1237. smartlist_split_string(elements, line->value, " ",
  1238. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1239. if (smartlist_len(elements) != 2) {
  1240. log_fn(LOG_WARN, "Wrong number of elements in RedirectExit line");
  1241. goto err;
  1242. }
  1243. if (parse_addr_and_port_range(smartlist_get(elements,0),&r->addr,&r->mask,
  1244. &r->port_min,&r->port_max)) {
  1245. log_fn(LOG_WARN, "Error parsing source address in RedirectExit line");
  1246. goto err;
  1247. }
  1248. if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
  1249. r->is_redirect = 0;
  1250. } else {
  1251. if (parse_addr_port(smartlist_get(elements,1),NULL,&r->addr_dest,
  1252. &r->port_dest)) {
  1253. log_fn(LOG_WARN, "Error parseing dest address in RedirectExit line");
  1254. goto err;
  1255. }
  1256. r->is_redirect = 1;
  1257. }
  1258. goto done;
  1259. err:
  1260. tor_free(r);
  1261. done:
  1262. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  1263. smartlist_free(elements);
  1264. if (r) {
  1265. smartlist_add(options->RedirectExitList, r);
  1266. return 0;
  1267. } else {
  1268. return -1;
  1269. }
  1270. }
  1271. static int parse_dir_server_line(const char *line)
  1272. {
  1273. smartlist_t *items = NULL;
  1274. int r;
  1275. char *addrport, *address=NULL;
  1276. uint16_t port;
  1277. char digest[DIGEST_LEN];
  1278. items = smartlist_create();
  1279. smartlist_split_string(items, line, " ",
  1280. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  1281. if (smartlist_len(items) < 2) {
  1282. log_fn(LOG_WARN, "Too few arguments to DirServer line.");
  1283. goto err;
  1284. }
  1285. addrport = smartlist_get(items, 0);
  1286. if (parse_addr_port(addrport, &address, NULL, &port)<0) {
  1287. log_fn(LOG_WARN, "Error parsing DirServer address '%s'", addrport);
  1288. goto err;
  1289. }
  1290. if (!port) {
  1291. log_fn(LOG_WARN, "Missing port in DirServe address '%s'",addrport);
  1292. goto err;
  1293. }
  1294. tor_strstrip(smartlist_get(items, 1), " ");
  1295. if (strlen(smartlist_get(items, 1)) != HEX_DIGEST_LEN) {
  1296. log_fn(LOG_WARN, "Key digest for DirServer is wrong length.");
  1297. goto err;
  1298. }
  1299. if (base16_decode(digest, DIGEST_LEN,
  1300. smartlist_get(items,1), HEX_DIGEST_LEN)<0) {
  1301. log_fn(LOG_WARN, "Unable to decode DirServer key digest.");
  1302. goto err;
  1303. }
  1304. log_fn(LOG_DEBUG, "Trusted dirserver at %s:%d (%s)", address, (int)port,
  1305. (char*)smartlist_get(items,1));
  1306. add_trusted_dir_server(address, port, digest);
  1307. r = 0;
  1308. goto done;
  1309. err:
  1310. r = -1;
  1311. done:
  1312. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  1313. smartlist_free(items);
  1314. if (address)
  1315. tor_free(address);
  1316. return r;
  1317. }
  1318. const char *
  1319. get_data_directory(or_options_t *options)
  1320. {
  1321. const char *d;
  1322. if (options->DataDirectory) {
  1323. d = options->DataDirectory;
  1324. } else {
  1325. #ifdef MS_WINDOWS
  1326. char *p;
  1327. p = tor_malloc(MAX_PATH);
  1328. strlcpy(p,get_windows_conf_root(),MAX_PATH);
  1329. options->DataDirectory = p;
  1330. return p;
  1331. #else
  1332. d = "~/.tor";
  1333. #endif
  1334. }
  1335. if (d && strncmp(d,"~/",2) == 0) {
  1336. char *fn = expand_filename(d);
  1337. if (!fn) {
  1338. log_fn(LOG_ERR,"Failed to expand filename '%s'. Exiting.", d);
  1339. exit(1);
  1340. }
  1341. tor_free(options->DataDirectory);
  1342. options->DataDirectory = fn;
  1343. }
  1344. return options->DataDirectory;
  1345. }
  1346. /*
  1347. Local Variables:
  1348. mode:c
  1349. indent-tabs-mode:nil
  1350. c-basic-offset:2
  1351. End:
  1352. */