config.c 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  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, NULL),
  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. smartlist_t *config_get_default_firewallports(void) {
  752. static smartlist_t *answer;
  753. if(!answer) {
  754. answer = smartlist_create();
  755. smartlist_add(answer, tor_strdup("80"));
  756. smartlist_add(answer, tor_strdup("443"));
  757. }
  758. return answer;
  759. }
  760. static int
  761. validate_options(or_options_t *options)
  762. {
  763. int i;
  764. int result = 0;
  765. struct config_line_t *cl;
  766. if (options->ORPort < 0 || options->ORPort > 65535) {
  767. log(LOG_WARN, "ORPort option out of bounds.");
  768. result = -1;
  769. }
  770. if (options->Nickname == NULL) {
  771. if (server_mode()) {
  772. if (!(options->Nickname = get_default_nickname()))
  773. return -1;
  774. log_fn(LOG_NOTICE, "Choosing default nickname %s", options->Nickname);
  775. }
  776. } else {
  777. if (strspn(options->Nickname, LEGAL_NICKNAME_CHARACTERS) !=
  778. strlen(options->Nickname)) {
  779. log_fn(LOG_WARN, "Nickname '%s' contains illegal characters.", options->Nickname);
  780. result = -1;
  781. }
  782. if (strlen(options->Nickname) == 0) {
  783. log_fn(LOG_WARN, "Nickname must have at least one character");
  784. result = -1;
  785. }
  786. if (strlen(options->Nickname) > MAX_NICKNAME_LEN) {
  787. log_fn(LOG_WARN, "Nickname '%s' has more than %d characters.",
  788. options->Nickname, MAX_NICKNAME_LEN);
  789. result = -1;
  790. }
  791. }
  792. if (server_mode()) {
  793. /* confirm that our address isn't broken, so we can complain now */
  794. uint32_t tmp;
  795. if (resolve_my_address(options->Address, &tmp) < 0)
  796. result = -1;
  797. }
  798. if (options->SocksPort < 0 || options->SocksPort > 65535) {
  799. log(LOG_WARN, "SocksPort option out of bounds.");
  800. result = -1;
  801. }
  802. if (options->SocksPort == 0 && options->ORPort == 0) {
  803. log(LOG_WARN, "SocksPort and ORPort are both undefined? Quitting.");
  804. result = -1;
  805. }
  806. if (options->ControlPort < 0 || options->ControlPort > 65535) {
  807. log(LOG_WARN, "ControlPort option out of bounds.");
  808. result = -1;
  809. }
  810. if (options->DirPort < 0 || options->DirPort > 65535) {
  811. log(LOG_WARN, "DirPort option out of bounds.");
  812. result = -1;
  813. }
  814. if (options->StrictExitNodes &&
  815. (!options->ExitNodes || !strlen(options->ExitNodes))) {
  816. log(LOG_WARN, "StrictExitNodes set, but no ExitNodes listed.");
  817. }
  818. if (options->StrictEntryNodes &&
  819. (!options->EntryNodes || !strlen(options->EntryNodes))) {
  820. log(LOG_WARN, "StrictEntryNodes set, but no EntryNodes listed.");
  821. }
  822. if (options->AuthoritativeDir && options->RecommendedVersions == NULL) {
  823. log(LOG_WARN, "Directory servers must configure RecommendedVersions.");
  824. result = -1;
  825. }
  826. if (options->AuthoritativeDir && !options->DirPort) {
  827. log(LOG_WARN, "Running as authoritative directory, but no DirPort set.");
  828. result = -1;
  829. }
  830. if (options->AuthoritativeDir && !options->ORPort) {
  831. log(LOG_WARN, "Running as authoritative directory, but no ORPort set.");
  832. result = -1;
  833. }
  834. if (options->AuthoritativeDir && options->ClientOnly) {
  835. log(LOG_WARN, "Running as authoritative directory, but ClientOnly also set.");
  836. result = -1;
  837. }
  838. if (options->FirewallPorts) {
  839. SMARTLIST_FOREACH(options->FirewallPorts, const char *, cp,
  840. {
  841. i = atoi(cp);
  842. if (i < 1 || i > 65535) {
  843. log(LOG_WARN, "Port '%s' out of range in FirewallPorts", cp);
  844. result=-1;
  845. }
  846. });
  847. }
  848. options->_AllowUnverified = 0;
  849. if (options->AllowUnverifiedNodes) {
  850. SMARTLIST_FOREACH(options->AllowUnverifiedNodes, const char *, cp, {
  851. if (!strcasecmp(cp, "entry"))
  852. options->_AllowUnverified |= ALLOW_UNVERIFIED_ENTRY;
  853. else if (!strcasecmp(cp, "exit"))
  854. options->_AllowUnverified |= ALLOW_UNVERIFIED_EXIT;
  855. else if (!strcasecmp(cp, "middle"))
  856. options->_AllowUnverified |= ALLOW_UNVERIFIED_MIDDLE;
  857. else if (!strcasecmp(cp, "introduction"))
  858. options->_AllowUnverified |= ALLOW_UNVERIFIED_INTRODUCTION;
  859. else if (!strcasecmp(cp, "rendezvous"))
  860. options->_AllowUnverified |= ALLOW_UNVERIFIED_RENDEZVOUS;
  861. else {
  862. log(LOG_WARN, "Unrecognized value '%s' in AllowUnverifiedNodes",
  863. cp);
  864. result=-1;
  865. }
  866. });
  867. }
  868. if (options->SocksPort >= 1 &&
  869. (options->PathlenCoinWeight < 0.0 || options->PathlenCoinWeight >= 1.0)) {
  870. log(LOG_WARN, "PathlenCoinWeight option must be >=0.0 and <1.0.");
  871. result = -1;
  872. }
  873. if (options->MaxConn < 1) {
  874. log(LOG_WARN, "MaxConn option must be a non-zero positive integer.");
  875. result = -1;
  876. }
  877. if (options->MaxConn >= MAXCONNECTIONS) {
  878. log(LOG_WARN, "MaxConn option must be less than %d.", MAXCONNECTIONS);
  879. result = -1;
  880. }
  881. #define MIN_DIRFETCHPOSTPERIOD 60
  882. if (options->DirFetchPostPeriod < MIN_DIRFETCHPOSTPERIOD) {
  883. log(LOG_WARN, "DirFetchPostPeriod option must be at least %d.", MIN_DIRFETCHPOSTPERIOD);
  884. result = -1;
  885. }
  886. if (options->DirFetchPostPeriod > MIN_ONION_KEY_LIFETIME / 2) {
  887. log(LOG_WARN, "DirFetchPostPeriod is too large; clipping.");
  888. options->DirFetchPostPeriod = MIN_ONION_KEY_LIFETIME / 2;
  889. }
  890. if (options->KeepalivePeriod < 1) {
  891. log(LOG_WARN,"KeepalivePeriod option must be positive.");
  892. result = -1;
  893. }
  894. if (options->AccountingStart < 0 || options->AccountingStart > 31) {
  895. log(LOG_WARN,"Monthly accounting must start on a day of the month, and no months have %d days.",
  896. options->AccountingStart);
  897. result = -1;
  898. } else if (options->AccountingStart > 28) {
  899. log(LOG_WARN,"Not every month has %d days.",options->AccountingStart);
  900. result = -1;
  901. }
  902. if (options->HttpProxy) { /* parse it now */
  903. if (parse_addr_port(options->HttpProxy, NULL,
  904. &options->HttpProxyAddr, &options->HttpProxyPort) < 0) {
  905. log(LOG_WARN,"HttpProxy failed to parse or resolve. Please fix.");
  906. result = -1;
  907. }
  908. if (options->HttpProxyPort == 0) { /* give it a default */
  909. options->HttpProxyPort = 80;
  910. }
  911. }
  912. if (check_nickname_list(options->ExitNodes, "ExitNodes"))
  913. result = -1;
  914. if (check_nickname_list(options->EntryNodes, "EntryNodes"))
  915. result = -1;
  916. if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes"))
  917. result = -1;
  918. if (check_nickname_list(options->RendNodes, "RendNodes"))
  919. result = -1;
  920. if (check_nickname_list(options->RendNodes, "RendExcludeNodes"))
  921. result = -1;
  922. if (check_nickname_list(options->MyFamily, "MyFamily"))
  923. result = -1;
  924. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  925. if (check_nickname_list(cl->value, "NodeFamily"))
  926. result = -1;
  927. }
  928. if (!options->RedirectExitList)
  929. options->RedirectExitList = smartlist_create();
  930. /* XXX need to free the old one if it's there, else they just keep piling up */
  931. for (cl = options->RedirectExit; cl; cl = cl->next) {
  932. if (parse_redirect_line(options, cl)<0)
  933. result = -1;
  934. }
  935. clear_trusted_dir_servers();
  936. if (!options->DirServers) {
  937. add_default_trusted_dirservers();
  938. } else {
  939. for (cl = options->DirServers; cl; cl = cl->next) {
  940. if (parse_dir_server_line(cl->value)<0)
  941. result = -1;
  942. }
  943. }
  944. return result;
  945. }
  946. /** Read a configuration file into <b>options</b>, finding the configuration
  947. * file location based on the command line. After loading the options,
  948. * validate them for consistency. Return 0 if success, <0 if failure. */
  949. int
  950. getconfig(int argc, char **argv, or_options_t *options)
  951. {
  952. struct config_line_t *cl;
  953. FILE *cf;
  954. char *fname;
  955. int i;
  956. int result = 0;
  957. int using_default_torrc;
  958. static char **backup_argv;
  959. static int backup_argc;
  960. char *previous_pidfile = NULL;
  961. int previous_runasdaemon = 0;
  962. int previous_orport = -1;
  963. if (argv) { /* first time we're called. save commandline args */
  964. backup_argv = argv;
  965. backup_argc = argc;
  966. } else { /* we're reloading. need to clean up old options first. */
  967. argv = backup_argv;
  968. argc = backup_argc;
  969. /* record some previous values, so we can fail if they change */
  970. if (options->PidFile)
  971. previous_pidfile = tor_strdup(options->PidFile);
  972. previous_runasdaemon = options->RunAsDaemon;
  973. previous_orport = options->ORPort;
  974. free_options(options);
  975. }
  976. init_options(options);
  977. if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
  978. print_usage();
  979. exit(0);
  980. }
  981. if (argc > 1 && (!strcmp(argv[1],"--version"))) {
  982. printf("Tor version %s.\n",VERSION);
  983. exit(0);
  984. }
  985. /* learn config file name, get config lines, assign them */
  986. fname = NULL;
  987. using_default_torrc = 1;
  988. options->command = CMD_RUN_TOR;
  989. for (i = 1; i < argc; ++i) {
  990. if (i < argc-1 && !strcmp(argv[i],"-f")) {
  991. if (fname) {
  992. log(LOG_WARN, "Duplicate -f options on command line.");
  993. tor_free(fname);
  994. }
  995. fname = tor_strdup(argv[i+1]);
  996. using_default_torrc = 0;
  997. ++i;
  998. } else if (!strcmp(argv[i],"--list-fingerprint")) {
  999. options->command = CMD_LIST_FINGERPRINT;
  1000. } else if (!strcmp(argv[i],"--hash-password")) {
  1001. options->command = CMD_HASH_PASSWORD;
  1002. options->command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
  1003. ++i;
  1004. }
  1005. }
  1006. if (using_default_torrc) {
  1007. /* didn't find one, try CONFDIR */
  1008. char *fn;
  1009. fn = get_default_conf_file();
  1010. if (fn && file_status(fn) == FN_FILE) {
  1011. fname = fn;
  1012. } else {
  1013. tor_free(fn);
  1014. fn = expand_filename("~/.torrc");
  1015. if (fn && file_status(fn) == FN_FILE) {
  1016. fname = fn;
  1017. } else {
  1018. tor_free(fn);
  1019. fname = get_default_conf_file();
  1020. }
  1021. }
  1022. }
  1023. tor_assert(fname);
  1024. log(LOG_DEBUG, "Opening config file '%s'", fname);
  1025. cf = fopen(fname, "r");
  1026. if (!cf) {
  1027. if (using_default_torrc == 1) {
  1028. log(LOG_NOTICE, "Configuration file '%s' not present, "
  1029. "using reasonable defaults.", fname);
  1030. tor_free(fname);
  1031. } else {
  1032. log(LOG_WARN, "Unable to open configuration file '%s'.", fname);
  1033. tor_free(fname);
  1034. return -1;
  1035. }
  1036. } else { /* it opened successfully. use it. */
  1037. tor_free(fname);
  1038. if (config_get_lines(cf, &cl)<0)
  1039. return -1;
  1040. if (config_assign(options,cl, 0) < 0)
  1041. return -1;
  1042. config_free_lines(cl);
  1043. fclose(cf);
  1044. }
  1045. /* go through command-line variables too */
  1046. cl = config_get_commandlines(argc,argv);
  1047. if (config_assign(options,cl,0) < 0)
  1048. return -1;
  1049. config_free_lines(cl);
  1050. /* Validate options */
  1051. /* first check if any of the previous options have changed but aren't allowed to */
  1052. if (previous_pidfile && strcmp(previous_pidfile,options->PidFile)) {
  1053. log_fn(LOG_WARN,"During reload, PidFile changed from %s to %s. Failing.",
  1054. previous_pidfile, options->PidFile);
  1055. return -1;
  1056. }
  1057. tor_free(previous_pidfile);
  1058. if (previous_runasdaemon && !options->RunAsDaemon) {
  1059. log_fn(LOG_WARN,"During reload, change from RunAsDaemon=1 to =0 not allowed. Failing.");
  1060. return -1;
  1061. }
  1062. if (previous_orport == 0 && options->ORPort > 0) {
  1063. log_fn(LOG_WARN,"During reload, change from ORPort=0 to >0 not allowed. Failing.");
  1064. return -1;
  1065. }
  1066. if (validate_options(options) < 0)
  1067. result = -1;
  1068. if (rend_config_services(options) < 0) {
  1069. result = -1;
  1070. }
  1071. return result;
  1072. }
  1073. static int
  1074. add_single_log(struct config_line_t *level_opt,
  1075. struct config_line_t *file_opt, int isDaemon)
  1076. {
  1077. int levelMin = -1, levelMax = -1;
  1078. char *cp, *tmp_sev;
  1079. if (level_opt) {
  1080. cp = strchr(level_opt->value, '-');
  1081. if (cp) {
  1082. tmp_sev = tor_strndup(level_opt->value, cp - level_opt->value);
  1083. levelMin = parse_log_level(tmp_sev);
  1084. if (levelMin < 0) {
  1085. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  1086. "err|warn|notice|info|debug", tmp_sev);
  1087. return -1;
  1088. }
  1089. tor_free(tmp_sev);
  1090. levelMax = parse_log_level(cp+1);
  1091. if (levelMax < 0) {
  1092. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  1093. "err|warn|notice|info|debug", cp+1);
  1094. return -1;
  1095. }
  1096. } else {
  1097. levelMin = parse_log_level(level_opt->value);
  1098. if (levelMin < 0) {
  1099. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  1100. "err|warn|notice|info|debug", level_opt->value);
  1101. return -1;
  1102. }
  1103. }
  1104. }
  1105. if (levelMin < 0 && levelMax < 0) {
  1106. levelMin = LOG_NOTICE;
  1107. levelMax = LOG_ERR;
  1108. } else if (levelMin < 0) {
  1109. levelMin = levelMax;
  1110. } else {
  1111. levelMax = LOG_ERR;
  1112. }
  1113. if (file_opt && !strcasecmp(file_opt->key, "LogFile")) {
  1114. if (add_file_log(levelMin, levelMax, file_opt->value) < 0) {
  1115. log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", file_opt->value,
  1116. strerror(errno));
  1117. return -1;
  1118. }
  1119. log_fn(LOG_NOTICE, "Successfully opened LogFile '%s', redirecting output.",
  1120. file_opt->value);
  1121. } else if (file_opt && !strcasecmp(file_opt->key, "SysLog")) {
  1122. #ifdef HAVE_SYSLOG_H
  1123. if (add_syslog_log(levelMin, levelMax) < 0) {
  1124. log_fn(LOG_WARN, "Cannot open system log facility");
  1125. return -1;
  1126. }
  1127. log_fn(LOG_NOTICE, "Successfully opened system log, redirecting output.");
  1128. #else
  1129. log_fn(LOG_WARN, "Tor was compiled without system logging enabled; can't enable SysLog.");
  1130. #endif
  1131. } else if (!isDaemon) {
  1132. add_stream_log(levelMin, levelMax, "<stdout>", stdout);
  1133. close_temp_logs();
  1134. }
  1135. return 0;
  1136. }
  1137. /**
  1138. * Initialize the logs based on the configuration file.
  1139. */
  1140. int
  1141. config_init_logs(or_options_t *options)
  1142. {
  1143. /* The order of options is: Level? (File Level?)+
  1144. */
  1145. struct config_line_t *opt = options->LogOptions;
  1146. /* Special case if no options are given. */
  1147. if (!opt) {
  1148. add_stream_log(LOG_NOTICE, LOG_ERR, "<stdout>", stdout);
  1149. close_temp_logs();
  1150. /* don't return yet, in case we want to do a debuglogfile below */
  1151. }
  1152. /* Special case for if first option is LogLevel. */
  1153. if (opt && !strcasecmp(opt->key, "LogLevel")) {
  1154. if (opt->next && (!strcasecmp(opt->next->key, "LogFile") ||
  1155. !strcasecmp(opt->next->key, "SysLog"))) {
  1156. if (add_single_log(opt, opt->next, options->RunAsDaemon) < 0)
  1157. return -1;
  1158. opt = opt->next->next;
  1159. } else if (!opt->next) {
  1160. if (add_single_log(opt, NULL, options->RunAsDaemon) < 0)
  1161. return -1;
  1162. opt = opt->next;
  1163. } else {
  1164. ; /* give warning below */
  1165. }
  1166. }
  1167. while (opt) {
  1168. if (!strcasecmp(opt->key, "LogLevel")) {
  1169. log_fn(LOG_WARN, "Two LogLevel options in a row without intervening LogFile or SysLog");
  1170. opt = opt->next;
  1171. } else {
  1172. tor_assert(!strcasecmp(opt->key, "LogFile") ||
  1173. !strcasecmp(opt->key, "SysLog"));
  1174. if (opt->next && !strcasecmp(opt->next->key, "LogLevel")) {
  1175. /* LogFile/SysLog followed by LogLevel */
  1176. if (add_single_log(opt->next, opt, options->RunAsDaemon) < 0)
  1177. return -1;
  1178. opt = opt->next->next;
  1179. } else {
  1180. /* LogFile/SysLog followed by LogFile/SysLog or end of list. */
  1181. if (add_single_log(NULL, opt, options->RunAsDaemon) < 0)
  1182. return -1;
  1183. opt = opt->next;
  1184. }
  1185. }
  1186. }
  1187. if (options->DebugLogFile) {
  1188. log_fn(LOG_WARN, "DebugLogFile is deprecated; use LogFile and LogLevel instead");
  1189. if (add_file_log(LOG_DEBUG, LOG_ERR, options->DebugLogFile) < 0)
  1190. return -1;
  1191. }
  1192. return 0;
  1193. }
  1194. /**
  1195. * Given a linked list of config lines containing "allow" and "deny" tokens,
  1196. * parse them and place the result in <b>dest</b>. Skip malformed lines.
  1197. */
  1198. void
  1199. config_parse_exit_policy(struct config_line_t *cfg,
  1200. struct exit_policy_t **dest)
  1201. {
  1202. struct exit_policy_t **nextp;
  1203. smartlist_t *entries;
  1204. if (!cfg)
  1205. return;
  1206. nextp = dest;
  1207. while (*nextp)
  1208. nextp = &((*nextp)->next);
  1209. entries = smartlist_create();
  1210. for (; cfg; cfg = cfg->next) {
  1211. smartlist_split_string(entries, cfg->value, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1212. SMARTLIST_FOREACH(entries, const char *, ent,
  1213. {
  1214. log_fn(LOG_DEBUG,"Adding new entry '%s'",ent);
  1215. *nextp = router_parse_exit_policy_from_string(ent);
  1216. if (*nextp) {
  1217. nextp = &((*nextp)->next);
  1218. } else {
  1219. log_fn(LOG_WARN,"Malformed exit policy %s; skipping.", ent);
  1220. }
  1221. });
  1222. SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
  1223. smartlist_clear(entries);
  1224. }
  1225. smartlist_free(entries);
  1226. }
  1227. void exit_policy_free(struct exit_policy_t *p) {
  1228. struct exit_policy_t *e;
  1229. while (p) {
  1230. e = p;
  1231. p = p->next;
  1232. tor_free(e->string);
  1233. tor_free(e);
  1234. }
  1235. }
  1236. static int parse_redirect_line(or_options_t *options,
  1237. struct config_line_t *line)
  1238. {
  1239. smartlist_t *elements = NULL;
  1240. exit_redirect_t *r;
  1241. tor_assert(options);
  1242. tor_assert(options->RedirectExitList);
  1243. tor_assert(line);
  1244. r = tor_malloc_zero(sizeof(exit_redirect_t));
  1245. elements = smartlist_create();
  1246. smartlist_split_string(elements, line->value, " ",
  1247. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1248. if (smartlist_len(elements) != 2) {
  1249. log_fn(LOG_WARN, "Wrong number of elements in RedirectExit line");
  1250. goto err;
  1251. }
  1252. if (parse_addr_and_port_range(smartlist_get(elements,0),&r->addr,&r->mask,
  1253. &r->port_min,&r->port_max)) {
  1254. log_fn(LOG_WARN, "Error parsing source address in RedirectExit line");
  1255. goto err;
  1256. }
  1257. if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
  1258. r->is_redirect = 0;
  1259. } else {
  1260. if (parse_addr_port(smartlist_get(elements,1),NULL,&r->addr_dest,
  1261. &r->port_dest)) {
  1262. log_fn(LOG_WARN, "Error parseing dest address in RedirectExit line");
  1263. goto err;
  1264. }
  1265. r->is_redirect = 1;
  1266. }
  1267. goto done;
  1268. err:
  1269. tor_free(r);
  1270. done:
  1271. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  1272. smartlist_free(elements);
  1273. if (r) {
  1274. smartlist_add(options->RedirectExitList, r);
  1275. return 0;
  1276. } else {
  1277. return -1;
  1278. }
  1279. }
  1280. static int parse_dir_server_line(const char *line)
  1281. {
  1282. smartlist_t *items = NULL;
  1283. int r;
  1284. char *addrport, *address=NULL;
  1285. uint16_t port;
  1286. char digest[DIGEST_LEN];
  1287. items = smartlist_create();
  1288. smartlist_split_string(items, line, " ",
  1289. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  1290. if (smartlist_len(items) < 2) {
  1291. log_fn(LOG_WARN, "Too few arguments to DirServer line.");
  1292. goto err;
  1293. }
  1294. addrport = smartlist_get(items, 0);
  1295. if (parse_addr_port(addrport, &address, NULL, &port)<0) {
  1296. log_fn(LOG_WARN, "Error parsing DirServer address '%s'", addrport);
  1297. goto err;
  1298. }
  1299. if (!port) {
  1300. log_fn(LOG_WARN, "Missing port in DirServe address '%s'",addrport);
  1301. goto err;
  1302. }
  1303. tor_strstrip(smartlist_get(items, 1), " ");
  1304. if (strlen(smartlist_get(items, 1)) != HEX_DIGEST_LEN) {
  1305. log_fn(LOG_WARN, "Key digest for DirServer is wrong length.");
  1306. goto err;
  1307. }
  1308. if (base16_decode(digest, DIGEST_LEN,
  1309. smartlist_get(items,1), HEX_DIGEST_LEN)<0) {
  1310. log_fn(LOG_WARN, "Unable to decode DirServer key digest.");
  1311. goto err;
  1312. }
  1313. log_fn(LOG_DEBUG, "Trusted dirserver at %s:%d (%s)", address, (int)port,
  1314. (char*)smartlist_get(items,1));
  1315. add_trusted_dir_server(address, port, digest);
  1316. r = 0;
  1317. goto done;
  1318. err:
  1319. r = -1;
  1320. done:
  1321. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  1322. smartlist_free(items);
  1323. if (address)
  1324. tor_free(address);
  1325. return r;
  1326. }
  1327. const char *
  1328. get_data_directory(or_options_t *options)
  1329. {
  1330. const char *d;
  1331. if (options->DataDirectory) {
  1332. d = options->DataDirectory;
  1333. } else {
  1334. #ifdef MS_WINDOWS
  1335. char *p;
  1336. p = tor_malloc(MAX_PATH);
  1337. strlcpy(p,get_windows_conf_root(),MAX_PATH);
  1338. options->DataDirectory = p;
  1339. return p;
  1340. #else
  1341. d = "~/.tor";
  1342. #endif
  1343. }
  1344. if (d && strncmp(d,"~/",2) == 0) {
  1345. char *fn = expand_filename(d);
  1346. if (!fn) {
  1347. log_fn(LOG_ERR,"Failed to expand filename '%s'. Exiting.", d);
  1348. exit(1);
  1349. }
  1350. tor_free(options->DataDirectory);
  1351. options->DataDirectory = fn;
  1352. }
  1353. return options->DataDirectory;
  1354. }
  1355. /*
  1356. Local Variables:
  1357. mode:c
  1358. indent-tabs-mode:nil
  1359. c-basic-offset:2
  1360. End:
  1361. */