config.c 80 KB

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