config.c 76 KB

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