config.c 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char config_c_id[] = "$Id$";
  7. /**
  8. * \file config.c
  9. *
  10. * \brief Code to parse and interpret configuration files.
  11. **/
  12. #include "or.h"
  13. #ifdef MS_WINDOWS
  14. #include <shlobj.h>
  15. #endif
  16. #include "../common/aes.h"
  17. /** Enumeration of types which option values can take */
  18. typedef enum config_type_t {
  19. CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
  20. CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
  21. CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
  22. CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
  23. CONFIG_TYPE_DOUBLE, /**< A floating-point value */
  24. CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
  25. CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and optional
  26. * whitespace. */
  27. CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
  28. CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
  29. * mixed with other keywords. */
  30. CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
  31. * context-sensitive config lines when fetching.
  32. */
  33. CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
  34. } config_type_t;
  35. /* An abbreviation for a configuration option allowed on the command line */
  36. typedef struct config_abbrev_t {
  37. const char *abbreviated;
  38. const char *full;
  39. int commandline_only;
  40. } config_abbrev_t;
  41. /* Handy macro for declaring "In the config file or on the command line,
  42. * you can abbreviate <b>tok</b>s as <b>tok</b>". */
  43. #define PLURAL(tok) { #tok, #tok "s", 0 }
  44. /* A list of command-line abbreviations. */
  45. static config_abbrev_t config_abbrevs[] = {
  46. PLURAL(ExitNode),
  47. PLURAL(EntryNode),
  48. PLURAL(ExcludeNode),
  49. PLURAL(FirewallPort),
  50. PLURAL(LongLivedPort),
  51. PLURAL(HiddenServiceNode),
  52. PLURAL(HiddenServiceExcludeNode),
  53. PLURAL(RendNode),
  54. PLURAL(RendExcludeNode),
  55. PLURAL(StrictEntryNode),
  56. PLURAL(StrictExitNode),
  57. { "l", "Log", 1},
  58. { "BandwidthRateBytes", "BandwidthRate", 0},
  59. { "BandwidthBurstBytes", "BandwidthBurst", 0},
  60. { "DirFetchPostPeriod", "StatusFetchPeriod", 0},
  61. { NULL, NULL , 0},
  62. };
  63. #undef PLURAL
  64. /** A variable allowed in the configuration file or on the command line. */
  65. typedef struct config_var_t {
  66. const char *name; /**< The full keyword (case insensitive). */
  67. config_type_t type; /**< How to interpret the type and turn it into a value. */
  68. off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
  69. const char *initvalue; /**< String (or null) describing initial value. */
  70. } config_var_t;
  71. /** Return the offset of <b>member</b> within the type <b>tp</b>, in bytes */
  72. #define STRUCT_OFFSET(tp, member) ((off_t) (((char*)&((tp*)0)->member)-(char*)0))
  73. /** An entry for config_vars: "The option <b>name</b> has type
  74. * CONFIG_TYPE_<b>conftype</b>, and corresponds to
  75. * or_options_t.<b>member</b>"
  76. */
  77. #define VAR(name,conftype,member,initvalue) \
  78. { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), initvalue }
  79. /** An entry for config_vars: "The option <b>name</b> is obsolete." */
  80. #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
  81. /** Array of configuration options. Until we disallow nonstandard
  82. * abbreviations, order is significant, since the first matching option will
  83. * be chosen first.
  84. */
  85. static config_var_t config_vars[] = {
  86. VAR("Address", STRING, Address, NULL),
  87. VAR("AccountingStart", STRING, AccountingStart, NULL),
  88. VAR("AllowUnverifiedNodes",CSV, AllowUnverifiedNodes, "middle,rendezvous"),
  89. VAR("AuthoritativeDirectory",BOOL, AuthoritativeDir, "0"),
  90. VAR("BandwidthRate", MEMUNIT, BandwidthRate, "1 MB"),
  91. VAR("BandwidthBurst", MEMUNIT, BandwidthBurst, "5 MB"),
  92. VAR("ClientOnly", BOOL, ClientOnly, "0"),
  93. VAR("ContactInfo", STRING, ContactInfo, NULL),
  94. VAR("ControlPort", UINT, ControlPort, "0"),
  95. VAR("CookieAuthentication",BOOL, CookieAuthentication, "0"),
  96. VAR("DebugLogFile", STRING, DebugLogFile, NULL),
  97. VAR("DataDirectory", STRING, DataDirectory, NULL),
  98. VAR("DirAllowPrivateAddresses",BOOL, DirAllowPrivateAddresses, NULL),
  99. VAR("DirPort", UINT, DirPort, "0"),
  100. VAR("DirBindAddress", LINELIST, DirBindAddress, NULL),
  101. /* XXX we'd like dirfetchperiod to be higher for people with dirport not
  102. * set, but low for people with dirport set. how to have two defaults? */
  103. VAR("DirFetchPeriod", INTERVAL, DirFetchPeriod, "1 hour"),
  104. VAR("DirPostPeriod", INTERVAL, DirPostPeriod, "20 minutes"),
  105. VAR("RendPostPeriod", INTERVAL, RendPostPeriod, "20 minutes"),
  106. VAR("DirPolicy", LINELIST, DirPolicy, NULL),
  107. VAR("DirServer", LINELIST, DirServers, NULL),
  108. VAR("ExitNodes", STRING, ExitNodes, NULL),
  109. VAR("EntryNodes", STRING, EntryNodes, NULL),
  110. VAR("StrictExitNodes", BOOL, StrictExitNodes, "0"),
  111. VAR("StrictEntryNodes", BOOL, StrictEntryNodes, "0"),
  112. VAR("ExitPolicy", LINELIST, ExitPolicy, NULL),
  113. VAR("ExcludeNodes", STRING, ExcludeNodes, NULL),
  114. VAR("TrackHostExits", CSV, TrackHostExits, NULL),
  115. VAR("TrackHostExitsExpire",INTERVAL, TrackHostExitsExpire, "30 minutes"),
  116. VAR("AddressMap", LINELIST, AddressMap, NULL),
  117. VAR("FascistFirewall", BOOL, FascistFirewall, "0"),
  118. VAR("FirewallPorts", CSV, FirewallPorts, "80,443"),
  119. VAR("MyFamily", STRING, MyFamily, NULL),
  120. VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
  121. VAR("Group", STRING, Group, NULL),
  122. VAR("HashedControlPassword",STRING, HashedControlPassword, NULL),
  123. VAR("HttpProxy", STRING, HttpProxy, NULL),
  124. VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
  125. VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
  126. VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
  127. VAR("HiddenServiceNodes", LINELIST_S, RendConfigLines, NULL),
  128. VAR("HiddenServiceExcludeNodes", LINELIST_S, RendConfigLines, NULL),
  129. VAR("IgnoreVersion", BOOL, IgnoreVersion, "0"),
  130. VAR("KeepalivePeriod", INTERVAL, KeepalivePeriod, "5 minutes"),
  131. VAR("Log", LINELIST, Logs, NULL),
  132. VAR("LogLevel", LINELIST_S, OldLogOptions, NULL),
  133. VAR("LogFile", LINELIST_S, OldLogOptions, NULL),
  134. OBSOLETE("LinkPadding"),
  135. VAR("MaxConn", UINT, MaxConn, "1024"),
  136. VAR("MaxOnionsPending", UINT, MaxOnionsPending, "100"),
  137. VAR("MonthlyAccountingStart",UINT, _MonthlyAccountingStart,"0"),
  138. VAR("AccountingMaxKB", UINT, _AccountingMaxKB, "0"),
  139. VAR("AccountingMax", MEMUNIT, AccountingMax, "0 bytes"),
  140. VAR("Nickname", STRING, Nickname, NULL),
  141. VAR("NewCircuitPeriod", INTERVAL, NewCircuitPeriod, "30 seconds"),
  142. VAR("MaxCircuitDirtiness", INTERVAL, MaxCircuitDirtiness, "10 minutes"),
  143. VAR("NumCpus", UINT, NumCpus, "1"),
  144. VAR("ORPort", UINT, ORPort, "0"),
  145. VAR("ORBindAddress", LINELIST, ORBindAddress, NULL),
  146. VAR("OutboundBindAddress", STRING, OutboundBindAddress, NULL),
  147. VAR("PidFile", STRING, PidFile, NULL),
  148. VAR("LongLivedPorts", CSV, LongLivedPorts, "21,22,706,1863,5050,5190,5222,5223,6667,8300,8888"),
  149. VAR("PathlenCoinWeight", DOUBLE, PathlenCoinWeight, "0.3"),
  150. VAR("RedirectExit", LINELIST, RedirectExit, NULL),
  151. OBSOLETE("RouterFile"),
  152. VAR("RunAsDaemon", BOOL, RunAsDaemon, "0"),
  153. VAR("RunTesting", BOOL, RunTesting, "0"),
  154. VAR("RecommendedVersions", LINELIST, RecommendedVersions, NULL),
  155. VAR("RendNodes", STRING, RendNodes, NULL),
  156. VAR("RendExcludeNodes", STRING, RendExcludeNodes, NULL),
  157. VAR("SocksPort", UINT, SocksPort, "9050"),
  158. VAR("SocksBindAddress", LINELIST, SocksBindAddress, NULL),
  159. VAR("SocksPolicy", LINELIST, SocksPolicy, NULL),
  160. /* XXX as with dirfetchperiod, we want this to be 15 minutes for people
  161. * with a dirport open, but higher for people without a dirport open. */
  162. VAR("StatusFetchPeriod", INTERVAL, StatusFetchPeriod, "15 minutes"),
  163. VAR("SysLog", LINELIST_S, OldLogOptions, NULL),
  164. OBSOLETE("TrafficShaping"),
  165. VAR("User", STRING, User, NULL),
  166. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  167. };
  168. #undef VAR
  169. #undef OBSOLETE
  170. /** Largest allowed config line */
  171. #define CONFIG_LINE_T_MAXLEN 4096
  172. static void config_line_append(struct config_line_t **lst,
  173. const char *key, const char *val);
  174. static void option_reset(or_options_t *options, config_var_t *var);
  175. static void options_free(or_options_t *options);
  176. static int option_is_same(or_options_t *o1, or_options_t *o2,const char *name);
  177. static or_options_t *options_dup(or_options_t *old);
  178. static int options_validate(or_options_t *options);
  179. static int options_transition_allowed(or_options_t *old, or_options_t *new);
  180. static int check_nickname_list(const char *lst, const char *name);
  181. static void config_register_addressmaps(or_options_t *options);
  182. static int parse_dir_server_line(const char *line, int validate_only);
  183. static int parse_redirect_line(smartlist_t *result,
  184. struct config_line_t *line);
  185. static int parse_log_severity_range(const char *range, int *min_out,
  186. int *max_out);
  187. static int convert_log_option(or_options_t *options,
  188. struct config_line_t *level_opt,
  189. struct config_line_t *file_opt, int isDaemon);
  190. static int add_single_log_option(or_options_t *options, int minSeverity,
  191. int maxSeverity,
  192. const char *type, const char *fname);
  193. static int normalize_log_options(or_options_t *options);
  194. static int validate_data_directory(or_options_t *options);
  195. static int write_configuration_file(const char *fname, or_options_t *options);
  196. static uint64_t config_parse_memunit(const char *s, int *ok);
  197. static int config_parse_interval(const char *s, int *ok);
  198. static void print_cvs_version(void);
  199. /*
  200. * Functions to read and write the global options pointer.
  201. */
  202. /** Command-line and config-file options. */
  203. static or_options_t *global_options=NULL;
  204. /** Name of most recently read torrc file. */
  205. static char *config_fname = NULL;
  206. /** Return the currently configured options. */
  207. or_options_t *
  208. get_options(void) {
  209. tor_assert(global_options);
  210. return global_options;
  211. }
  212. /** Change the current global options to contain <b>new_val</b> instead
  213. * of their current value; free the old value as necessary.
  214. */
  215. void
  216. set_options(or_options_t *new_val) {
  217. if (global_options)
  218. options_free(global_options);
  219. global_options = new_val;
  220. }
  221. void
  222. config_free_all(void)
  223. {
  224. options_free(global_options);
  225. tor_free(config_fname);
  226. }
  227. /** Fetch the active option list, and take actions based on it. All
  228. * of the things we do should survive being done repeatedly.
  229. * Return 0 if all goes well, return -1 if it's time to die.
  230. *
  231. * Note 1: <b>new_val</b> must have previously been validated with
  232. * options_validate(), or Tor may freak out and exit.
  233. *
  234. * Note 2: We haven't moved all the "act on new configuration" logic
  235. * here yet. Some is still in do_hup() and other places.
  236. */
  237. int
  238. options_act(void) {
  239. struct config_line_t *cl;
  240. or_options_t *options = get_options();
  241. static int libevent_initialized = 0;
  242. /* XXXX009 We once had a reason to separate start_daemon and finish_daemon:
  243. * It let us have the parent process stick around until we were sure Tor
  244. * was started. Should we make start_daemon get called earlier? -NM */
  245. if (options->RunAsDaemon) {
  246. start_daemon(options->DataDirectory);
  247. }
  248. if (!libevent_initialized) {
  249. event_init();
  250. libevent_initialized = 1;
  251. }
  252. clear_trusted_dir_servers();
  253. for (cl = options->DirServers; cl; cl = cl->next) {
  254. if (parse_dir_server_line(cl->value, 0)<0) {
  255. log_fn(LOG_ERR,
  256. "Bug: Previously validated DirServer line could not be added!");
  257. return -1;
  258. }
  259. }
  260. if (rend_config_services(options, 0)<0) {
  261. log_fn(LOG_ERR,
  262. "Bug: Previously validated hidden services line could not be added!");
  263. return -1;
  264. }
  265. /* Setuid/setgid as appropriate */
  266. if (options->User || options->Group) {
  267. if (switch_id(options->User, options->Group) != 0) {
  268. return -1;
  269. }
  270. }
  271. /* Ensure data directory is private; create if possible. */
  272. if (check_private_dir(options->DataDirectory, CPD_CREATE) != 0) {
  273. log_fn(LOG_ERR, "Couldn't access/create private data directory %s",
  274. options->DataDirectory);
  275. return -1;
  276. }
  277. /* Bail out at this point if we're not going to be a server: we want
  278. * to not fork, and to log stuff to stderr. */
  279. if (options->command != CMD_RUN_TOR)
  280. return 0;
  281. mark_logs_temp(); /* Close current logs once new logs are open. */
  282. if (config_init_logs(options, 0)<0) /* Configure the log(s) */
  283. return -1;
  284. /* Close the temporary log we used while starting up, if it isn't already
  285. * gone. */
  286. close_temp_logs();
  287. add_callback_log(LOG_NOTICE, LOG_ERR, control_event_logmsg);
  288. if (set_max_file_descriptors(options->MaxConn) < 0)
  289. return -1;
  290. {
  291. smartlist_t *sl = smartlist_create();
  292. for (cl = options->RedirectExit; cl; cl = cl->next) {
  293. if (parse_redirect_line(sl, cl)<0)
  294. return -1;
  295. }
  296. set_exit_redirects(sl);
  297. }
  298. /* Start backgrounding the process, if requested. */
  299. /* Finish backgrounding the process */
  300. if (options->RunAsDaemon) {
  301. /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
  302. finish_daemon();
  303. }
  304. /* Write our pid to the pid file. If we do not have write permissions we
  305. * will log a warning */
  306. if (options->PidFile)
  307. write_pidfile(options->PidFile);
  308. /* Register addressmap directives */
  309. config_register_addressmaps(options);
  310. /* Update address policies. */
  311. parse_socks_policy();
  312. parse_dir_policy();
  313. init_cookie_authentication(options->CookieAuthentication);
  314. /* reload keys as needed for rendezvous services. */
  315. if (rend_service_load_keys()<0) {
  316. log_fn(LOG_ERR,"Error loading rendezvous service keys");
  317. return -1;
  318. }
  319. /* Set up accounting */
  320. if (accounting_parse_options(options, 0)<0) {
  321. log_fn(LOG_ERR,"Error in accounting options");
  322. return -1;
  323. }
  324. if (accounting_is_enabled(options))
  325. configure_accounting(time(NULL));
  326. if (!we_are_hibernating() && retry_all_listeners(1) < 0) {
  327. log_fn(LOG_ERR,"Failed to bind one of the listener ports.");
  328. return -1;
  329. }
  330. #if 0
  331. {
  332. char *smin, *smax;
  333. smin = config_dump_options(options, 1);
  334. smax = config_dump_options(options, 0);
  335. log_fn(LOG_DEBUG, "These are our options:\n%s",smax);
  336. log_fn(LOG_DEBUG, "We changed these options:\n%s",smin);
  337. tor_free(smin);
  338. tor_free(smax);
  339. }
  340. #endif
  341. /* Since our options changed, we might need to regenerate and upload our
  342. * server descriptor. (We could probably be more clever about only calling
  343. * this when something significant changed.)
  344. */
  345. mark_my_descriptor_dirty();
  346. return 0;
  347. }
  348. /*
  349. * Functions to parse config options
  350. */
  351. /** If <b>option</b> is an official abbreviation for a longer option,
  352. * return the longer option. Otherwise return <b>option</b>.
  353. * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
  354. * apply abbreviations that work for the config file and the command line. */
  355. static const char *
  356. expand_abbrev(const char *option, int command_line)
  357. {
  358. int i;
  359. for (i=0; config_abbrevs[i].abbreviated; ++i) {
  360. /* Abbreviations aren't casei. */
  361. if (!strcasecmp(option,config_abbrevs[i].abbreviated) &&
  362. (command_line || !config_abbrevs[i].commandline_only)) {
  363. return config_abbrevs[i].full;
  364. }
  365. }
  366. return option;
  367. }
  368. /** Helper: Read a list of configuration options from the command line. */
  369. static struct config_line_t *
  370. config_get_commandlines(int argc, char **argv)
  371. {
  372. struct config_line_t *new;
  373. struct config_line_t *front = NULL;
  374. char *s;
  375. int i = 1;
  376. while (i < argc-1) {
  377. if (!strcmp(argv[i],"-f") ||
  378. !strcmp(argv[i],"--hash-password")) {
  379. i += 2; /* command-line option with argument. ignore them. */
  380. continue;
  381. } else if (!strcmp(argv[i],"--list-fingerprint")) {
  382. i += 1; /* command-line option. ignore it. */
  383. continue;
  384. } else if (!strcmp(argv[i],"--nt-service")) {
  385. i += 1;
  386. continue;
  387. }
  388. new = tor_malloc(sizeof(struct config_line_t));
  389. s = argv[i];
  390. while (*s == '-')
  391. s++;
  392. new->key = tor_strdup(expand_abbrev(s, 1));
  393. new->value = tor_strdup(argv[i+1]);
  394. log(LOG_DEBUG,"Commandline: parsed keyword '%s', value '%s'",
  395. new->key, new->value);
  396. new->next = front;
  397. front = new;
  398. i += 2;
  399. }
  400. return front;
  401. }
  402. /** Helper: allocate a new configuration option mapping 'key' to 'val',
  403. * append it to *<b>lst</b>. */
  404. static void
  405. config_line_append(struct config_line_t **lst,
  406. const char *key,
  407. const char *val)
  408. {
  409. struct config_line_t *newline;
  410. newline = tor_malloc(sizeof(struct config_line_t));
  411. newline->key = tor_strdup(key);
  412. newline->value = tor_strdup(val);
  413. newline->next = NULL;
  414. while (*lst)
  415. lst = &((*lst)->next);
  416. (*lst) = newline;
  417. }
  418. /** Helper: parse the config string and strdup into key/value
  419. * strings. Set *result to the list, or NULL if parsing the string
  420. * failed. Return 0 on success, -1 on failure. Warn and ignore any
  421. * misformatted lines. */
  422. int
  423. config_get_lines(char *string, struct config_line_t **result)
  424. {
  425. struct config_line_t *list = NULL, **next;
  426. char *k, *v;
  427. next = &list;
  428. do {
  429. string = parse_line_from_str(string, &k, &v);
  430. if (!string) {
  431. config_free_lines(list);
  432. return -1;
  433. }
  434. if (k && v) {
  435. /* This list can get long, so we keep a pointer to the end of it
  436. * rather than using config_line_append over and over and getting n^2
  437. * performance. This is the only really long list. */
  438. *next = tor_malloc(sizeof(struct config_line_t));
  439. (*next)->key = tor_strdup(k);
  440. (*next)->value = tor_strdup(v);
  441. (*next)->next = NULL;
  442. next = &((*next)->next);
  443. }
  444. } while (*string);
  445. *result = list;
  446. return 0;
  447. }
  448. /**
  449. * Free all the configuration lines on the linked list <b>front</b>.
  450. */
  451. void
  452. config_free_lines(struct config_line_t *front)
  453. {
  454. struct config_line_t *tmp;
  455. while (front) {
  456. tmp = front;
  457. front = tmp->next;
  458. tor_free(tmp->key);
  459. tor_free(tmp->value);
  460. tor_free(tmp);
  461. }
  462. }
  463. /** If <b>key</b> is a configuration option, return the corresponding
  464. * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
  465. * warn, and return the corresponding config_var_t. Otherwise return NULL.
  466. */
  467. static config_var_t *config_find_option(const char *key)
  468. {
  469. int i;
  470. size_t keylen = strlen(key);
  471. if (!keylen)
  472. return NULL; /* if they say "--" on the commandline, it's not an option */
  473. /* First, check for an exact (case-insensitive) match */
  474. for (i=0; config_vars[i].name; ++i) {
  475. if (!strcasecmp(key, config_vars[i].name))
  476. return &config_vars[i];
  477. }
  478. /* If none, check for an abbreviated match */
  479. for (i=0; config_vars[i].name; ++i) {
  480. if (!strncasecmp(key, config_vars[i].name, keylen)) {
  481. log_fn(LOG_WARN, "The abbreviation '%s' is deprecated. "
  482. "Tell Nick and Roger to make it official, or just use '%s' instead",
  483. key, config_vars[i].name);
  484. return &config_vars[i];
  485. }
  486. }
  487. /* Okay, unrecognized options */
  488. return NULL;
  489. }
  490. /** If <b>c</b> is a syntactically valid configuration line, update
  491. * <b>options</b> with its value and return 0. Otherwise return -1 for bad key,
  492. * -2 for bad value.
  493. *
  494. * If 'reset' is set, and we get a line containing no value, restore the
  495. * option to its default value.
  496. */
  497. static int
  498. config_assign_line(or_options_t *options, struct config_line_t *c, int reset)
  499. {
  500. int i, ok;
  501. config_var_t *var;
  502. void *lvalue;
  503. var = config_find_option(c->key);
  504. if (!var) {
  505. log_fn(LOG_WARN, "Unknown option '%s'. Failing.", c->key);
  506. return -1;
  507. }
  508. /* Put keyword into canonical case. */
  509. if (strcmp(var->name, c->key)) {
  510. tor_free(c->key);
  511. c->key = tor_strdup(var->name);
  512. }
  513. if (reset && !strlen(c->value)) {
  514. option_reset(options, var);
  515. return 0;
  516. }
  517. lvalue = ((char*)options) + var->var_offset;
  518. switch (var->type) {
  519. case CONFIG_TYPE_UINT:
  520. i = tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
  521. if (!ok) {
  522. log(LOG_WARN, "Int keyword '%s %s' is malformed or out of bounds.",
  523. c->key,c->value);
  524. return -2;
  525. }
  526. *(int *)lvalue = i;
  527. break;
  528. case CONFIG_TYPE_INTERVAL: {
  529. i = config_parse_interval(c->value, &ok);
  530. if (!ok) {
  531. return -2;
  532. }
  533. *(int *)lvalue = i;
  534. break;
  535. }
  536. case CONFIG_TYPE_MEMUNIT: {
  537. uint64_t u64 = config_parse_memunit(c->value, &ok);
  538. if (!ok) {
  539. return -2;
  540. }
  541. *(uint64_t *)lvalue = u64;
  542. break;
  543. }
  544. case CONFIG_TYPE_BOOL:
  545. i = tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
  546. if (!ok) {
  547. log(LOG_WARN, "Boolean keyword '%s' expects 0 or 1.", c->key);
  548. return -2;
  549. }
  550. *(int *)lvalue = i;
  551. break;
  552. case CONFIG_TYPE_STRING:
  553. tor_free(*(char **)lvalue);
  554. *(char **)lvalue = tor_strdup(c->value);
  555. break;
  556. case CONFIG_TYPE_DOUBLE:
  557. *(double *)lvalue = atof(c->value);
  558. break;
  559. case CONFIG_TYPE_CSV:
  560. if (*(smartlist_t**)lvalue) {
  561. SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
  562. smartlist_clear(*(smartlist_t**)lvalue);
  563. } else {
  564. *(smartlist_t**)lvalue = smartlist_create();
  565. }
  566. smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
  567. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  568. break;
  569. case CONFIG_TYPE_LINELIST:
  570. case CONFIG_TYPE_LINELIST_S:
  571. config_line_append((struct config_line_t**)lvalue, c->key, c->value);
  572. break;
  573. case CONFIG_TYPE_OBSOLETE:
  574. log_fn(LOG_WARN, "Skipping obsolete configuration option '%s'", c->key);
  575. break;
  576. case CONFIG_TYPE_LINELIST_V:
  577. log_fn(LOG_WARN, "Can't provide value for virtual option '%s'", c->key);
  578. return -2;
  579. default:
  580. tor_assert(0);
  581. break;
  582. }
  583. return 0;
  584. }
  585. /** restore the option named <b>key</b> in options to its default value. */
  586. static void
  587. config_reset_line(or_options_t *options, const char *key)
  588. {
  589. config_var_t *var;
  590. var = config_find_option(key);
  591. if (!var)
  592. return; /* give error on next pass. */
  593. option_reset(options, var);
  594. }
  595. /** Return true iff key is a valid configuration option. */
  596. int
  597. config_option_is_recognized(const char *key)
  598. {
  599. config_var_t *var = config_find_option(key);
  600. return (var != NULL);
  601. }
  602. /** Return a canonicalized list of the options assigned for key.
  603. */
  604. struct config_line_t *
  605. config_get_assigned_option(or_options_t *options, const char *key)
  606. {
  607. config_var_t *var;
  608. const void *value;
  609. char buf[32];
  610. struct config_line_t *result;
  611. tor_assert(options && key);
  612. var = config_find_option(key);
  613. if (!var) {
  614. log_fn(LOG_WARN, "Unknown option '%s'. Failing.", key);
  615. return NULL;
  616. } else if (var->type == CONFIG_TYPE_LINELIST_S) {
  617. log_fn(LOG_WARN, "Can't return context-sensitive '%s' on its own", key);
  618. return NULL;
  619. }
  620. value = ((char*)options) + var->var_offset;
  621. if (var->type == CONFIG_TYPE_LINELIST ||
  622. var->type == CONFIG_TYPE_LINELIST_V) {
  623. /* Linelist requires special handling: we just copy and return it. */
  624. const struct config_line_t *next_in = *(const struct config_line_t**)value;
  625. struct config_line_t **next_out = &result;
  626. while (next_in) {
  627. *next_out = tor_malloc(sizeof(struct config_line_t));
  628. (*next_out)->key = tor_strdup(next_in->key);
  629. (*next_out)->value = tor_strdup(next_in->value);
  630. next_in = next_in->next;
  631. next_out = &((*next_out)->next);
  632. }
  633. (*next_out) = NULL;
  634. return result;
  635. }
  636. result = tor_malloc_zero(sizeof(struct config_line_t));
  637. result->key = tor_strdup(var->name);
  638. switch (var->type)
  639. {
  640. case CONFIG_TYPE_STRING:
  641. if (*(char**)value) {
  642. result->value = tor_strdup(*(char**)value);
  643. } else {
  644. tor_free(result->key);
  645. tor_free(result);
  646. return NULL;
  647. }
  648. break;
  649. case CONFIG_TYPE_INTERVAL:
  650. case CONFIG_TYPE_UINT:
  651. /* This means every or_options_t uint or bool element
  652. * needs to be an int. Not, say, a uint16_t or char. */
  653. tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
  654. result->value = tor_strdup(buf);
  655. break;
  656. case CONFIG_TYPE_MEMUNIT:
  657. tor_snprintf(buf, sizeof(buf), U64_FORMAT,
  658. U64_PRINTF_ARG(*(uint64_t*)value));
  659. result->value = tor_strdup(buf);
  660. break;
  661. case CONFIG_TYPE_DOUBLE:
  662. tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
  663. result->value = tor_strdup(buf);
  664. break;
  665. case CONFIG_TYPE_BOOL:
  666. result->value = tor_strdup(*(int*)value ? "1" : "0");
  667. break;
  668. case CONFIG_TYPE_CSV:
  669. if (*(smartlist_t**)value)
  670. result->value = smartlist_join_strings(*(smartlist_t**)value,",",0,NULL);
  671. else
  672. result->value = tor_strdup("");
  673. break;
  674. case CONFIG_TYPE_OBSOLETE:
  675. log_fn(LOG_WARN,"You asked me for the value of an obsolete config option %s.", key);
  676. tor_free(result->key);
  677. tor_free(result);
  678. return NULL;
  679. default:
  680. tor_free(result->key);
  681. tor_free(result);
  682. log_fn(LOG_WARN,"Bug: unknown type %d for known key %s", var->type, key);
  683. return NULL;
  684. }
  685. return result;
  686. }
  687. /** Iterate through the linked list of requested options <b>list</b>.
  688. * For each item, convert as appropriate and assign to <b>options</b>.
  689. * If an item is unrecognized, return -1 immediately,
  690. * else return 0 for success.
  691. *
  692. * If <b>reset</b>, then interpret empty lines as meaning "restore to
  693. * default value", and interpret LINELIST* options as replacing (not
  694. * extending) their previous values. Return 0 on success, -1 on bad key,
  695. * -2 on bad value.
  696. */
  697. static int
  698. config_assign(or_options_t *options, struct config_line_t *list, int reset)
  699. {
  700. struct config_line_t *p;
  701. tor_assert(options);
  702. /* pass 1: normalize keys */
  703. for (p = list; p; p = p->next) {
  704. const char *full = expand_abbrev(p->key, 0);
  705. if (strcmp(full,p->key)) {
  706. tor_free(p->key);
  707. p->key = tor_strdup(full);
  708. }
  709. }
  710. /* pass 2: if we're reading from a resetting source, clear all mentioned
  711. * linelists. */
  712. if (reset) {
  713. for (p = list; p; p = p->next)
  714. config_reset_line(options, p->key);
  715. }
  716. /* pass 3: assign. */
  717. while (list) {
  718. int r;
  719. if ((r=config_assign_line(options, list, reset)))
  720. return r;
  721. list = list->next;
  722. }
  723. return 0;
  724. }
  725. /** Try assigning <b>list</b> to the global options. You do this by duping
  726. * options, assigning list to the new one, then validating it. If it's
  727. * ok, then throw out the old one and stick with the new one. Else,
  728. * revert to old and return failure. Return 0 on success, -1 on bad
  729. * keys, -2 on bad values, -3 on bad transition.
  730. */
  731. int
  732. config_trial_assign(struct config_line_t *list, int reset)
  733. {
  734. int r;
  735. or_options_t *trial_options = options_dup(get_options());
  736. if ((r=config_assign(trial_options, list, reset)) < 0) {
  737. options_free(trial_options);
  738. return r;
  739. }
  740. if (options_validate(trial_options) < 0) {
  741. options_free(trial_options);
  742. return -2;
  743. }
  744. if (options_transition_allowed(get_options(), trial_options) < 0) {
  745. options_free(trial_options);
  746. return -3;
  747. }
  748. set_options(trial_options); /* we liked it. put it in place. */
  749. return 0;
  750. }
  751. /** Replace the option indexed by <b>var</b> in <b>options</b> with its
  752. * default value. */
  753. static void
  754. option_reset(or_options_t *options, config_var_t *var)
  755. {
  756. struct config_line_t *c;
  757. void *lvalue;
  758. lvalue = ((char*)options) + var->var_offset;
  759. switch (var->type) {
  760. case CONFIG_TYPE_STRING:
  761. tor_free(*(char**)lvalue);
  762. break;
  763. case CONFIG_TYPE_DOUBLE:
  764. *(double*)lvalue = 0.0;
  765. break;
  766. case CONFIG_TYPE_INTERVAL:
  767. case CONFIG_TYPE_UINT:
  768. case CONFIG_TYPE_BOOL:
  769. *(int*)lvalue = 0;
  770. break;
  771. case CONFIG_TYPE_MEMUNIT:
  772. *(uint64_t*)lvalue = 0;
  773. break;
  774. case CONFIG_TYPE_CSV:
  775. if (*(smartlist_t**)lvalue) {
  776. SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
  777. smartlist_free(*(smartlist_t **)lvalue);
  778. *(smartlist_t **)lvalue = NULL;
  779. }
  780. break;
  781. case CONFIG_TYPE_LINELIST:
  782. case CONFIG_TYPE_LINELIST_S:
  783. config_free_lines(*(struct config_line_t **)lvalue);
  784. *(struct config_line_t **)lvalue = NULL;
  785. break;
  786. case CONFIG_TYPE_LINELIST_V:
  787. /* handled by linelist_s. */
  788. break;
  789. case CONFIG_TYPE_OBSOLETE:
  790. break;
  791. }
  792. if (var->initvalue) {
  793. c = tor_malloc_zero(sizeof(struct config_line_t));
  794. c->key = tor_strdup(var->name);
  795. c->value = tor_strdup(var->initvalue);
  796. config_assign_line(options,c,0);
  797. config_free_lines(c);
  798. }
  799. }
  800. /** Set <b>options</b>-&gt;DirServers to contain the default directory
  801. * servers. */
  802. static void
  803. add_default_trusted_dirservers(or_options_t *options)
  804. {
  805. /* moria1 */
  806. config_line_append(&options->DirServers, "DirServer",
  807. "18.244.0.188:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
  808. /* moria2 */
  809. config_line_append(&options->DirServers, "DirServer",
  810. "18.244.0.114:80 719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF");
  811. /* tor26 */
  812. config_line_append(&options->DirServers, "DirServer",
  813. "62.116.124.106:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
  814. // "tor.noreply.org:9030 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
  815. }
  816. /** Print a usage message for tor. */
  817. static void
  818. print_usage(void)
  819. {
  820. printf(
  821. "Copyright 2001-2004 Roger Dingledine, Nick Mathewson, Matej Pfajfar.\n\n"
  822. "tor -f <torrc> [args]\n"
  823. "See man page for options, or http://tor.eff.org/ for documentation.\n");
  824. }
  825. /**
  826. * Based on <b>address</b>, guess our public IP address and put it
  827. * in <b>addr</b>.
  828. */
  829. int
  830. resolve_my_address(const char *address, uint32_t *addr)
  831. {
  832. struct in_addr in;
  833. struct hostent *rent;
  834. char hostname[256];
  835. int explicit_ip=1;
  836. char tmpbuf[INET_NTOA_BUF_LEN];
  837. tor_assert(addr);
  838. if (address) {
  839. strlcpy(hostname, address, sizeof(hostname));
  840. } else { /* then we need to guess our address */
  841. explicit_ip = 0; /* it's implicit */
  842. if (gethostname(hostname, sizeof(hostname)) < 0) {
  843. log_fn(LOG_WARN,"Error obtaining local hostname");
  844. return -1;
  845. }
  846. log_fn(LOG_DEBUG,"Guessed local host name as '%s'",hostname);
  847. }
  848. /* now we know hostname. resolve it and keep only the IP */
  849. if (tor_inet_aton(hostname, &in) == 0) {
  850. /* then we have to resolve it */
  851. explicit_ip = 0;
  852. rent = (struct hostent *)gethostbyname(hostname);
  853. if (!rent) {
  854. log_fn(LOG_WARN,"Could not resolve local Address %s. Failing.", hostname);
  855. return -1;
  856. }
  857. tor_assert(rent->h_length == 4);
  858. memcpy(&in.s_addr, rent->h_addr, rent->h_length);
  859. }
  860. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  861. if (!explicit_ip && is_internal_IP(htonl(in.s_addr))) {
  862. log_fn(LOG_WARN,"Address '%s' resolves to private IP '%s'. "
  863. "Please set the Address config option to be the IP you want to use.",
  864. hostname, tmpbuf);
  865. return -1;
  866. }
  867. log_fn(LOG_DEBUG, "Resolved Address to %s.", tmpbuf);
  868. *addr = ntohl(in.s_addr);
  869. return 0;
  870. }
  871. /** Called when we don't have a nickname set. Try to guess a good
  872. * nickname based on the hostname, and return it in a newly allocated string. */
  873. static char *
  874. get_default_nickname(void)
  875. {
  876. char localhostname[256];
  877. char *cp, *out, *outp;
  878. if (gethostname(localhostname, sizeof(localhostname)) < 0) {
  879. log_fn(LOG_WARN,"Error obtaining local hostname");
  880. return NULL;
  881. }
  882. /* Put it in lowercase; stop at the first dot. */
  883. for (cp = localhostname; *cp; ++cp) {
  884. if (*cp == '.') {
  885. *cp = '\0';
  886. break;
  887. }
  888. *cp = tolower(*cp);
  889. }
  890. /* Strip invalid characters. */
  891. cp = localhostname;
  892. out = outp = tor_malloc(strlen(localhostname) + 1);
  893. while (*cp) {
  894. if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
  895. *outp++ = *cp++;
  896. else
  897. cp++;
  898. }
  899. *outp = '\0';
  900. /* Enforce length. */
  901. if (strlen(out) > MAX_NICKNAME_LEN)
  902. out[MAX_NICKNAME_LEN]='\0';
  903. return out;
  904. }
  905. /** Release storage held by <b>options</b> */
  906. static void
  907. options_free(or_options_t *options)
  908. {
  909. int i;
  910. void *lvalue;
  911. tor_assert(options);
  912. for (i=0; config_vars[i].name; ++i) {
  913. lvalue = ((char*)options) + config_vars[i].var_offset;
  914. switch (config_vars[i].type) {
  915. case CONFIG_TYPE_MEMUNIT:
  916. case CONFIG_TYPE_INTERVAL:
  917. case CONFIG_TYPE_UINT:
  918. case CONFIG_TYPE_BOOL:
  919. case CONFIG_TYPE_DOUBLE:
  920. case CONFIG_TYPE_OBSOLETE:
  921. break; /* nothing to free for these config types */
  922. case CONFIG_TYPE_STRING:
  923. tor_free(*(char **)lvalue);
  924. break;
  925. case CONFIG_TYPE_LINELIST:
  926. case CONFIG_TYPE_LINELIST_V:
  927. config_free_lines(*(struct config_line_t**)lvalue);
  928. *(struct config_line_t**)lvalue = NULL;
  929. break;
  930. case CONFIG_TYPE_CSV:
  931. if (*(smartlist_t**)lvalue) {
  932. SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
  933. smartlist_free(*(smartlist_t**)lvalue);
  934. *(smartlist_t**)lvalue = NULL;
  935. }
  936. break;
  937. case CONFIG_TYPE_LINELIST_S:
  938. /* will be freed by corresponding LINELIST_V. */
  939. break;
  940. }
  941. }
  942. tor_free(options);
  943. }
  944. /** Return true iff the option <b>var</b> has the same value in <b>o1</b>
  945. * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
  946. */
  947. static int
  948. option_is_same(or_options_t *o1, or_options_t *o2, const char *name)
  949. {
  950. struct config_line_t *c1, *c2;
  951. int r = 1;
  952. c1 = config_get_assigned_option(o1, name);
  953. c2 = config_get_assigned_option(o2, name);
  954. while (c1 && c2) {
  955. if (strcasecmp(c1->key, c2->key) ||
  956. strcmp(c1->value, c2->value)) {
  957. r = 0;
  958. break;
  959. }
  960. c1 = c1->next;
  961. c2 = c2->next;
  962. }
  963. if (r && (c1 || c2)) {
  964. r = 0;
  965. }
  966. config_free_lines(c1);
  967. config_free_lines(c2);
  968. return r;
  969. }
  970. /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
  971. static or_options_t *
  972. options_dup(or_options_t *old)
  973. {
  974. or_options_t *newopts;
  975. int i;
  976. struct config_line_t *line;
  977. newopts = tor_malloc_zero(sizeof(or_options_t));
  978. for (i=0; config_vars[i].name; ++i) {
  979. if (config_vars[i].type == CONFIG_TYPE_LINELIST_S)
  980. continue;
  981. if (config_vars[i].type == CONFIG_TYPE_OBSOLETE)
  982. continue;
  983. line = config_get_assigned_option(old, config_vars[i].name);
  984. if (line) {
  985. if (config_assign(newopts, line, 0) < 0) {
  986. log_fn(LOG_WARN,"Bug: config_get_assigned_option() generated "
  987. "something we couldn't config_assign().");
  988. tor_assert(0);
  989. }
  990. }
  991. config_free_lines(line);
  992. }
  993. return newopts;
  994. }
  995. /** Set <b>options</b> to hold reasonable defaults for most options.
  996. * Each option defaults to zero. */
  997. void
  998. options_init(or_options_t *options)
  999. {
  1000. int i;
  1001. config_var_t *var;
  1002. for (i=0; config_vars[i].name; ++i) {
  1003. var = &config_vars[i];
  1004. if (!var->initvalue)
  1005. continue; /* defaults to NULL or 0 */
  1006. option_reset(options, var);
  1007. }
  1008. }
  1009. /** Return a string containing a possible configuration file that would give
  1010. * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
  1011. * include options that are the same as Tor's defaults.
  1012. */
  1013. char *
  1014. config_dump_options(or_options_t *options, int minimal)
  1015. {
  1016. smartlist_t *elements;
  1017. or_options_t *defaults;
  1018. struct config_line_t *line;
  1019. char *result;
  1020. int i;
  1021. defaults = tor_malloc_zero(sizeof(or_options_t));
  1022. options_init(defaults);
  1023. options_validate(defaults); /* ??? will this work? */
  1024. elements = smartlist_create();
  1025. for (i=0; config_vars[i].name; ++i) {
  1026. if (config_vars[i].type == CONFIG_TYPE_OBSOLETE ||
  1027. config_vars[i].type == CONFIG_TYPE_LINELIST_S)
  1028. continue;
  1029. if (minimal && option_is_same(options, defaults, config_vars[i].name))
  1030. continue;
  1031. line = config_get_assigned_option(options, config_vars[i].name);
  1032. for (; line; line = line->next) {
  1033. size_t len = strlen(line->key) + strlen(line->value) + 3;
  1034. char *tmp;
  1035. tmp = tor_malloc(len);
  1036. if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
  1037. log_fn(LOG_ERR, "Internal error writing log option");
  1038. tor_assert(0);
  1039. }
  1040. smartlist_add(elements, tmp);
  1041. }
  1042. config_free_lines(line);
  1043. }
  1044. result = smartlist_join_strings(elements, "", 0, NULL);
  1045. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  1046. smartlist_free(elements);
  1047. return result;
  1048. }
  1049. static int
  1050. validate_ports_csv(smartlist_t *sl, char *name) {
  1051. int i;
  1052. int result = 0;
  1053. tor_assert(name);
  1054. if (!sl)
  1055. return 0;
  1056. SMARTLIST_FOREACH(sl, const char *, cp,
  1057. {
  1058. i = atoi(cp);
  1059. if (i < 1 || i > 65535) {
  1060. log(LOG_WARN, "Port '%s' out of range in %s", cp, name);
  1061. result=-1;
  1062. }
  1063. });
  1064. return result;
  1065. }
  1066. /** Return 0 if every setting in <b>options</b> is reasonable. Else
  1067. * warn and return -1. Should have no side effects, except for
  1068. * normalizing the contents of <b>options</b>. */
  1069. static int
  1070. options_validate(or_options_t *options)
  1071. {
  1072. int result = 0;
  1073. struct config_line_t *cl;
  1074. addr_policy_t *addr_policy=NULL;
  1075. if (options->ORPort < 0 || options->ORPort > 65535) {
  1076. log(LOG_WARN, "ORPort option out of bounds.");
  1077. result = -1;
  1078. }
  1079. /* XXX might similarly want to check the other *BindAddress options */
  1080. if (options->ORPort == 0 && options->ORBindAddress != NULL) {
  1081. log(LOG_WARN, "ORPort must be defined if ORBindAddress is defined.");
  1082. result = -1;
  1083. }
  1084. if (validate_data_directory(options)<0) {
  1085. log(LOG_WARN, "Invalid DataDirectory");
  1086. result = -1;
  1087. }
  1088. if (options->Nickname == NULL) {
  1089. if (server_mode(options)) {
  1090. if (!(options->Nickname = get_default_nickname()))
  1091. return -1;
  1092. log_fn(LOG_NOTICE, "Choosing default nickname %s", options->Nickname);
  1093. }
  1094. } else {
  1095. if (strspn(options->Nickname, LEGAL_NICKNAME_CHARACTERS) !=
  1096. strlen(options->Nickname)) {
  1097. log_fn(LOG_WARN, "Nickname '%s' contains illegal characters.", options->Nickname);
  1098. result = -1;
  1099. }
  1100. if (strlen(options->Nickname) == 0) {
  1101. log_fn(LOG_WARN, "Nickname must have at least one character");
  1102. result = -1;
  1103. }
  1104. if (strlen(options->Nickname) > MAX_NICKNAME_LEN) {
  1105. log_fn(LOG_WARN, "Nickname '%s' has more than %d characters.",
  1106. options->Nickname, MAX_NICKNAME_LEN);
  1107. result = -1;
  1108. }
  1109. }
  1110. if (normalize_log_options(options))
  1111. return -1;
  1112. /* Special case if no options are given. */
  1113. if (!options->Logs) {
  1114. config_line_append(&options->Logs, "Log", "notice stdout");
  1115. }
  1116. if (config_init_logs(options, 1)<0) /* Validate the log(s) */
  1117. return -1;
  1118. if (server_mode(options)) {
  1119. /* confirm that our address isn't broken, so we can complain now */
  1120. uint32_t tmp;
  1121. if (resolve_my_address(options->Address, &tmp) < 0)
  1122. result = -1;
  1123. }
  1124. if (options->SocksPort < 0 || options->SocksPort > 65535) {
  1125. log(LOG_WARN, "SocksPort option out of bounds.");
  1126. result = -1;
  1127. }
  1128. if (options->SocksPort == 0 && options->ORPort == 0) {
  1129. log(LOG_WARN, "SocksPort and ORPort are both undefined? Quitting.");
  1130. result = -1;
  1131. }
  1132. if (options->ControlPort < 0 || options->ControlPort > 65535) {
  1133. log(LOG_WARN, "ControlPort option out of bounds.");
  1134. result = -1;
  1135. }
  1136. if (options->DirPort < 0 || options->DirPort > 65535) {
  1137. log(LOG_WARN, "DirPort option out of bounds.");
  1138. result = -1;
  1139. }
  1140. if (options->StrictExitNodes &&
  1141. (!options->ExitNodes || !strlen(options->ExitNodes))) {
  1142. log(LOG_WARN, "StrictExitNodes set, but no ExitNodes listed.");
  1143. }
  1144. if (options->StrictEntryNodes &&
  1145. (!options->EntryNodes || !strlen(options->EntryNodes))) {
  1146. log(LOG_WARN, "StrictEntryNodes set, but no EntryNodes listed.");
  1147. }
  1148. if (options->AuthoritativeDir && options->RecommendedVersions == NULL) {
  1149. log(LOG_WARN, "Directory servers must configure RecommendedVersions.");
  1150. result = -1;
  1151. }
  1152. if (options->AuthoritativeDir && !options->DirPort) {
  1153. log(LOG_WARN, "Running as authoritative directory, but no DirPort set.");
  1154. result = -1;
  1155. }
  1156. if (options->AuthoritativeDir && !options->ORPort) {
  1157. log(LOG_WARN, "Running as authoritative directory, but no ORPort set.");
  1158. result = -1;
  1159. }
  1160. if (options->AuthoritativeDir && options->ClientOnly) {
  1161. log(LOG_WARN, "Running as authoritative directory, but ClientOnly also set.");
  1162. result = -1;
  1163. }
  1164. if (options->_AccountingMaxKB) {
  1165. log(LOG_WARN, "AccountingMaxKB is deprecated. Say 'AccountingMax %d KB' instead.", options->_AccountingMaxKB);
  1166. options->AccountingMax = U64_LITERAL(1024)*options->_AccountingMaxKB;
  1167. options->_AccountingMaxKB = 0;
  1168. }
  1169. if (validate_ports_csv(options->FirewallPorts,
  1170. "FirewallPorts") < 0)
  1171. result = -1;
  1172. if (validate_ports_csv(options->LongLivedPorts,
  1173. "LongLivedPorts") < 0)
  1174. result = -1;
  1175. options->_AllowUnverified = 0;
  1176. if (options->AllowUnverifiedNodes) {
  1177. SMARTLIST_FOREACH(options->AllowUnverifiedNodes, const char *, cp, {
  1178. if (!strcasecmp(cp, "entry"))
  1179. options->_AllowUnverified |= ALLOW_UNVERIFIED_ENTRY;
  1180. else if (!strcasecmp(cp, "exit"))
  1181. options->_AllowUnverified |= ALLOW_UNVERIFIED_EXIT;
  1182. else if (!strcasecmp(cp, "middle"))
  1183. options->_AllowUnverified |= ALLOW_UNVERIFIED_MIDDLE;
  1184. else if (!strcasecmp(cp, "introduction"))
  1185. options->_AllowUnverified |= ALLOW_UNVERIFIED_INTRODUCTION;
  1186. else if (!strcasecmp(cp, "rendezvous"))
  1187. options->_AllowUnverified |= ALLOW_UNVERIFIED_RENDEZVOUS;
  1188. else {
  1189. log(LOG_WARN, "Unrecognized value '%s' in AllowUnverifiedNodes",
  1190. cp);
  1191. result = -1;
  1192. }
  1193. });
  1194. }
  1195. if (options->SocksPort >= 1 &&
  1196. (options->PathlenCoinWeight < 0.0 || options->PathlenCoinWeight >= 1.0)) {
  1197. log(LOG_WARN, "PathlenCoinWeight option must be >=0.0 and <1.0.");
  1198. result = -1;
  1199. }
  1200. if (options->MaxConn < 1) {
  1201. log(LOG_WARN, "MaxConn option must be a non-zero positive integer.");
  1202. result = -1;
  1203. }
  1204. if (options->MaxConn > MAXCONNECTIONS) {
  1205. log(LOG_WARN, "MaxConn option must be at most %d.", MAXCONNECTIONS);
  1206. result = -1;
  1207. }
  1208. #define MIN_DIR_FETCH_PERIOD 600
  1209. #define MIN_DIR_POST_PERIOD 300
  1210. #define MIN_REND_POST_PERIOD 300
  1211. #define MIN_STATUS_FETCH_PERIOD 60
  1212. #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
  1213. #define MAX_CACHE_DIR_FETCH_PERIOD 3600
  1214. #define MAX_CACHE_STATUS_FETCH_PERIOD 900
  1215. if (options->DirFetchPeriod < MIN_DIR_FETCH_PERIOD) {
  1216. log(LOG_WARN, "DirFetchPeriod option must be at least %d seconds. Clipping.", MIN_DIR_FETCH_PERIOD);
  1217. options->DirFetchPeriod = MIN_DIR_FETCH_PERIOD;
  1218. }
  1219. if (options->StatusFetchPeriod < MIN_STATUS_FETCH_PERIOD) {
  1220. log(LOG_WARN, "StatusFetchPeriod option must be at least %d seconds. Clipping.", MIN_STATUS_FETCH_PERIOD);
  1221. options->StatusFetchPeriod = MIN_STATUS_FETCH_PERIOD;
  1222. }
  1223. if (options->DirPostPeriod < MIN_DIR_POST_PERIOD) {
  1224. log(LOG_WARN, "DirPostPeriod option must be at least %d seconds. Clipping.",
  1225. MIN_DIR_POST_PERIOD);
  1226. options->DirPostPeriod = MIN_DIR_POST_PERIOD;
  1227. }
  1228. if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
  1229. log(LOG_WARN,"RendPostPeriod option must be at least %d seconds. Clipping.",
  1230. MIN_REND_POST_PERIOD);
  1231. options->RendPostPeriod = MIN_REND_POST_PERIOD;
  1232. }
  1233. if (options->DirPort && ! options->AuthoritativeDir) {
  1234. if (options->DirFetchPeriod > MAX_CACHE_DIR_FETCH_PERIOD) {
  1235. log(LOG_WARN, "Caching directory servers must have DirFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_DIR_FETCH_PERIOD);
  1236. options->DirFetchPeriod = MAX_CACHE_DIR_FETCH_PERIOD;
  1237. }
  1238. if (options->StatusFetchPeriod > MAX_CACHE_STATUS_FETCH_PERIOD) {
  1239. log(LOG_WARN, "Caching directory servers must have StatusFetchPeriod less than %d seconds. Clipping.", MAX_CACHE_STATUS_FETCH_PERIOD);
  1240. options->StatusFetchPeriod = MAX_CACHE_STATUS_FETCH_PERIOD;
  1241. }
  1242. }
  1243. if (options->DirFetchPeriod > MAX_DIR_PERIOD) {
  1244. log(LOG_WARN, "DirFetchPeriod is too large; clipping.");
  1245. options->DirFetchPeriod = MAX_DIR_PERIOD;
  1246. }
  1247. if (options->DirPostPeriod > MAX_DIR_PERIOD) {
  1248. log(LOG_WARN, "DirPostPeriod is too large; clipping.");
  1249. options->DirPostPeriod = MAX_DIR_PERIOD;
  1250. }
  1251. if (options->StatusFetchPeriod > MAX_DIR_PERIOD) {
  1252. log(LOG_WARN, "StatusFetchPeriod is too large; clipping.");
  1253. options->StatusFetchPeriod = MAX_DIR_PERIOD;
  1254. }
  1255. if (options->RendPostPeriod > MAX_DIR_PERIOD) {
  1256. log(LOG_WARN, "RendPostPeriod is too large; clipping.");
  1257. options->RendPostPeriod = MAX_DIR_PERIOD;
  1258. }
  1259. if (options->KeepalivePeriod < 1) {
  1260. log(LOG_WARN,"KeepalivePeriod option must be positive.");
  1261. result = -1;
  1262. }
  1263. if (options->BandwidthRate > INT_MAX) {
  1264. log(LOG_WARN,"BandwidthRate must be less than %d",INT_MAX);
  1265. result = -1;
  1266. }
  1267. if (options->BandwidthBurst > INT_MAX) {
  1268. log(LOG_WARN,"BandwidthBurst must be less than %d",INT_MAX);
  1269. result = -1;
  1270. }
  1271. if (server_mode(options) &&
  1272. options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH*2) {
  1273. log(LOG_WARN,"BandwidthRate is set to %d bytes/second. For servers, it must be at least %d.", (int)options->BandwidthRate, ROUTER_REQUIRED_MIN_BANDWIDTH*2);
  1274. result = -1;
  1275. }
  1276. if (options->BandwidthRate > options->BandwidthBurst) {
  1277. log(LOG_WARN,"BandwidthBurst must be at least equal to BandwidthRate.");
  1278. result = -1;
  1279. }
  1280. #if 0
  1281. if (2*options->BandwidthRate > options->BandwidthBurst) {
  1282. log(LOG_NOTICE,"You have chosen a BandwidthBurst less than twice BandwidthRate. Please consider setting your BandwidthBurst higher (at least %d), to provide better service to the Tor network.", (int)(2*options->BandwidthRate));
  1283. }
  1284. #endif
  1285. if (options->_MonthlyAccountingStart) {
  1286. if (options->AccountingStart) {
  1287. log(LOG_WARN,"Can't specify AccountingStart and MonthlyAccountingStart");
  1288. result = -1;
  1289. } else {
  1290. options->AccountingStart = tor_malloc(32);
  1291. if (tor_snprintf(options->AccountingStart, 32, "month %d 0:00",
  1292. options->_MonthlyAccountingStart)<0) {
  1293. log_fn(LOG_WARN,"Error translating MonthlyAccountingStart");
  1294. result = -1;
  1295. } else {
  1296. log_fn(LOG_WARN,"MonthlyAccountingStart is deprecated. Use 'AccountingStart %s' instead.", options->AccountingStart);
  1297. }
  1298. }
  1299. }
  1300. if (accounting_parse_options(options, 1)<0) {
  1301. result = -1;
  1302. }
  1303. if (options->HttpProxy) { /* parse it now */
  1304. if (parse_addr_port(options->HttpProxy, NULL,
  1305. &options->HttpProxyAddr, &options->HttpProxyPort) < 0) {
  1306. log(LOG_WARN,"HttpProxy failed to parse or resolve. Please fix.");
  1307. result = -1;
  1308. }
  1309. if (options->HttpProxyPort == 0) { /* give it a default */
  1310. options->HttpProxyPort = 80;
  1311. }
  1312. }
  1313. if (options->HashedControlPassword) {
  1314. if (decode_hashed_password(NULL, options->HashedControlPassword)<0) {
  1315. log_fn(LOG_WARN,"Bad HashedControlPassword: wrong length or bad base64");
  1316. result = -1;
  1317. }
  1318. }
  1319. if (options->HashedControlPassword && options->CookieAuthentication) {
  1320. log_fn(LOG_WARN,"Cannot enable both HashedControlPassword and CookieAuthentication");
  1321. result = -1;
  1322. }
  1323. if (check_nickname_list(options->ExitNodes, "ExitNodes"))
  1324. result = -1;
  1325. if (check_nickname_list(options->EntryNodes, "EntryNodes"))
  1326. result = -1;
  1327. if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes"))
  1328. result = -1;
  1329. if (check_nickname_list(options->RendNodes, "RendNodes"))
  1330. result = -1;
  1331. if (check_nickname_list(options->RendNodes, "RendExcludeNodes"))
  1332. result = -1;
  1333. if (check_nickname_list(options->MyFamily, "MyFamily"))
  1334. result = -1;
  1335. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  1336. if (check_nickname_list(cl->value, "NodeFamily"))
  1337. result = -1;
  1338. }
  1339. if (config_parse_addr_policy(options->ExitPolicy, &addr_policy)) {
  1340. log_fn(LOG_WARN, "Error in Exit Policy entry.");
  1341. result = -1;
  1342. }
  1343. if (server_mode(options)) {
  1344. exit_policy_implicitly_allows_local_networks(addr_policy, 1);
  1345. }
  1346. /* The rest of these calls *append* to addr_policy. So don't actually
  1347. * use the results for anything other than checking if they parse! */
  1348. if (config_parse_addr_policy(options->DirPolicy, &addr_policy)) {
  1349. log_fn(LOG_WARN, "Error in DirPolicy entry.");
  1350. result = -1;
  1351. }
  1352. if (config_parse_addr_policy(options->SocksPolicy, &addr_policy)) {
  1353. log_fn(LOG_WARN, "Error in SocksPolicy entry.");
  1354. result = -1;
  1355. }
  1356. addr_policy_free(addr_policy);
  1357. for (cl = options->RedirectExit; cl; cl = cl->next) {
  1358. if (parse_redirect_line(NULL, cl)<0)
  1359. result = -1;
  1360. }
  1361. if (!options->DirServers) {
  1362. add_default_trusted_dirservers(options);
  1363. } else {
  1364. for (cl = options->DirServers; cl; cl = cl->next) {
  1365. if (parse_dir_server_line(cl->value, 1)<0)
  1366. result = -1;
  1367. }
  1368. }
  1369. if (rend_config_services(options, 1) < 0)
  1370. result = -1;
  1371. return result;
  1372. }
  1373. /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
  1374. * equal strings. */
  1375. static int
  1376. opt_streq(const char *s1, const char *s2)
  1377. {
  1378. if (!s1 && !s2)
  1379. return 1;
  1380. else if (s1 && s2 && !strcmp(s1,s2))
  1381. return 1;
  1382. else
  1383. return 0;
  1384. }
  1385. /** Check if any of the previous options have changed but aren't allowed to. */
  1386. static int
  1387. options_transition_allowed(or_options_t *old, or_options_t *new_val) {
  1388. if (!old)
  1389. return 0;
  1390. if (!opt_streq(old->PidFile, new_val->PidFile)) {
  1391. log_fn(LOG_WARN,"PidFile is not allowed to change. Failing.");
  1392. return -1;
  1393. }
  1394. if (old->RunAsDaemon && !new_val->RunAsDaemon) {
  1395. log_fn(LOG_WARN,"During reload, change from RunAsDaemon=1 to =0 not allowed. Failing.");
  1396. return -1;
  1397. }
  1398. if (old->ORPort != new_val->ORPort) {
  1399. log_fn(LOG_WARN,"During reload, changing ORPort is not allowed. Failing.");
  1400. return -1;
  1401. }
  1402. if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
  1403. log_fn(LOG_WARN,"During reload, changing DataDirectory (%s->%s) is not allowed. Failing.", old->DataDirectory, new_val->DataDirectory);
  1404. return -1;
  1405. }
  1406. if (!opt_streq(old->User, new_val->User)) {
  1407. log_fn(LOG_WARN,"During reload, changing User is not allowed. Failing.");
  1408. return -1;
  1409. }
  1410. if (!opt_streq(old->Group, new_val->Group)) {
  1411. log_fn(LOG_WARN,"During reload, changing User is not allowed. Failing.");
  1412. return -1;
  1413. }
  1414. return 0;
  1415. }
  1416. #ifdef MS_WINDOWS
  1417. /** Return the directory on windows where we expect to find our application
  1418. * data. */
  1419. static char *get_windows_conf_root(void)
  1420. {
  1421. static int is_set = 0;
  1422. static char path[MAX_PATH+1];
  1423. LPITEMIDLIST idl;
  1424. IMalloc *m;
  1425. HRESULT result;
  1426. if (is_set)
  1427. return path;
  1428. /* Find X:\documents and settings\username\application data\ .
  1429. * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
  1430. */
  1431. if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
  1432. &idl))) {
  1433. GetCurrentDirectory(MAX_PATH, path);
  1434. is_set = 1;
  1435. 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);
  1436. return path;
  1437. }
  1438. /* Convert the path from an "ID List" (whatever that is!) to a path. */
  1439. result = SHGetPathFromIDList(idl, path);
  1440. /* Now we need to free the */
  1441. SHGetMalloc(&m);
  1442. if (m) {
  1443. m->lpVtbl->Free(m, idl);
  1444. m->lpVtbl->Release(m);
  1445. }
  1446. if (!SUCCEEDED(result)) {
  1447. return NULL;
  1448. }
  1449. strlcat(path,"\\tor",MAX_PATH);
  1450. is_set = 1;
  1451. return path;
  1452. }
  1453. #endif
  1454. /** Return the default location for our torrc file. */
  1455. static char *
  1456. get_default_conf_file(void)
  1457. {
  1458. #ifdef MS_WINDOWS
  1459. char *path = tor_malloc(MAX_PATH);
  1460. strlcpy(path, get_windows_conf_root(), MAX_PATH);
  1461. strlcat(path,"\\torrc",MAX_PATH);
  1462. return path;
  1463. #else
  1464. return tor_strdup(CONFDIR "/torrc");
  1465. #endif
  1466. }
  1467. /** Verify whether lst is a string containing valid-looking space-separated
  1468. * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
  1469. */
  1470. static int check_nickname_list(const char *lst, const char *name)
  1471. {
  1472. int r = 0;
  1473. smartlist_t *sl;
  1474. if (!lst)
  1475. return 0;
  1476. sl = smartlist_create();
  1477. smartlist_split_string(sl, lst, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1478. SMARTLIST_FOREACH(sl, const char *, s,
  1479. {
  1480. if (!is_legal_nickname_or_hexdigest(s)) {
  1481. log_fn(LOG_WARN, "Invalid nickname '%s' in %s line", s, name);
  1482. r = -1;
  1483. }
  1484. });
  1485. SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
  1486. smartlist_free(sl);
  1487. return r;
  1488. }
  1489. /** Read a configuration file into <b>options</b>, finding the configuration
  1490. * file location based on the command line. After loading the options,
  1491. * validate them for consistency, then take actions based on them.
  1492. * Return 0 if success, -1 if failure. */
  1493. int
  1494. init_from_config(int argc, char **argv)
  1495. {
  1496. or_options_t *oldoptions, *newoptions;
  1497. struct config_line_t *cl;
  1498. char *cf=NULL, *fname=NULL;
  1499. int i, retval;
  1500. int using_default_torrc;
  1501. static char **backup_argv;
  1502. static int backup_argc;
  1503. if (argv) { /* first time we're called. save commandline args */
  1504. backup_argv = argv;
  1505. backup_argc = argc;
  1506. oldoptions = NULL;
  1507. } else { /* we're reloading. need to clean up old options first. */
  1508. argv = backup_argv;
  1509. argc = backup_argc;
  1510. oldoptions = get_options();
  1511. }
  1512. if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
  1513. print_usage();
  1514. exit(0);
  1515. }
  1516. if (argc > 1 && (!strcmp(argv[1],"--version"))) {
  1517. printf("Tor version %s.\n",VERSION);
  1518. if (argc > 2 && (!strcmp(argv[2],"--version"))) {
  1519. print_cvs_version();
  1520. }
  1521. exit(0);
  1522. }
  1523. newoptions = tor_malloc_zero(sizeof(or_options_t));
  1524. options_init(newoptions);
  1525. /* learn config file name, get config lines, assign them */
  1526. fname = NULL;
  1527. using_default_torrc = 1;
  1528. newoptions->command = CMD_RUN_TOR;
  1529. for (i = 1; i < argc; ++i) {
  1530. if (i < argc-1 && !strcmp(argv[i],"-f")) {
  1531. if (fname) {
  1532. log(LOG_WARN, "Duplicate -f options on command line.");
  1533. tor_free(fname);
  1534. }
  1535. fname = tor_strdup(argv[i+1]);
  1536. using_default_torrc = 0;
  1537. ++i;
  1538. } else if (!strcmp(argv[i],"--list-fingerprint")) {
  1539. newoptions->command = CMD_LIST_FINGERPRINT;
  1540. } else if (!strcmp(argv[i],"--hash-password")) {
  1541. newoptions->command = CMD_HASH_PASSWORD;
  1542. newoptions->command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
  1543. ++i;
  1544. }
  1545. }
  1546. if (using_default_torrc) {
  1547. /* didn't find one, try CONFDIR */
  1548. char *fn;
  1549. fn = get_default_conf_file();
  1550. if (fn && file_status(fn) == FN_FILE) {
  1551. fname = fn;
  1552. } else {
  1553. tor_free(fn);
  1554. #ifndef MS_WINDOWS
  1555. fn = expand_filename("~/.torrc");
  1556. if (fn && file_status(fn) == FN_FILE) {
  1557. fname = fn;
  1558. } else {
  1559. tor_free(fn);
  1560. fname = get_default_conf_file();
  1561. }
  1562. #else
  1563. fname = get_default_conf_file();
  1564. #endif
  1565. }
  1566. }
  1567. tor_assert(fname);
  1568. log(LOG_DEBUG, "Opening config file '%s'", fname);
  1569. if (file_status(fname) != FN_FILE ||
  1570. !(cf = read_file_to_str(fname,0))) {
  1571. if (using_default_torrc == 1) {
  1572. log(LOG_NOTICE, "Configuration file '%s' not present, "
  1573. "using reasonable defaults.", fname);
  1574. tor_free(fname); /* sets fname to NULL */
  1575. } else {
  1576. log(LOG_WARN, "Unable to open configuration file '%s'.", fname);
  1577. tor_free(fname);
  1578. goto err;
  1579. }
  1580. } else { /* it opened successfully. use it. */
  1581. retval = config_get_lines(cf, &cl);
  1582. tor_free(cf);
  1583. if (retval < 0)
  1584. goto err;
  1585. retval = config_assign(newoptions, cl, 0);
  1586. config_free_lines(cl);
  1587. if (retval < 0)
  1588. goto err;
  1589. }
  1590. /* Go through command-line variables too */
  1591. cl = config_get_commandlines(argc,argv);
  1592. retval = config_assign(newoptions,cl,0);
  1593. config_free_lines(cl);
  1594. if (retval < 0)
  1595. goto err;
  1596. /* Validate newoptions */
  1597. if (options_validate(newoptions) < 0)
  1598. goto err;
  1599. if (options_transition_allowed(oldoptions, newoptions) < 0)
  1600. goto err;
  1601. set_options(newoptions); /* frees and replaces old options */
  1602. if (options_act() < 0) { /* acting on them failed. die. */
  1603. log_fn(LOG_ERR,"Acting on config options left us in a broken state. Dying.");
  1604. exit(1);
  1605. }
  1606. tor_free(config_fname);
  1607. config_fname = fname;
  1608. return 0;
  1609. err:
  1610. tor_free(fname);
  1611. options_free(newoptions);
  1612. return -1;
  1613. }
  1614. static void
  1615. config_register_addressmaps(or_options_t *options) {
  1616. smartlist_t *elts;
  1617. struct config_line_t *opt;
  1618. char *from, *to;
  1619. elts = smartlist_create();
  1620. for (opt = options->AddressMap; opt; opt = opt->next) {
  1621. smartlist_split_string(elts, opt->value, NULL,
  1622. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  1623. if (smartlist_len(elts) >= 2) {
  1624. from = smartlist_get(elts,0);
  1625. to = smartlist_get(elts,1);
  1626. addressmap_register(from, tor_strdup(to), 0);
  1627. } else {
  1628. log_fn(LOG_WARN,"AddressMap '%s' has too few arguments. Ignoring.", opt->value);
  1629. }
  1630. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  1631. smartlist_clear(elts);
  1632. }
  1633. smartlist_free(elts);
  1634. }
  1635. /** If <b>range</b> is of the form MIN-MAX, for MIN and MAX both
  1636. * recognized log severity levels, set *<b>min_out</b> to MIN and
  1637. * *<b>max_out</b> to MAX and return 0. Else, if <b>range<b> is of
  1638. * the form MIN, act as if MIN-err had been specified. Else, warn and
  1639. * return -1.
  1640. */
  1641. static int
  1642. parse_log_severity_range(const char *range, int *min_out, int *max_out)
  1643. {
  1644. int levelMin, levelMax;
  1645. const char *cp;
  1646. cp = strchr(range, '-');
  1647. if (cp) {
  1648. if (cp == range) {
  1649. levelMin = LOG_DEBUG;
  1650. } else {
  1651. char *tmp_sev = tor_strndup(range, cp - range);
  1652. levelMin = parse_log_level(tmp_sev);
  1653. if (levelMin < 0) {
  1654. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  1655. "err|warn|notice|info|debug", tmp_sev);
  1656. tor_free(tmp_sev);
  1657. return -1;
  1658. }
  1659. tor_free(tmp_sev);
  1660. }
  1661. if (!*(cp+1)) {
  1662. levelMax = LOG_ERR;
  1663. } else {
  1664. levelMax = parse_log_level(cp+1);
  1665. if (levelMax < 0) {
  1666. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  1667. "err|warn|notice|info|debug", cp+1);
  1668. return -1;
  1669. }
  1670. }
  1671. } else {
  1672. levelMin = parse_log_level(range);
  1673. if (levelMin < 0) {
  1674. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  1675. "err|warn|notice|info|debug", range);
  1676. return -1;
  1677. }
  1678. levelMax = LOG_ERR;
  1679. }
  1680. *min_out = levelMin;
  1681. *max_out = levelMax;
  1682. return 0;
  1683. }
  1684. /** Try to convert a pair of old-style logging options [LogLevel, and
  1685. * (LogFile/Syslog)] to a new-style option, and add the new option to
  1686. * options->Logs. */
  1687. static int
  1688. convert_log_option(or_options_t *options, struct config_line_t *level_opt,
  1689. struct config_line_t *file_opt, int isDaemon)
  1690. {
  1691. int levelMin = -1, levelMax = -1;
  1692. if (level_opt) {
  1693. if (parse_log_severity_range(level_opt->value, &levelMin, &levelMax))
  1694. return -1;
  1695. }
  1696. if (levelMin < 0 && levelMax < 0) {
  1697. levelMin = LOG_NOTICE;
  1698. levelMax = LOG_ERR;
  1699. } else if (levelMin < 0) {
  1700. levelMin = levelMax;
  1701. } else {
  1702. levelMax = LOG_ERR;
  1703. }
  1704. if (file_opt && !strcasecmp(file_opt->key, "LogFile")) {
  1705. if (add_single_log_option(options, levelMin, levelMax, "file", file_opt->value) < 0) {
  1706. log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", file_opt->value,
  1707. strerror(errno));
  1708. return -1;
  1709. }
  1710. } else if (file_opt && !strcasecmp(file_opt->key, "SysLog")) {
  1711. if (add_single_log_option(options, levelMin, levelMax, "syslog", NULL) < 0)
  1712. return -1;
  1713. } else if (!isDaemon) {
  1714. add_single_log_option(options, levelMin, levelMax, "stdout", NULL);
  1715. }
  1716. return 0;
  1717. }
  1718. /**
  1719. * Initialize the logs based on the configuration file.
  1720. */
  1721. int
  1722. config_init_logs(or_options_t *options, int validate_only)
  1723. {
  1724. struct config_line_t *opt;
  1725. int ok;
  1726. smartlist_t *elts;
  1727. ok = 1;
  1728. elts = smartlist_create();
  1729. for (opt = options->Logs; opt; opt = opt->next) {
  1730. int levelMin=LOG_DEBUG, levelMax=LOG_ERR;
  1731. smartlist_split_string(elts, opt->value, NULL,
  1732. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  1733. if (smartlist_len(elts) == 0) {
  1734. log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
  1735. ok = 0; goto cleanup;
  1736. }
  1737. if (parse_log_severity_range(smartlist_get(elts,0), &levelMin, &levelMax)) {
  1738. ok = 0; goto cleanup;
  1739. }
  1740. if (smartlist_len(elts) < 2) { /* only loglevels were provided */
  1741. if (!validate_only)
  1742. add_stream_log(levelMin, levelMax, "<stdout>", stdout);
  1743. goto cleanup;
  1744. }
  1745. if (!strcasecmp(smartlist_get(elts,1), "file")) {
  1746. if (smartlist_len(elts) != 3) {
  1747. log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
  1748. ok = 0; goto cleanup;
  1749. }
  1750. if (!validate_only)
  1751. add_file_log(levelMin, levelMax, smartlist_get(elts, 2));
  1752. goto cleanup;
  1753. }
  1754. if (smartlist_len(elts) != 2) {
  1755. log_fn(LOG_WARN, "Bad syntax on Log option 'Log %s'", opt->value);
  1756. ok = 0; goto cleanup;
  1757. }
  1758. if (!strcasecmp(smartlist_get(elts,1), "stdout")) {
  1759. if (!validate_only) {
  1760. add_stream_log(levelMin, levelMax, "<stdout>", stdout);
  1761. close_temp_logs();
  1762. }
  1763. } else if (!strcasecmp(smartlist_get(elts,1), "stderr")) {
  1764. if (!validate_only) {
  1765. add_stream_log(levelMin, levelMax, "<stderr>", stderr);
  1766. close_temp_logs();
  1767. }
  1768. } else if (!strcasecmp(smartlist_get(elts,1), "syslog")) {
  1769. #ifdef HAVE_SYSLOG_H
  1770. if (!validate_only)
  1771. add_syslog_log(levelMin, levelMax);
  1772. #else
  1773. log_fn(LOG_WARN, "Syslog is not supported in this compilation.");
  1774. #endif
  1775. } else {
  1776. log_fn(LOG_WARN, "Unrecognized log type %s",
  1777. (const char*)smartlist_get(elts,1));
  1778. if (strchr(smartlist_get(elts,1), '/')) {
  1779. log_fn(LOG_WARN, "Did you mean to say 'Log file %s' ?",
  1780. (const char *)smartlist_get(elts,1));
  1781. }
  1782. ok = 0; goto cleanup;
  1783. }
  1784. cleanup:
  1785. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  1786. smartlist_clear(elts);
  1787. }
  1788. smartlist_free(elts);
  1789. if (!validate_only)
  1790. close_temp_logs();
  1791. return ok?0:-1;
  1792. }
  1793. /** Add a single option of the form Log min-max <type> [fname] to options. */
  1794. static int
  1795. add_single_log_option(or_options_t *options, int minSeverity, int maxSeverity,
  1796. const char *type, const char *fname)
  1797. {
  1798. char buf[512];
  1799. int n;
  1800. n = tor_snprintf(buf, sizeof(buf), "%s%s%s %s%s%s",
  1801. log_level_to_string(minSeverity),
  1802. maxSeverity == LOG_ERR ? "" : "-",
  1803. maxSeverity == LOG_ERR ? "" : log_level_to_string(maxSeverity),
  1804. type, fname?" ":"", fname?fname:"");
  1805. if (n<0) {
  1806. log_fn(LOG_WARN, "Normalized log option too long.");
  1807. return -1;
  1808. }
  1809. log(LOG_WARN, "The old LogLevel/LogFile/DebugLogFile/SysLog options are deprecated, and will go away soon. Your new torrc line should be: 'Log %s'", buf);
  1810. config_line_append(&options->Logs, "Log", buf);
  1811. return 0;
  1812. }
  1813. /** Convert all old-style logging options to new-style Log options. Return 0
  1814. * on success, -1 on failure. */
  1815. static int
  1816. normalize_log_options(or_options_t *options)
  1817. {
  1818. /* The order of options is: Level? (File Level?)+
  1819. */
  1820. struct config_line_t *opt = options->OldLogOptions;
  1821. /* Special case for if first option is LogLevel. */
  1822. if (opt && !strcasecmp(opt->key, "LogLevel")) {
  1823. if (opt->next && (!strcasecmp(opt->next->key, "LogFile") ||
  1824. !strcasecmp(opt->next->key, "SysLog"))) {
  1825. if (convert_log_option(options, opt, opt->next, options->RunAsDaemon) < 0)
  1826. return -1;
  1827. opt = opt->next->next;
  1828. } else if (!opt->next) {
  1829. if (convert_log_option(options, opt, NULL, options->RunAsDaemon) < 0)
  1830. return -1;
  1831. opt = opt->next;
  1832. } else {
  1833. ; /* give warning below */
  1834. }
  1835. }
  1836. while (opt) {
  1837. if (!strcasecmp(opt->key, "LogLevel")) {
  1838. log_fn(LOG_WARN, "Two LogLevel options in a row without intervening LogFile or SysLog");
  1839. opt = opt->next;
  1840. } else {
  1841. tor_assert(!strcasecmp(opt->key, "LogFile") ||
  1842. !strcasecmp(opt->key, "SysLog"));
  1843. if (opt->next && !strcasecmp(opt->next->key, "LogLevel")) {
  1844. /* LogFile/SysLog followed by LogLevel */
  1845. if (convert_log_option(options,opt->next,opt, options->RunAsDaemon) < 0)
  1846. return -1;
  1847. opt = opt->next->next;
  1848. } else {
  1849. /* LogFile/SysLog followed by LogFile/SysLog or end of list. */
  1850. if (convert_log_option(options,NULL, opt, options->RunAsDaemon) < 0)
  1851. return -1;
  1852. opt = opt->next;
  1853. }
  1854. }
  1855. }
  1856. if (options->DebugLogFile) {
  1857. if (add_single_log_option(options, LOG_DEBUG, LOG_ERR, "file", options->DebugLogFile) < 0)
  1858. return -1;
  1859. }
  1860. tor_free(options->DebugLogFile);
  1861. config_free_lines(options->OldLogOptions);
  1862. options->OldLogOptions = NULL;
  1863. return 0;
  1864. }
  1865. /**
  1866. * Given a linked list of config lines containing "allow" and "deny" tokens,
  1867. * parse them and append the result to <b>dest</b>. Return -1 if any tokens
  1868. * are malformed, else return 0.
  1869. */
  1870. int
  1871. config_parse_addr_policy(struct config_line_t *cfg,
  1872. addr_policy_t **dest)
  1873. {
  1874. addr_policy_t **nextp;
  1875. smartlist_t *entries;
  1876. int r = 0;
  1877. if (!cfg)
  1878. return 0;
  1879. nextp = dest;
  1880. while (*nextp)
  1881. nextp = &((*nextp)->next);
  1882. entries = smartlist_create();
  1883. for (; cfg; cfg = cfg->next) {
  1884. smartlist_split_string(entries, cfg->value, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1885. SMARTLIST_FOREACH(entries, const char *, ent,
  1886. {
  1887. log_fn(LOG_DEBUG,"Adding new entry '%s'",ent);
  1888. *nextp = router_parse_addr_policy_from_string(ent);
  1889. if (*nextp) {
  1890. nextp = &((*nextp)->next);
  1891. } else {
  1892. log_fn(LOG_WARN,"Malformed policy %s.", ent);
  1893. r = -1;
  1894. }
  1895. });
  1896. SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
  1897. smartlist_clear(entries);
  1898. }
  1899. smartlist_free(entries);
  1900. return r;
  1901. }
  1902. /** Release all storage held by <b>p</b> */
  1903. void
  1904. addr_policy_free(addr_policy_t *p) {
  1905. addr_policy_t *e;
  1906. while (p) {
  1907. e = p;
  1908. p = p->next;
  1909. tor_free(e->string);
  1910. tor_free(e);
  1911. }
  1912. }
  1913. /** Parse a single RedirectExit line's contents from <b>line</b>. If
  1914. * they are valid, and <b>result</b> is not NULL, add an element to
  1915. * <b>result</b> and return 0. Else if they are valid, return 0.
  1916. * Else return -1. */
  1917. static int
  1918. parse_redirect_line(smartlist_t *result, struct config_line_t *line)
  1919. {
  1920. smartlist_t *elements = NULL;
  1921. exit_redirect_t *r;
  1922. tor_assert(line);
  1923. r = tor_malloc_zero(sizeof(exit_redirect_t));
  1924. elements = smartlist_create();
  1925. smartlist_split_string(elements, line->value, NULL,
  1926. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1927. if (smartlist_len(elements) != 2) {
  1928. log_fn(LOG_WARN, "Wrong number of elements in RedirectExit line");
  1929. goto err;
  1930. }
  1931. if (parse_addr_and_port_range(smartlist_get(elements,0),&r->addr,&r->mask,
  1932. &r->port_min,&r->port_max)) {
  1933. log_fn(LOG_WARN, "Error parsing source address in RedirectExit line");
  1934. goto err;
  1935. }
  1936. if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
  1937. r->is_redirect = 0;
  1938. } else {
  1939. if (parse_addr_port(smartlist_get(elements,1),NULL,&r->addr_dest,
  1940. &r->port_dest)) {
  1941. log_fn(LOG_WARN, "Error parsing dest address in RedirectExit line");
  1942. goto err;
  1943. }
  1944. r->is_redirect = 1;
  1945. }
  1946. goto done;
  1947. err:
  1948. tor_free(r);
  1949. done:
  1950. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  1951. smartlist_free(elements);
  1952. if (r) {
  1953. if (result)
  1954. smartlist_add(result, r);
  1955. else
  1956. tor_free(r);
  1957. return 0;
  1958. } else {
  1959. return -1;
  1960. }
  1961. }
  1962. /** Read the contents of a DirServer line from <b>line</b>. Return 0
  1963. * if the line is well-formed, and 0 if it isn't. If
  1964. * <b>validate_only</b> is 0, and the line is well-formed, then add
  1965. * the dirserver described in the line as a valid server. */
  1966. static int
  1967. parse_dir_server_line(const char *line, int validate_only)
  1968. {
  1969. smartlist_t *items = NULL;
  1970. int r;
  1971. char *addrport, *address=NULL;
  1972. uint16_t port;
  1973. char digest[DIGEST_LEN];
  1974. items = smartlist_create();
  1975. smartlist_split_string(items, line, NULL,
  1976. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  1977. if (smartlist_len(items) < 2) {
  1978. log_fn(LOG_WARN, "Too few arguments to DirServer line.");
  1979. goto err;
  1980. }
  1981. addrport = smartlist_get(items, 0);
  1982. if (parse_addr_port(addrport, &address, NULL, &port)<0) {
  1983. log_fn(LOG_WARN, "Error parsing DirServer address '%s'", addrport);
  1984. goto err;
  1985. }
  1986. if (!port) {
  1987. log_fn(LOG_WARN, "Missing port in DirServer address '%s'",addrport);
  1988. goto err;
  1989. }
  1990. tor_strstrip(smartlist_get(items, 1), " ");
  1991. if (strlen(smartlist_get(items, 1)) != HEX_DIGEST_LEN) {
  1992. log_fn(LOG_WARN, "Key digest for DirServer is wrong length.");
  1993. goto err;
  1994. }
  1995. if (base16_decode(digest, DIGEST_LEN,
  1996. smartlist_get(items,1), HEX_DIGEST_LEN)<0) {
  1997. log_fn(LOG_WARN, "Unable to decode DirServer key digest.");
  1998. goto err;
  1999. }
  2000. if (!validate_only) {
  2001. log_fn(LOG_DEBUG, "Trusted dirserver at %s:%d (%s)", address, (int)port,
  2002. (char*)smartlist_get(items,1));
  2003. add_trusted_dir_server(address, port, digest);
  2004. }
  2005. r = 0;
  2006. goto done;
  2007. err:
  2008. r = -1;
  2009. done:
  2010. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  2011. smartlist_free(items);
  2012. tor_free(address);
  2013. return r;
  2014. }
  2015. /** Adjust the value of options->DataDirectory, or fill it in if it's
  2016. * absent. Return 0 on success, -1 on failure. */
  2017. static int
  2018. normalize_data_directory(or_options_t *options) {
  2019. #ifdef MS_WINDOWS
  2020. char *p;
  2021. if (options->DataDirectory)
  2022. return 0; /* all set */
  2023. p = tor_malloc(MAX_PATH);
  2024. strlcpy(p,get_windows_conf_root(),MAX_PATH);
  2025. options->DataDirectory = p;
  2026. return 0;
  2027. #else
  2028. const char *d = options->DataDirectory;
  2029. if (!d)
  2030. d = "~/.tor";
  2031. if (strncmp(d,"~/",2) == 0) {
  2032. char *fn = expand_filename(d);
  2033. if (!fn) {
  2034. log_fn(LOG_ERR,"Failed to expand filename '%s'.", d);
  2035. return -1;
  2036. }
  2037. if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
  2038. /* If our homedir is /, we probably don't want to use it. */
  2039. /* XXXX Default to /var/lib/tor? */
  2040. log_fn(LOG_WARN, "Defaulting to 'DataDirectory %s', which may not be what you want", fn);
  2041. }
  2042. tor_free(options->DataDirectory);
  2043. options->DataDirectory = fn;
  2044. }
  2045. return 0;
  2046. #endif
  2047. }
  2048. /** Check and normalize the value of options->DataDirectory; return 0 if it
  2049. * sane, -1 otherwise. */
  2050. static int
  2051. validate_data_directory(or_options_t *options) {
  2052. if (normalize_data_directory(options) < 0)
  2053. return -1;
  2054. tor_assert(options->DataDirectory);
  2055. if (strlen(options->DataDirectory) > (512-128)) {
  2056. log_fn(LOG_ERR, "DataDirectory is too long.");
  2057. return -1;
  2058. }
  2059. #if 0
  2060. if (check_private_dir(options->DataDirectory, CPD_CHECK != 0)) {
  2061. log_fn(LOG_WARN, "Can't create directory %s", options->DataDirectory);
  2062. return -1;
  2063. }
  2064. #endif
  2065. return 0;
  2066. }
  2067. #define GENERATED_FILE_PREFIX "# This file was generated by Tor; if you edit it, comments will not be preserved"
  2068. /** Save a configuration file for the configuration in <b>options</b>
  2069. * into the file <b>fname</b>. If the file already exists, and
  2070. * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
  2071. * replace it. Return 0 on success, -1 on failure. */
  2072. static int
  2073. write_configuration_file(const char *fname, or_options_t *options)
  2074. {
  2075. char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
  2076. int rename_old = 0, r;
  2077. size_t len;
  2078. if (fname) {
  2079. switch (file_status(fname)) {
  2080. case FN_FILE:
  2081. old_val = read_file_to_str(fname, 0);
  2082. if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
  2083. rename_old = 1;
  2084. }
  2085. tor_free(old_val);
  2086. break;
  2087. case FN_NOENT:
  2088. break;
  2089. default:
  2090. log_fn(LOG_WARN,"Config file %s is not a file? Failing.", fname);
  2091. return -1;
  2092. }
  2093. }
  2094. if (!(new_conf = config_dump_options(options, 1))) {
  2095. log_fn(LOG_WARN, "Couldn't get configuration string");
  2096. goto err;
  2097. }
  2098. len = strlen(new_conf)+128;
  2099. new_val = tor_malloc(len);
  2100. tor_snprintf(new_val, len, "%s\n\n%s", GENERATED_FILE_PREFIX, new_conf);
  2101. if (rename_old) {
  2102. int i = 1;
  2103. size_t fn_tmp_len = strlen(fname)+32;
  2104. char *fn_tmp;
  2105. tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
  2106. fn_tmp = tor_malloc(fn_tmp_len);
  2107. while (1) {
  2108. if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
  2109. log_fn(LOG_WARN, "tor_snprintf failed inexplicably");
  2110. tor_free(fn_tmp);
  2111. goto err;
  2112. }
  2113. if (file_status(fn_tmp) == FN_NOENT)
  2114. break;
  2115. ++i;
  2116. }
  2117. log_fn(LOG_NOTICE, "Renaming old configuration file to %s", fn_tmp);
  2118. rename(fname, fn_tmp);
  2119. tor_free(fn_tmp);
  2120. }
  2121. write_str_to_file(fname, new_val, 0);
  2122. r = 0;
  2123. goto done;
  2124. err:
  2125. r = -1;
  2126. done:
  2127. tor_free(new_val);
  2128. tor_free(new_conf);
  2129. return r;
  2130. }
  2131. /**
  2132. * Save the current configuration file value to disk. Return 0 on
  2133. * success, -1 on failure.
  2134. **/
  2135. int
  2136. save_current_config(void)
  2137. {
  2138. char *fn;
  2139. if (config_fname) {
  2140. /* XXX This fails if we can't write to our configuration file.
  2141. * Arguably, we should try falling back to datadirectory or something.
  2142. * But just as arguably, we shouldn't. */
  2143. return write_configuration_file(config_fname, get_options());
  2144. }
  2145. fn = get_default_conf_file();
  2146. return write_configuration_file(fn, get_options());
  2147. }
  2148. struct unit_table_t {
  2149. const char *unit;
  2150. uint64_t multiplier;
  2151. };
  2152. static struct unit_table_t memory_units[] = {
  2153. { "", 1 },
  2154. { "b", 1<< 0 },
  2155. { "byte", 1<< 0 },
  2156. { "bytes", 1<< 0 },
  2157. { "kb", 1<<10 },
  2158. { "kilobyte", 1<<10 },
  2159. { "kilobytes", 1<<10 },
  2160. { "m", 1<<20 },
  2161. { "mb", 1<<20 },
  2162. { "megabyte", 1<<20 },
  2163. { "megabytes", 1<<20 },
  2164. { "gb", 1<<30 },
  2165. { "gigabyte", 1<<30 },
  2166. { "gigabytes", 1<<30 },
  2167. { "tb", U64_LITERAL(1)<<40 },
  2168. { "terabyte", U64_LITERAL(1)<<40 },
  2169. { "terabytes", U64_LITERAL(1)<<40 },
  2170. { NULL, 0 },
  2171. };
  2172. static struct unit_table_t time_units[] = {
  2173. { "", 1 },
  2174. { "second", 1 },
  2175. { "seconds", 1 },
  2176. { "minute", 60 },
  2177. { "minutes", 60 },
  2178. { "hour", 60*60 },
  2179. { "hours", 60*60 },
  2180. { "day", 24*60*60 },
  2181. { "days", 24*60*60 },
  2182. { "week", 7*24*60*60 },
  2183. { "weeks", 7*24*60*60 },
  2184. { NULL, 0 },
  2185. };
  2186. /** Parse a string <b>val</b> containing a number, zero or more
  2187. * spaces, and an optional unit string. If the unit appears in the
  2188. * table <b>u</b>, then multiply the number by the unit multiplier.
  2189. * On success, set *<b>ok</b> to 1 and return this product.
  2190. * Otherwise, set *<b>ok</b> to 0.
  2191. */
  2192. static uint64_t
  2193. config_parse_units(const char *val, struct unit_table_t *u, int *ok)
  2194. {
  2195. uint64_t v;
  2196. char *cp;
  2197. tor_assert(ok);
  2198. v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
  2199. if (!*ok)
  2200. return 0;
  2201. if (!cp) {
  2202. *ok = 1;
  2203. return v;
  2204. }
  2205. while (TOR_ISSPACE(*cp))
  2206. ++cp;
  2207. for ( ;u->unit;++u) {
  2208. if (!strcasecmp(u->unit, cp)) {
  2209. v *= u->multiplier;
  2210. *ok = 1;
  2211. return v;
  2212. }
  2213. }
  2214. log_fn(LOG_WARN, "Unknown unit '%s'.", cp);
  2215. *ok = 0;
  2216. return 0;
  2217. }
  2218. /** Parse a string in the format "number unit", where unit is a unit of
  2219. * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
  2220. * and return the number of bytes specified. Otherwise, set
  2221. * *<b>ok</b> to false and return 0. */
  2222. static uint64_t
  2223. config_parse_memunit(const char *s, int *ok) {
  2224. return config_parse_units(s, memory_units, ok);
  2225. }
  2226. /** Parse a string in the format "number unit", where unit is a unit of time.
  2227. * On success, set *<b>ok</b> to true and return the number of seconds in
  2228. * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
  2229. */
  2230. static int
  2231. config_parse_interval(const char *s, int *ok) {
  2232. uint64_t r;
  2233. r = config_parse_units(s, time_units, ok);
  2234. if (!ok)
  2235. return -1;
  2236. if (r > INT_MAX) {
  2237. log_fn(LOG_WARN, "Interval '%s' is too long", s);
  2238. *ok = 0;
  2239. return -1;
  2240. }
  2241. return (int)r;
  2242. }
  2243. static void
  2244. print_cvs_version(void)
  2245. {
  2246. extern const char aes_c_id[];
  2247. extern const char compat_c_id[];
  2248. extern const char container_c_id[];
  2249. extern const char crypto_c_id[];
  2250. extern const char log_c_id[];
  2251. extern const char torgzip_c_id[];
  2252. extern const char tortls_c_id[];
  2253. extern const char util_c_id[];
  2254. extern const char buffers_c_id[];
  2255. extern const char circuitbuild_c_id[];
  2256. extern const char circuitlist_c_id[];
  2257. extern const char circuituse_c_id[];
  2258. extern const char command_c_id[];
  2259. // extern const char config_c_id[];
  2260. extern const char connection_c_id[];
  2261. extern const char connection_edge_c_id[];
  2262. extern const char connection_or_c_id[];
  2263. extern const char control_c_id[];
  2264. extern const char cpuworker_c_id[];
  2265. extern const char directory_c_id[];
  2266. extern const char dirserv_c_id[];
  2267. extern const char dns_c_id[];
  2268. extern const char hibernate_c_id[];
  2269. extern const char main_c_id[];
  2270. extern const char onion_c_id[];
  2271. extern const char relay_c_id[];
  2272. extern const char rendclient_c_id[];
  2273. extern const char rendcommon_c_id[];
  2274. extern const char rendmid_c_id[];
  2275. extern const char rendservice_c_id[];
  2276. extern const char rephist_c_id[];
  2277. extern const char router_c_id[];
  2278. extern const char routerlist_c_id[];
  2279. extern const char routerparse_c_id[];
  2280. puts(AES_H_ID);
  2281. puts(COMPAT_H_ID);
  2282. puts(CONTAINER_H_ID);
  2283. puts(CRYPTO_H_ID);
  2284. puts(LOG_H_ID);
  2285. puts(TORGZIP_H_ID);
  2286. puts(TORINT_H_ID);
  2287. puts(TORTLS_H_ID);
  2288. puts(UTIL_H_ID);
  2289. puts(aes_c_id);
  2290. puts(compat_c_id);
  2291. puts(container_c_id);
  2292. puts(crypto_c_id);
  2293. puts(log_c_id);
  2294. puts(torgzip_c_id);
  2295. puts(tortls_c_id);
  2296. puts(util_c_id);
  2297. puts(OR_H_ID);
  2298. puts(buffers_c_id);
  2299. puts(circuitbuild_c_id);
  2300. puts(circuitlist_c_id);
  2301. puts(circuituse_c_id);
  2302. puts(command_c_id);
  2303. puts(config_c_id);
  2304. puts(connection_c_id);
  2305. puts(connection_edge_c_id);
  2306. puts(connection_or_c_id);
  2307. puts(control_c_id);
  2308. puts(cpuworker_c_id);
  2309. puts(directory_c_id);
  2310. puts(dirserv_c_id);
  2311. puts(dns_c_id);
  2312. puts(hibernate_c_id);
  2313. puts(main_c_id);
  2314. puts(onion_c_id);
  2315. puts(relay_c_id);
  2316. puts(rendclient_c_id);
  2317. puts(rendcommon_c_id);
  2318. puts(rendmid_c_id);
  2319. puts(rendservice_c_id);
  2320. puts(rephist_c_id);
  2321. puts(router_c_id);
  2322. puts(routerlist_c_id);
  2323. puts(routerparse_c_id);
  2324. }