config.c 85 KB

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