config.c 43 KB

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