config.c 50 KB

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