config.c 85 KB

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