config.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  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. /** Largest allowed config line */
  26. #define CONFIG_LINE_T_MAXLEN 4096
  27. static struct config_line_t *config_get_commandlines(int argc, char **argv);
  28. static int config_get_lines(FILE *f, struct config_line_t **result);
  29. static void config_free_lines(struct config_line_t *front);
  30. static int config_compare(struct config_line_t *c, const char *key, config_type_t type, void *arg);
  31. static int config_assign(or_options_t *options, struct config_line_t *list);
  32. static int parse_dir_server_line(const char *line);
  33. /** Helper: Read a list of configuration options from the command line. */
  34. static struct config_line_t *
  35. config_get_commandlines(int argc, char **argv)
  36. {
  37. struct config_line_t *new;
  38. struct config_line_t *front = NULL;
  39. char *s;
  40. int i = 1;
  41. while (i < argc-1) {
  42. if (!strcmp(argv[i],"-f")) {
  43. // log(LOG_DEBUG,"Commandline: skipping over -f.");
  44. i += 2; /* this is the config file option. ignore it. */
  45. continue;
  46. }
  47. new = tor_malloc(sizeof(struct config_line_t));
  48. s = argv[i];
  49. while(*s == '-')
  50. s++;
  51. new->key = tor_strdup(s);
  52. new->value = tor_strdup(argv[i+1]);
  53. log(LOG_DEBUG,"Commandline: parsed keyword '%s', value '%s'",
  54. new->key, new->value);
  55. new->next = front;
  56. front = new;
  57. i += 2;
  58. }
  59. return front;
  60. }
  61. /** Helper: allocate a new configuration option mapping 'key' to 'val',
  62. * prepend it to 'front', and return the newly allocated config_line_t */
  63. static struct config_line_t *
  64. config_line_prepend(struct config_line_t *front,
  65. const char *key,
  66. const char *val)
  67. {
  68. struct config_line_t *newline;
  69. newline = tor_malloc(sizeof(struct config_line_t));
  70. newline->key = tor_strdup(key);
  71. newline->value = tor_strdup(val);
  72. newline->next = front;
  73. return newline;
  74. }
  75. /** Helper: parse the config file and strdup into key/value
  76. * strings. Set *result to the list, or NULL if parsing the file
  77. * failed. Return 0 on success, -1 on failure. Warn and ignore any
  78. * misformatted lines. */
  79. static int
  80. config_get_lines(FILE *f, struct config_line_t **result)
  81. {
  82. struct config_line_t *front = NULL;
  83. char line[CONFIG_LINE_T_MAXLEN];
  84. int r;
  85. char *key, *value;
  86. while ((r = parse_line_from_file(line, sizeof(line), f, &key, &value)) > 0) {
  87. front = config_line_prepend(front, key, value);
  88. }
  89. if (r < 0) {
  90. *result = NULL;
  91. return -1;
  92. } else {
  93. *result = front;
  94. return 0;
  95. }
  96. }
  97. /**
  98. * Free all the configuration lines on the linked list <b>front</b>.
  99. */
  100. static void
  101. config_free_lines(struct config_line_t *front)
  102. {
  103. struct config_line_t *tmp;
  104. while (front) {
  105. tmp = front;
  106. front = tmp->next;
  107. tor_free(tmp->key);
  108. tor_free(tmp->value);
  109. tor_free(tmp);
  110. }
  111. }
  112. /** Search the linked list <b>c</b> for any option whose key is <b>key</b>.
  113. * If such an option is found, interpret it as of type <b>type</b>, and store
  114. * the result in <b>arg</b>. If the option is misformatted, log a warning and
  115. * skip it.
  116. */
  117. static int
  118. config_compare(struct config_line_t *c, const char *key,
  119. config_type_t type, void *arg)
  120. {
  121. int i, ok;
  122. if (strncasecmp(c->key, key, strlen(c->key)))
  123. return 0;
  124. if (strcasecmp(c->key, key)) {
  125. tor_free(c->key);
  126. c->key = tor_strdup(key);
  127. }
  128. /* it's a match. cast and assign. */
  129. log_fn(LOG_DEBUG, "Recognized keyword '%s' as %s, using value '%s'.",
  130. c->key, key, c->value);
  131. switch(type) {
  132. case CONFIG_TYPE_UINT:
  133. i = tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
  134. if (!ok) {
  135. log(LOG_WARN, "Int keyword '%s %s' is malformed or out of bounds. Skipping.",
  136. c->key,c->value);
  137. return 0;
  138. }
  139. *(int *)arg = i;
  140. break;
  141. case CONFIG_TYPE_BOOL:
  142. i = tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
  143. if (!ok) {
  144. log(LOG_WARN, "Boolean keyword '%s' expects 0 or 1. Skipping.", c->key);
  145. return 0;
  146. }
  147. *(int *)arg = i;
  148. break;
  149. case CONFIG_TYPE_STRING:
  150. tor_free(*(char **)arg);
  151. *(char **)arg = tor_strdup(c->value);
  152. break;
  153. case CONFIG_TYPE_DOUBLE:
  154. *(double *)arg = atof(c->value);
  155. break;
  156. case CONFIG_TYPE_CSV:
  157. if (*(smartlist_t**)arg == NULL)
  158. *(smartlist_t**)arg = smartlist_create();
  159. smartlist_split_string(*(smartlist_t**)arg, c->value, ",",
  160. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  161. break;
  162. case CONFIG_TYPE_LINELIST:
  163. /* Note: this reverses the order that the lines appear in. That's
  164. * just fine, since we build up the list of lines reversed in the
  165. * first place. */
  166. *(struct config_line_t**)arg =
  167. config_line_prepend(*(struct config_line_t**)arg, c->key, c->value);
  168. break;
  169. case CONFIG_TYPE_OBSOLETE:
  170. log_fn(LOG_WARN, "Skipping obsolete configuration option '%s'", c->key);
  171. break;
  172. }
  173. return 1;
  174. }
  175. /** Iterate through the linked list of options <b>list</b>.
  176. * For each item, convert as appropriate and assign to <b>options</b>.
  177. * If an item is unrecognized, return -1 immediately,
  178. * else return 0 for success. */
  179. static int
  180. config_assign(or_options_t *options, struct config_line_t *list)
  181. {
  182. while (list) {
  183. if (
  184. /* order matters here! abbreviated arguments use the first match. */
  185. /* string options */
  186. config_compare(list, "Address", CONFIG_TYPE_STRING, &options->Address) ||
  187. config_compare(list, "AllowUnverifiedNodes", CONFIG_TYPE_CSV, &options->AllowUnverifiedNodes) ||
  188. config_compare(list, "AuthoritativeDirectory",CONFIG_TYPE_BOOL, &options->AuthoritativeDir) ||
  189. config_compare(list, "BandwidthRate", CONFIG_TYPE_UINT, &options->BandwidthRate) ||
  190. config_compare(list, "BandwidthBurst", CONFIG_TYPE_UINT, &options->BandwidthBurst) ||
  191. config_compare(list, "ClientOnly", CONFIG_TYPE_BOOL, &options->ClientOnly) ||
  192. config_compare(list, "ContactInfo", CONFIG_TYPE_STRING, &options->ContactInfo) ||
  193. config_compare(list, "DebugLogFile", CONFIG_TYPE_STRING, &options->DebugLogFile) ||
  194. config_compare(list, "DataDirectory", CONFIG_TYPE_STRING, &options->DataDirectory) ||
  195. config_compare(list, "DirPort", CONFIG_TYPE_UINT, &options->DirPort) ||
  196. config_compare(list, "DirBindAddress", CONFIG_TYPE_LINELIST, &options->DirBindAddress) ||
  197. config_compare(list, "DirFetchPostPeriod",CONFIG_TYPE_UINT, &options->DirFetchPostPeriod) ||
  198. config_compare(list, "DirServer", CONFIG_TYPE_LINELIST, &options->DirServers) ||
  199. config_compare(list, "ExitNodes", CONFIG_TYPE_STRING, &options->ExitNodes) ||
  200. config_compare(list, "EntryNodes", CONFIG_TYPE_STRING, &options->EntryNodes) ||
  201. config_compare(list, "StrictExitNodes", CONFIG_TYPE_BOOL, &options->StrictExitNodes) ||
  202. config_compare(list, "StrictEntryNodes", CONFIG_TYPE_BOOL, &options->StrictEntryNodes) ||
  203. config_compare(list, "ExitPolicy", CONFIG_TYPE_LINELIST, &options->ExitPolicy) ||
  204. config_compare(list, "ExcludeNodes", CONFIG_TYPE_STRING, &options->ExcludeNodes) ||
  205. config_compare(list, "FascistFirewall",CONFIG_TYPE_BOOL, &options->FascistFirewall) ||
  206. config_compare(list, "FirewallPorts",CONFIG_TYPE_CSV, &options->FirewallPorts) ||
  207. config_compare(list, "MyFamily", CONFIG_TYPE_STRING, &options->MyFamily) ||
  208. config_compare(list, "Group", CONFIG_TYPE_STRING, &options->Group) ||
  209. config_compare(list, "HttpProxy", CONFIG_TYPE_STRING, &options->HttpProxy) ||
  210. config_compare(list, "HiddenServiceDir", CONFIG_TYPE_LINELIST, &options->RendConfigLines)||
  211. config_compare(list, "HiddenServicePort", CONFIG_TYPE_LINELIST, &options->RendConfigLines)||
  212. config_compare(list, "HiddenServiceNodes", CONFIG_TYPE_LINELIST, &options->RendConfigLines)||
  213. config_compare(list, "HiddenServiceExcludeNodes", CONFIG_TYPE_LINELIST, &options->RendConfigLines)||
  214. config_compare(list, "IgnoreVersion", CONFIG_TYPE_BOOL, &options->IgnoreVersion) ||
  215. config_compare(list, "KeepalivePeriod",CONFIG_TYPE_UINT, &options->KeepalivePeriod) ||
  216. config_compare(list, "LogLevel", CONFIG_TYPE_LINELIST, &options->LogOptions) ||
  217. config_compare(list, "LogFile", CONFIG_TYPE_LINELIST, &options->LogOptions) ||
  218. config_compare(list, "LinkPadding", CONFIG_TYPE_OBSOLETE, NULL) ||
  219. config_compare(list, "MaxConn", CONFIG_TYPE_UINT, &options->MaxConn) ||
  220. config_compare(list, "MaxOnionsPending",CONFIG_TYPE_UINT, &options->MaxOnionsPending) ||
  221. config_compare(list, "Nickname", CONFIG_TYPE_STRING, &options->Nickname) ||
  222. config_compare(list, "NewCircuitPeriod",CONFIG_TYPE_UINT, &options->NewCircuitPeriod) ||
  223. config_compare(list, "NumCpus", CONFIG_TYPE_UINT, &options->NumCpus) ||
  224. config_compare(list, "ORPort", CONFIG_TYPE_UINT, &options->ORPort) ||
  225. config_compare(list, "ORBindAddress", CONFIG_TYPE_LINELIST, &options->ORBindAddress) ||
  226. config_compare(list, "OutboundBindAddress",CONFIG_TYPE_STRING, &options->OutboundBindAddress) ||
  227. config_compare(list, "PidFile", CONFIG_TYPE_STRING, &options->PidFile) ||
  228. config_compare(list, "PathlenCoinWeight",CONFIG_TYPE_DOUBLE, &options->PathlenCoinWeight) ||
  229. config_compare(list, "RouterFile", CONFIG_TYPE_STRING, &options->RouterFile) ||
  230. config_compare(list, "RunAsDaemon", CONFIG_TYPE_BOOL, &options->RunAsDaemon) ||
  231. config_compare(list, "RunTesting", CONFIG_TYPE_BOOL, &options->RunTesting) ||
  232. config_compare(list, "RecommendedVersions",CONFIG_TYPE_LINELIST, &options->RecommendedVersions) ||
  233. config_compare(list, "RendNodes", CONFIG_TYPE_STRING, &options->RendNodes) ||
  234. config_compare(list, "RendExcludeNodes",CONFIG_TYPE_STRING, &options->RendExcludeNodes) ||
  235. config_compare(list, "SocksPort", CONFIG_TYPE_UINT, &options->SocksPort) ||
  236. config_compare(list, "SocksBindAddress",CONFIG_TYPE_LINELIST,&options->SocksBindAddress) ||
  237. config_compare(list, "SocksPolicy", CONFIG_TYPE_LINELIST,&options->SocksPolicy) ||
  238. config_compare(list, "TrafficShaping", CONFIG_TYPE_OBSOLETE, NULL) ||
  239. config_compare(list, "User", CONFIG_TYPE_STRING, &options->User)
  240. ) {
  241. /* then we're ok. it matched something. */
  242. } else {
  243. log_fn(LOG_WARN,"Unknown keyword '%s'. Failing.",list->key);
  244. return -1;
  245. }
  246. list = list->next;
  247. }
  248. return 0;
  249. }
  250. static void
  251. add_default_trusted_dirservers(void)
  252. {
  253. /* moria1 */
  254. parse_dir_server_line("18.244.0.188:9031 "
  255. "FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
  256. /* moria2 */
  257. parse_dir_server_line("18.244.0.114:80 "
  258. "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF");
  259. /* tor26 */
  260. parse_dir_server_line("62.116.124.106:9030 "
  261. "847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
  262. }
  263. /** Set <b>options</b> to a reasonable default.
  264. *
  265. * Call this function before we parse the torrc file.
  266. */
  267. static int
  268. config_assign_defaults(or_options_t *options)
  269. {
  270. /* set them up as a client only */
  271. options->SocksPort = 9050;
  272. options->AllowUnverifiedNodes = smartlist_create();
  273. smartlist_add(options->AllowUnverifiedNodes, "middle");
  274. smartlist_add(options->AllowUnverifiedNodes, "rendezvous");
  275. config_free_lines(options->ExitPolicy);
  276. options->ExitPolicy = NULL;
  277. return 0;
  278. }
  279. /** Print a usage message for tor. */
  280. static void
  281. print_usage(void)
  282. {
  283. printf("tor -f <torrc> [args]\n"
  284. "See man page for more options. This -h is probably obsolete.\n\n"
  285. "-b <bandwidth>\t\tbytes/second rate limiting\n"
  286. "-d <file>\t\tDebug file\n"
  287. // "-m <max>\t\tMax number of connections\n"
  288. "-l <level>\t\tLog level\n"
  289. "-r <file>\t\tList of known routers\n");
  290. printf("\nClient options:\n"
  291. "-e \"nick1 nick2 ...\"\t\tExit nodes\n"
  292. "-s <IP>\t\t\tPort to bind to for Socks\n");
  293. printf("\nServer options:\n"
  294. "-n <nick>\t\tNickname of router\n"
  295. "-o <port>\t\tOR port to bind to\n"
  296. "-p <file>\t\tPID file\n");
  297. }
  298. /**
  299. * Based on <b>address</b>, guess our public IP address and put it
  300. * in <b>addr</b>.
  301. */
  302. int
  303. resolve_my_address(const char *address, uint32_t *addr)
  304. {
  305. struct in_addr in;
  306. struct hostent *rent;
  307. char hostname[256];
  308. int explicit_ip=1;
  309. tor_assert(addr);
  310. if (address) {
  311. strlcpy(hostname, address, sizeof(hostname));
  312. } else { /* then we need to guess our address */
  313. explicit_ip = 0; /* it's implicit */
  314. if (gethostname(hostname, sizeof(hostname)) < 0) {
  315. log_fn(LOG_WARN,"Error obtaining local hostname");
  316. return -1;
  317. }
  318. log_fn(LOG_DEBUG,"Guessed local host name as '%s'",hostname);
  319. }
  320. /* now we know hostname. resolve it and keep only the IP */
  321. if (tor_inet_aton(hostname, &in) == 0) {
  322. /* then we have to resolve it */
  323. explicit_ip = 0;
  324. rent = (struct hostent *)gethostbyname(hostname);
  325. if (!rent) {
  326. log_fn(LOG_WARN,"Could not resolve local Address %s. Failing.", hostname);
  327. return -1;
  328. }
  329. tor_assert(rent->h_length == 4);
  330. memcpy(&in.s_addr, rent->h_addr, rent->h_length);
  331. }
  332. if (!explicit_ip && is_internal_IP(htonl(in.s_addr))) {
  333. log_fn(LOG_WARN,"Address '%s' resolves to private IP '%s'. "
  334. "Please set the Address config option to be the IP you want to use.",
  335. hostname, inet_ntoa(in));
  336. return -1;
  337. }
  338. log_fn(LOG_DEBUG, "Resolved Address to %s.", inet_ntoa(in));
  339. *addr = ntohl(in.s_addr);
  340. return 0;
  341. }
  342. static char *
  343. get_default_nickname(void)
  344. {
  345. char localhostname[256];
  346. char *cp, *out, *outp;
  347. if (gethostname(localhostname, sizeof(localhostname)) < 0) {
  348. log_fn(LOG_WARN,"Error obtaining local hostname");
  349. return NULL;
  350. }
  351. /* Put it in lowercase; stop at the first dot. */
  352. for (cp = localhostname; *cp; ++cp) {
  353. if (*cp == '.') {
  354. *cp = '\0';
  355. break;
  356. }
  357. *cp = tolower(*cp);
  358. }
  359. /* Strip invalid characters. */
  360. cp = localhostname;
  361. out = outp = tor_malloc(strlen(localhostname) + 1);
  362. while (*cp) {
  363. if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
  364. *outp++ = *cp++;
  365. else
  366. cp++;
  367. }
  368. *outp = '\0';
  369. /* Enforce length. */
  370. if (strlen(out) > MAX_NICKNAME_LEN)
  371. out[MAX_NICKNAME_LEN]='\0';
  372. return out;
  373. }
  374. /** Release storage held by <b>options</b> */
  375. static void
  376. free_options(or_options_t *options)
  377. {
  378. config_free_lines(options->LogOptions);
  379. tor_free(options->ContactInfo);
  380. tor_free(options->DebugLogFile);
  381. tor_free(options->DataDirectory);
  382. tor_free(options->RouterFile);
  383. tor_free(options->Nickname);
  384. tor_free(options->Address);
  385. tor_free(options->PidFile);
  386. tor_free(options->ExitNodes);
  387. tor_free(options->EntryNodes);
  388. tor_free(options->ExcludeNodes);
  389. tor_free(options->RendNodes);
  390. tor_free(options->RendExcludeNodes);
  391. tor_free(options->OutboundBindAddress);
  392. tor_free(options->User);
  393. tor_free(options->Group);
  394. tor_free(options->HttpProxy);
  395. config_free_lines(options->RendConfigLines);
  396. config_free_lines(options->SocksBindAddress);
  397. config_free_lines(options->ORBindAddress);
  398. config_free_lines(options->DirBindAddress);
  399. config_free_lines(options->ExitPolicy);
  400. config_free_lines(options->SocksPolicy);
  401. config_free_lines(options->DirServers);
  402. config_free_lines(options->RecommendedVersions);
  403. if (options->FirewallPorts) {
  404. SMARTLIST_FOREACH(options->FirewallPorts, char *, cp, tor_free(cp));
  405. smartlist_free(options->FirewallPorts);
  406. options->FirewallPorts = NULL;
  407. }
  408. }
  409. /** Set <b>options</b> to hold reasonable defaults for most options.
  410. * Each option defaults to zero. */
  411. static void
  412. init_options(or_options_t *options)
  413. {
  414. memset(options,0,sizeof(or_options_t));
  415. options->LogOptions = NULL;
  416. options->ExitNodes = tor_strdup("");
  417. options->EntryNodes = tor_strdup("");
  418. options->StrictEntryNodes = options->StrictExitNodes = 0;
  419. options->ExcludeNodes = tor_strdup("");
  420. options->RendNodes = tor_strdup("");
  421. options->RendExcludeNodes = tor_strdup("");
  422. options->ExitPolicy = NULL;
  423. options->SocksPolicy = NULL;
  424. options->SocksBindAddress = NULL;
  425. options->ORBindAddress = NULL;
  426. options->DirBindAddress = NULL;
  427. options->OutboundBindAddress = NULL;
  428. options->RecommendedVersions = NULL;
  429. options->PidFile = NULL; // tor_strdup("tor.pid");
  430. options->DataDirectory = NULL;
  431. options->PathlenCoinWeight = 0.3;
  432. options->MaxConn = 900;
  433. options->DirFetchPostPeriod = 600;
  434. options->KeepalivePeriod = 300;
  435. options->MaxOnionsPending = 100;
  436. options->NewCircuitPeriod = 30; /* twice a minute */
  437. options->BandwidthRate = 800000; /* at most 800kB/s total sustained incoming */
  438. options->BandwidthBurst = 10000000; /* max burst on the token bucket */
  439. options->NumCpus = 1;
  440. options->RendConfigLines = NULL;
  441. options->FirewallPorts = NULL;
  442. options->DirServers = NULL;
  443. options->MyFamily = NULL;
  444. }
  445. static char *
  446. get_default_conf_file(void)
  447. {
  448. #ifdef MS_WINDOWS
  449. LPITEMIDLIST idl;
  450. IMalloc *m;
  451. HRESULT result;
  452. char *path = tor_malloc(MAX_PATH);
  453. /* Find X:\documents and settings\username\applicatation data\ .
  454. * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
  455. */
  456. if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
  457. &idl))) {
  458. tor_free(path);
  459. return NULL;
  460. }
  461. /* Convert the path from an "ID List" (whatever that is!) to a path. */
  462. result = SHGetPathFromIDList(idl, path);
  463. /* Now we need to free the */
  464. SHGetMalloc(&m);
  465. if (m) {
  466. m->lpVtbl->Free(m, idl);
  467. m->lpVtbl->Release(m);
  468. }
  469. if (!SUCCEEDED(result)) {
  470. tor_free(path);
  471. return NULL;
  472. }
  473. strlcat(path,"\\tor\\torrc",MAX_PATH);
  474. return path;
  475. #else
  476. return tor_strdup(CONFDIR "/torrc");
  477. #endif
  478. }
  479. /** Verify whether lst is a string containing valid-looking space-separated
  480. * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
  481. */
  482. static int check_nickname_list(const char *lst, const char *name)
  483. {
  484. int r = 0;
  485. smartlist_t *sl;
  486. if (!lst)
  487. return 0;
  488. sl = smartlist_create();
  489. smartlist_split_string(sl, lst, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  490. SMARTLIST_FOREACH(sl, const char *, s,
  491. {
  492. if (!is_legal_nickname_or_hexdigest(s)) {
  493. log_fn(LOG_WARN, "Invalid nickname '%s' in %s line", s, name);
  494. r = -1;
  495. }
  496. });
  497. SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
  498. smartlist_free(sl);
  499. return r;
  500. }
  501. /** Read a configuration file into <b>options</b>, finding the configuration
  502. * file location based on the command line. After loading the options,
  503. * validate them for consistency. Return 0 if success, <0 if failure. */
  504. int
  505. getconfig(int argc, char **argv, or_options_t *options)
  506. {
  507. struct config_line_t *cl;
  508. FILE *cf;
  509. char *fname;
  510. int i;
  511. int result = 0;
  512. static int first_load = 1;
  513. static char **backup_argv;
  514. static int backup_argc;
  515. char *previous_pidfile = NULL;
  516. int previous_runasdaemon = 0;
  517. int previous_orport = -1;
  518. int using_default_torrc;
  519. if (first_load) { /* first time we're called. save commandline args */
  520. backup_argv = argv;
  521. backup_argc = argc;
  522. first_load = 0;
  523. } else { /* we're reloading. need to clean up old ones first. */
  524. argv = backup_argv;
  525. argc = backup_argc;
  526. /* record some previous values, so we can fail if they change */
  527. if (options->PidFile)
  528. previous_pidfile = tor_strdup(options->PidFile);
  529. previous_runasdaemon = options->RunAsDaemon;
  530. previous_orport = options->ORPort;
  531. free_options(options);
  532. }
  533. init_options(options);
  534. if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
  535. print_usage();
  536. exit(0);
  537. }
  538. if (argc > 1 && (!strcmp(argv[1],"--version"))) {
  539. printf("Tor version %s.\n",VERSION);
  540. exit(0);
  541. }
  542. /* learn config file name, get config lines, assign them */
  543. i = 1;
  544. while (i < argc-1 && strcmp(argv[i],"-f")) {
  545. i++;
  546. }
  547. if (i < argc-1) { /* we found one */
  548. fname = tor_strdup(argv[i+1]);
  549. using_default_torrc = 0;
  550. } else {
  551. /* didn't find one, try CONFDIR */
  552. char *fn;
  553. using_default_torrc = 1;
  554. fn = get_default_conf_file();
  555. if (fn && file_status(fn) == FN_FILE) {
  556. fname = fn;
  557. } else {
  558. tor_free(fn);
  559. fn = expand_filename("~/.torrc");
  560. if (fn && file_status(fn) == FN_FILE) {
  561. fname = fn;
  562. } else {
  563. tor_free(fn);
  564. fname = get_default_conf_file();
  565. }
  566. }
  567. }
  568. tor_assert(fname);
  569. log(LOG_DEBUG, "Opening config file '%s'", fname);
  570. if (config_assign_defaults(options) < 0) {
  571. return -1;
  572. }
  573. cf = fopen(fname, "r");
  574. if (!cf) {
  575. if (using_default_torrc == 1) {
  576. log(LOG_NOTICE, "Configuration file '%s' not present, "
  577. "using reasonable defaults.", fname);
  578. tor_free(fname);
  579. } else {
  580. log(LOG_WARN, "Unable to open configuration file '%s'.", fname);
  581. tor_free(fname);
  582. return -1;
  583. }
  584. } else { /* it opened successfully. use it. */
  585. tor_free(fname);
  586. if (config_get_lines(cf, &cl)<0)
  587. return -1;
  588. if (config_assign(options,cl) < 0)
  589. return -1;
  590. config_free_lines(cl);
  591. fclose(cf);
  592. }
  593. /* go through command-line variables too */
  594. cl = config_get_commandlines(argc,argv);
  595. if (config_assign(options,cl) < 0)
  596. return -1;
  597. config_free_lines(cl);
  598. /* Validate options */
  599. /* first check if any of the previous options have changed but aren't allowed to */
  600. if (previous_pidfile && strcmp(previous_pidfile,options->PidFile)) {
  601. log_fn(LOG_WARN,"During reload, PidFile changed from %s to %s. Failing.",
  602. previous_pidfile, options->PidFile);
  603. return -1;
  604. }
  605. tor_free(previous_pidfile);
  606. if (previous_runasdaemon && !options->RunAsDaemon) {
  607. log_fn(LOG_WARN,"During reload, change from RunAsDaemon=1 to =0 not allowed. Failing.");
  608. return -1;
  609. }
  610. if (previous_orport == 0 && options->ORPort > 0) {
  611. log_fn(LOG_WARN,"During reload, change from ORPort=0 to >0 not allowed. Failing.");
  612. return -1;
  613. }
  614. if (options->ORPort < 0 || options->ORPort > 65535) {
  615. log(LOG_WARN, "ORPort option out of bounds.");
  616. result = -1;
  617. }
  618. if (options->Nickname == NULL) {
  619. if (server_mode()) {
  620. if (!(options->Nickname = get_default_nickname()))
  621. return -1;
  622. log_fn(LOG_NOTICE, "Choosing default nickname %s", options->Nickname);
  623. }
  624. } else {
  625. if (strspn(options->Nickname, LEGAL_NICKNAME_CHARACTERS) !=
  626. strlen(options->Nickname)) {
  627. log_fn(LOG_WARN, "Nickname '%s' contains illegal characters.", options->Nickname);
  628. result = -1;
  629. }
  630. if (strlen(options->Nickname) == 0) {
  631. log_fn(LOG_WARN, "Nickname must have at least one character");
  632. result = -1;
  633. }
  634. if (strlen(options->Nickname) > MAX_NICKNAME_LEN) {
  635. log_fn(LOG_WARN, "Nickname '%s' has more than %d characters.",
  636. options->Nickname, MAX_NICKNAME_LEN);
  637. result = -1;
  638. }
  639. }
  640. if (server_mode()) {
  641. /* confirm that our address isn't broken, so we can complain now */
  642. uint32_t tmp;
  643. if (resolve_my_address(options->Address, &tmp) < 0)
  644. result = -1;
  645. }
  646. if (options->SocksPort < 0 || options->SocksPort > 65535) {
  647. log(LOG_WARN, "SocksPort option out of bounds.");
  648. result = -1;
  649. }
  650. if (options->SocksPort == 0 && options->ORPort == 0) {
  651. log(LOG_WARN, "SocksPort and ORPort are both undefined? Quitting.");
  652. result = -1;
  653. }
  654. if (options->DirPort < 0 || options->DirPort > 65535) {
  655. log(LOG_WARN, "DirPort option out of bounds.");
  656. result = -1;
  657. }
  658. if (options->StrictExitNodes && !strlen(options->ExitNodes)) {
  659. log(LOG_WARN, "StrictExitNodes set, but no ExitNodes listed.");
  660. }
  661. if (options->StrictEntryNodes && !strlen(options->EntryNodes)) {
  662. log(LOG_WARN, "StrictEntryNodes set, but no EntryNodes listed.");
  663. }
  664. if (options->AuthoritativeDir && options->RecommendedVersions == NULL) {
  665. log(LOG_WARN, "Directory servers must configure RecommendedVersions.");
  666. result = -1;
  667. }
  668. if (options->AuthoritativeDir && !options->DirPort) {
  669. log(LOG_WARN, "Running as authoritative directory, but no DirPort set.");
  670. result = -1;
  671. }
  672. if (options->AuthoritativeDir && !options->ORPort) {
  673. log(LOG_WARN, "Running as authoritative directory, but no ORPort set.");
  674. result = -1;
  675. }
  676. if (options->AuthoritativeDir && options->ClientOnly) {
  677. log(LOG_WARN, "Running as authoritative directory, but ClientOnly also set.");
  678. result = -1;
  679. }
  680. if (options->FascistFirewall && !options->FirewallPorts) {
  681. options->FirewallPorts = smartlist_create();
  682. smartlist_add(options->FirewallPorts, tor_strdup("80"));
  683. smartlist_add(options->FirewallPorts, tor_strdup("443"));
  684. }
  685. if (options->FirewallPorts) {
  686. SMARTLIST_FOREACH(options->FirewallPorts, const char *, cp,
  687. {
  688. i = atoi(cp);
  689. if (i < 1 || i > 65535) {
  690. log(LOG_WARN, "Port '%s' out of range in FirewallPorts", cp);
  691. result=-1;
  692. }
  693. });
  694. }
  695. options->_AllowUnverified = 0;
  696. if (options->AllowUnverifiedNodes) {
  697. SMARTLIST_FOREACH(options->AllowUnverifiedNodes, const char *, cp, {
  698. if (!strcasecmp(cp, "entry"))
  699. options->_AllowUnverified |= ALLOW_UNVERIFIED_ENTRY;
  700. else if (!strcasecmp(cp, "exit"))
  701. options->_AllowUnverified |= ALLOW_UNVERIFIED_EXIT;
  702. else if (!strcasecmp(cp, "middle"))
  703. options->_AllowUnverified |= ALLOW_UNVERIFIED_MIDDLE;
  704. else if (!strcasecmp(cp, "introduction"))
  705. options->_AllowUnverified |= ALLOW_UNVERIFIED_INTRODUCTION;
  706. else if (!strcasecmp(cp, "rendezvous"))
  707. options->_AllowUnverified |= ALLOW_UNVERIFIED_RENDEZVOUS;
  708. else {
  709. log(LOG_WARN, "Unrecognized value '%s' in AllowUnverifiedNodes",
  710. cp);
  711. result=-1;
  712. }
  713. });
  714. }
  715. if (options->SocksPort >= 1 &&
  716. (options->PathlenCoinWeight < 0.0 || options->PathlenCoinWeight >= 1.0)) {
  717. log(LOG_WARN, "PathlenCoinWeight option must be >=0.0 and <1.0.");
  718. result = -1;
  719. }
  720. if (options->MaxConn < 1) {
  721. log(LOG_WARN, "MaxConn option must be a non-zero positive integer.");
  722. result = -1;
  723. }
  724. if (options->MaxConn >= MAXCONNECTIONS) {
  725. log(LOG_WARN, "MaxConn option must be less than %d.", MAXCONNECTIONS);
  726. result = -1;
  727. }
  728. #define MIN_DIRFETCHPOSTPERIOD 60
  729. if (options->DirFetchPostPeriod < MIN_DIRFETCHPOSTPERIOD) {
  730. log(LOG_WARN, "DirFetchPostPeriod option must be at least %d.", MIN_DIRFETCHPOSTPERIOD);
  731. result = -1;
  732. }
  733. if (options->DirFetchPostPeriod > MIN_ONION_KEY_LIFETIME / 2) {
  734. log(LOG_WARN, "DirFetchPostPeriod is too large; clipping.");
  735. options->DirFetchPostPeriod = MIN_ONION_KEY_LIFETIME / 2;
  736. }
  737. if (options->KeepalivePeriod < 1) {
  738. log(LOG_WARN,"KeepalivePeriod option must be positive.");
  739. result = -1;
  740. }
  741. if (options->HttpProxy) { /* parse it now */
  742. if (parse_addr_port(options->HttpProxy, NULL,
  743. &options->HttpProxyAddr, &options->HttpProxyPort) < 0) {
  744. log(LOG_WARN,"HttpProxy failed to parse or resolve. Please fix.");
  745. result = -1;
  746. }
  747. options->HttpProxyAddr = ntohl(options->HttpProxyAddr); /* switch to host-order */
  748. if (options->HttpProxyPort == 0) { /* give it a default */
  749. options->HttpProxyPort = 80;
  750. }
  751. }
  752. if (check_nickname_list(options->ExitNodes, "ExitNodes"))
  753. return -1;
  754. if (check_nickname_list(options->EntryNodes, "EntryNodes"))
  755. return -1;
  756. if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes"))
  757. return -1;
  758. if (check_nickname_list(options->RendNodes, "RendNodes"))
  759. return -1;
  760. if (check_nickname_list(options->RendNodes, "RendExcludeNodes"))
  761. return -1;
  762. if (check_nickname_list(options->MyFamily, "MyFamily"))
  763. return -1;
  764. clear_trusted_dir_servers();
  765. if (!options->DirServers) {
  766. add_default_trusted_dirservers();
  767. } else {
  768. for (cl = options->DirServers; cl; cl = cl->next) {
  769. if (parse_dir_server_line(cl->value)<0)
  770. return -1;
  771. }
  772. }
  773. if (rend_config_services(options) < 0) {
  774. result = -1;
  775. }
  776. return result;
  777. }
  778. static int
  779. add_single_log(struct config_line_t *level_opt,
  780. struct config_line_t *file_opt, int isDaemon)
  781. {
  782. int levelMin = -1, levelMax = -1;
  783. char *cp, *tmp_sev;
  784. if (level_opt) {
  785. cp = strchr(level_opt->value, '-');
  786. if (cp) {
  787. tmp_sev = tor_strndup(level_opt->value, cp - level_opt->value);
  788. levelMin = parse_log_level(tmp_sev);
  789. if (levelMin < 0) {
  790. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  791. "err|warn|notice|info|debug", tmp_sev);
  792. return -1;
  793. }
  794. tor_free(tmp_sev);
  795. levelMax = parse_log_level(cp+1);
  796. if (levelMax < 0) {
  797. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  798. "err|warn|notice|info|debug", cp+1);
  799. return -1;
  800. }
  801. } else {
  802. levelMin = parse_log_level(level_opt->value);
  803. if (levelMin < 0) {
  804. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  805. "err|warn|notice|info|debug", level_opt->value);
  806. return -1;
  807. }
  808. }
  809. }
  810. if (levelMin < 0 && levelMax < 0) {
  811. levelMin = LOG_NOTICE;
  812. levelMax = LOG_ERR;
  813. } else if (levelMin < 0) {
  814. levelMin = levelMax;
  815. } else {
  816. levelMax = LOG_ERR;
  817. }
  818. if (file_opt) {
  819. if (add_file_log(levelMin, levelMax, file_opt->value) < 0) {
  820. log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", file_opt->value,
  821. strerror(errno));
  822. return -1;
  823. }
  824. log_fn(LOG_NOTICE, "Successfully opened LogFile '%s', redirecting output.",
  825. file_opt->value);
  826. } else if (!isDaemon) {
  827. add_stream_log(levelMin, levelMax, "<stdout>", stdout);
  828. close_temp_logs();
  829. }
  830. return 0;
  831. }
  832. /**
  833. * Initialize the logs based on the configuration file.
  834. */
  835. int
  836. config_init_logs(or_options_t *options)
  837. {
  838. /* The order of options is: Level? (File Level?)+
  839. */
  840. struct config_line_t *opt = options->LogOptions;
  841. /* Special case if no options are given. */
  842. if (!opt) {
  843. add_stream_log(LOG_NOTICE, LOG_ERR, "<stdout>", stdout);
  844. close_temp_logs();
  845. /* don't return yet, in case we want to do a debuglogfile below */
  846. }
  847. /* Special case for if first option is LogLevel. */
  848. if (opt && !strcasecmp(opt->key, "LogLevel")) {
  849. if (opt->next && !strcasecmp(opt->next->key, "LogFile")) {
  850. if (add_single_log(opt, opt->next, options->RunAsDaemon) < 0)
  851. return -1;
  852. opt = opt->next->next;
  853. } else if (!opt->next) {
  854. if (add_single_log(opt, NULL, options->RunAsDaemon) < 0)
  855. return -1;
  856. opt = opt->next;
  857. } else {
  858. ; /* give warning below */
  859. }
  860. }
  861. while (opt) {
  862. if (!strcasecmp(opt->key, "LogLevel")) {
  863. log_fn(LOG_WARN, "Two LogLevel options in a row without intervening LogFile");
  864. opt = opt->next;
  865. } else {
  866. tor_assert(!strcasecmp(opt->key, "LogFile"));
  867. if (opt->next && !strcasecmp(opt->next->key, "LogLevel")) {
  868. /* LogFile followed by LogLevel */
  869. if (add_single_log(opt->next, opt, options->RunAsDaemon) < 0)
  870. return -1;
  871. opt = opt->next->next;
  872. } else {
  873. /* LogFile followed by LogFile or end of list. */
  874. if (add_single_log(NULL, opt, options->RunAsDaemon) < 0)
  875. return -1;
  876. opt = opt->next;
  877. }
  878. }
  879. }
  880. if (options->DebugLogFile) {
  881. log_fn(LOG_WARN, "DebugLogFile is deprecated; use LogFile and LogLevel instead");
  882. if (add_file_log(LOG_DEBUG, LOG_ERR, options->DebugLogFile) < 0)
  883. return -1;
  884. }
  885. return 0;
  886. }
  887. /**
  888. * Given a linked list of config lines containing "allow" and "deny" tokens,
  889. * parse them and place the result in <b>dest</b>. Skip malformed lines.
  890. */
  891. void
  892. config_parse_exit_policy(struct config_line_t *cfg,
  893. struct exit_policy_t **dest)
  894. {
  895. struct exit_policy_t **nextp;
  896. smartlist_t *entries;
  897. if (!cfg)
  898. return;
  899. nextp = dest;
  900. while (*nextp)
  901. nextp = &((*nextp)->next);
  902. entries = smartlist_create();
  903. for (; cfg; cfg = cfg->next) {
  904. smartlist_split_string(entries, cfg->value, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  905. SMARTLIST_FOREACH(entries, const char *, ent,
  906. {
  907. log_fn(LOG_DEBUG,"Adding new entry '%s'",ent);
  908. *nextp = router_parse_exit_policy_from_string(ent);
  909. if (*nextp) {
  910. nextp = &((*nextp)->next);
  911. } else {
  912. log_fn(LOG_WARN,"Malformed exit policy %s; skipping.", ent);
  913. }
  914. });
  915. SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
  916. smartlist_clear(entries);
  917. }
  918. smartlist_free(entries);
  919. }
  920. void exit_policy_free(struct exit_policy_t *p) {
  921. struct exit_policy_t *e;
  922. while (p) {
  923. e = p;
  924. p = p->next;
  925. tor_free(e->string);
  926. tor_free(e);
  927. }
  928. }
  929. static int parse_dir_server_line(const char *line)
  930. {
  931. smartlist_t *items = NULL;
  932. int r;
  933. char *addrport, *address=NULL;
  934. uint16_t port;
  935. char digest[DIGEST_LEN];
  936. items = smartlist_create();
  937. smartlist_split_string(items, line, " ",
  938. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  939. if (smartlist_len(items) < 2) {
  940. log_fn(LOG_WARN, "Too few arguments to DirServer line.");
  941. goto err;
  942. }
  943. addrport = smartlist_get(items, 0);
  944. if (parse_addr_port(addrport, &address, NULL, &port)<0) {
  945. log_fn(LOG_WARN, "Error parsing DirServer address '%s'", addrport);
  946. goto err;
  947. }
  948. if (!port) {
  949. log_fn(LOG_WARN, "Missing port in DirServe address '%s'",addrport);
  950. goto err;
  951. }
  952. tor_strstrip(smartlist_get(items, 1), " ");
  953. if (strlen(smartlist_get(items, 1)) != HEX_DIGEST_LEN) {
  954. log_fn(LOG_WARN, "Key digest for DirServer is wrong length.");
  955. goto err;
  956. }
  957. if (base16_decode(digest, DIGEST_LEN,
  958. smartlist_get(items,1), HEX_DIGEST_LEN)<0) {
  959. log_fn(LOG_WARN, "Unable to decode DirServer key digest.");
  960. goto err;
  961. }
  962. log_fn(LOG_DEBUG, "Trusted dirserver at %s:%d (%s)", address, (int)port,
  963. (char*)smartlist_get(items,1));
  964. add_trusted_dir_server(address, port, digest);
  965. r = 0;
  966. goto done;
  967. err:
  968. r = -1;
  969. done:
  970. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  971. smartlist_free(items);
  972. if (address)
  973. tor_free(address);
  974. return r;
  975. }
  976. const char *
  977. get_data_directory(or_options_t *options)
  978. {
  979. const char *d;
  980. if (options->DataDirectory) {
  981. d = options->DataDirectory;
  982. } else {
  983. #ifdef MS_WINDOWS
  984. char *p;
  985. p = tor_malloc(MAX_PATH);
  986. if (!SUCCEEDED(SHGetSpecialFolderPath(NULL, p, CSIDL_APPDATA, 1))) {
  987. strlcpy(p,CONFDIR, MAX_PATH);
  988. }
  989. strlcat(p,"\\tor",MAX_PATH);
  990. options->DataDirectory = p;
  991. return p;
  992. #else
  993. d = "~/.tor";
  994. #endif
  995. }
  996. if (d && strncmp(d,"~/",2) == 0) {
  997. char *fn = expand_filename(d);
  998. if (!fn) {
  999. log_fn(LOG_ERR,"Failed to expand filename '%s'. Exiting.", d);
  1000. exit(1);
  1001. }
  1002. tor_free(options->DataDirectory);
  1003. options->DataDirectory = fn;
  1004. }
  1005. return options->DataDirectory;
  1006. }
  1007. /*
  1008. Local Variables:
  1009. mode:c
  1010. indent-tabs-mode:nil
  1011. c-basic-offset:2
  1012. End:
  1013. */