PageParser.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. //
  2. // System.Web.UI.PageParser
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
  8. // Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System.Collections;
  30. using System.Collections.Specialized;
  31. using System.Globalization;
  32. using System.Security.Permissions;
  33. using System.Text;
  34. using System.Web.Compilation;
  35. using System.Web.Configuration;
  36. using System.Web.Hosting;
  37. using System.Web.Util;
  38. using System.IO;
  39. namespace System.Web.UI
  40. {
  41. // CAS - no InheritanceDemand here as the class is sealed
  42. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  43. public sealed class PageParser : TemplateControlParser
  44. {
  45. PagesEnableSessionState enableSessionState = PagesEnableSessionState.True;
  46. bool enableViewStateMac;
  47. bool enableViewStateMacSet;
  48. bool smartNavigation;
  49. bool haveTrace;
  50. bool trace;
  51. bool notBuffer;
  52. TraceMode tracemode = TraceMode.Default;
  53. string contentType;
  54. MainDirectiveAttribute <int> codepage;
  55. MainDirectiveAttribute <string> responseEncoding;
  56. MainDirectiveAttribute <int> lcid;
  57. MainDirectiveAttribute <string> clientTarget;
  58. MainDirectiveAttribute <string> masterPage;
  59. MainDirectiveAttribute <string> title;
  60. MainDirectiveAttribute <string> theme;
  61. #if NET_4_0
  62. MainDirectiveAttribute <string> metaDescription;
  63. MainDirectiveAttribute <string> metaKeywords;
  64. #endif
  65. string culture;
  66. string uiculture;
  67. string errorPage;
  68. bool validateRequest;
  69. bool async;
  70. int asyncTimeout = -1;
  71. Type masterType;
  72. string masterVirtualPath;
  73. string styleSheetTheme;
  74. bool enable_event_validation;
  75. bool maintainScrollPositionOnPostBack;
  76. int maxPageStateFieldLength = -1;
  77. Type previousPageType;
  78. string previousPageVirtualPath;
  79. public PageParser ()
  80. {
  81. LoadConfigDefaults ();
  82. }
  83. internal PageParser (string virtualPath, string inputFile, HttpContext context)
  84. {
  85. this.VirtualPath = new VirtualPath (virtualPath);
  86. Context = context;
  87. BaseVirtualDir = VirtualPathUtility.GetDirectory (virtualPath, false);
  88. InputFile = inputFile;
  89. SetBaseType (null);
  90. AddApplicationAssembly ();
  91. LoadConfigDefaults ();
  92. }
  93. internal PageParser (VirtualPath virtualPath, TextReader reader, HttpContext context)
  94. : this (virtualPath, null, reader, context)
  95. {
  96. }
  97. internal PageParser (VirtualPath virtualPath, string inputFile, TextReader reader, HttpContext context)
  98. {
  99. this.VirtualPath = virtualPath;
  100. Context = context;
  101. BaseVirtualDir = virtualPath.DirectoryNoNormalize;
  102. Reader = reader;
  103. if (String.IsNullOrEmpty (inputFile))
  104. InputFile = virtualPath.PhysicalPath;
  105. else
  106. InputFile = inputFile;
  107. SetBaseType (null);
  108. AddApplicationAssembly ();
  109. LoadConfigDefaults ();
  110. }
  111. internal override void LoadConfigDefaults ()
  112. {
  113. base.LoadConfigDefaults ();
  114. PagesSection ps = PagesConfig;
  115. notBuffer = !ps.Buffer;
  116. enableSessionState = ps.EnableSessionState;
  117. enableViewStateMac = ps.EnableViewStateMac;
  118. smartNavigation = ps.SmartNavigation;
  119. validateRequest = ps.ValidateRequest;
  120. string value = ps.MasterPageFile;
  121. if (value.Length > 0)
  122. masterPage = new MainDirectiveAttribute <string> (value, true);
  123. enable_event_validation = ps.EnableEventValidation;
  124. maxPageStateFieldLength = ps.MaxPageStateFieldLength;
  125. value = ps.Theme;
  126. if (value.Length > 0)
  127. theme = new MainDirectiveAttribute <string> (value, true);
  128. styleSheetTheme = ps.StyleSheetTheme;
  129. if (styleSheetTheme.Length == 0)
  130. styleSheetTheme = null;
  131. maintainScrollPositionOnPostBack = ps.MaintainScrollPositionOnPostBack;
  132. }
  133. public static IHttpHandler GetCompiledPageInstance (string virtualPath, string inputFile, HttpContext context)
  134. {
  135. bool isFake = false;
  136. if (!String.IsNullOrEmpty (inputFile))
  137. isFake = !inputFile.StartsWith (HttpRuntime.AppDomainAppPath);
  138. return BuildManager.CreateInstanceFromVirtualPath (new VirtualPath (virtualPath, inputFile, isFake), typeof (IHttpHandler)) as IHttpHandler;
  139. }
  140. internal override void ProcessMainAttributes (IDictionary atts)
  141. {
  142. // note: the 'enableSessionState' configuration property is
  143. // processed in a case-sensitive manner while the page-level
  144. // attribute is processed case-insensitive
  145. string enabless = GetString (atts, "EnableSessionState", null);
  146. if (enabless != null) {
  147. if (String.Compare (enabless, "readonly", true, Helpers.InvariantCulture) == 0)
  148. enableSessionState = PagesEnableSessionState.ReadOnly;
  149. else if (String.Compare (enabless, "true", true, Helpers.InvariantCulture) == 0)
  150. enableSessionState = PagesEnableSessionState.True;
  151. else if (String.Compare (enabless, "false", true, Helpers.InvariantCulture) == 0)
  152. enableSessionState = PagesEnableSessionState.False;
  153. else
  154. ThrowParseException ("Invalid value for enableSessionState: " + enabless);
  155. }
  156. string value = GetString (atts, "CodePage", null);
  157. if (value != null) {
  158. if (responseEncoding != null)
  159. ThrowParseException ("CodePage and ResponseEncoding are mutually exclusive.");
  160. if (!BaseParser.IsExpression (value)) {
  161. int cpval = -1;
  162. try {
  163. cpval = (int) UInt32.Parse (value);
  164. } catch {
  165. ThrowParseException ("Invalid value for CodePage: " + value);
  166. }
  167. try {
  168. Encoding.GetEncoding (cpval);
  169. } catch {
  170. ThrowParseException ("Unsupported codepage: " + value);
  171. }
  172. codepage = new MainDirectiveAttribute <int> (cpval, true);
  173. } else
  174. codepage = new MainDirectiveAttribute <int> (value);
  175. }
  176. value = GetString (atts, "ResponseEncoding", null);
  177. if (value != null) {
  178. if (codepage != null)
  179. ThrowParseException ("CodePage and ResponseEncoding are mutually exclusive.");
  180. if (!BaseParser.IsExpression (value)) {
  181. try {
  182. Encoding.GetEncoding (value);
  183. } catch {
  184. ThrowParseException ("Unsupported encoding: " + value);
  185. }
  186. responseEncoding = new MainDirectiveAttribute <string> (value, true);
  187. } else
  188. responseEncoding = new MainDirectiveAttribute <string> (value);
  189. }
  190. contentType = GetString (atts, "ContentType", null);
  191. value = GetString (atts, "LCID", null);
  192. if (value != null) {
  193. if (!BaseParser.IsExpression (value)) {
  194. int parsedLcid = -1;
  195. try {
  196. parsedLcid = (int) UInt32.Parse (value);
  197. } catch {
  198. ThrowParseException ("Invalid value for LCID: " + value);
  199. }
  200. CultureInfo ci = null;
  201. try {
  202. ci = new CultureInfo (parsedLcid);
  203. } catch {
  204. ThrowParseException ("Unsupported LCID: " + value);
  205. }
  206. if (ci.IsNeutralCulture) {
  207. string suggestedCulture = SuggestCulture (ci.Name);
  208. string fmt = "LCID attribute must be set to a non-neutral Culture.";
  209. if (suggestedCulture != null) {
  210. ThrowParseException (fmt + " Please try one of these: " +
  211. suggestedCulture);
  212. } else {
  213. ThrowParseException (fmt);
  214. }
  215. }
  216. lcid = new MainDirectiveAttribute <int> (parsedLcid, true);
  217. } else
  218. lcid = new MainDirectiveAttribute <int> (value);
  219. }
  220. culture = GetString (atts, "Culture", null);
  221. if (culture != null) {
  222. if (lcid != null)
  223. ThrowParseException ("Culture and LCID are mutually exclusive.");
  224. CultureInfo ci = null;
  225. try {
  226. if (!culture.StartsWith ("auto"))
  227. ci = new CultureInfo (culture);
  228. } catch {
  229. ThrowParseException ("Unsupported Culture: " + culture);
  230. }
  231. if (ci != null && ci.IsNeutralCulture) {
  232. string suggestedCulture = SuggestCulture (culture);
  233. string fmt = "Culture attribute must be set to a non-neutral Culture.";
  234. if (suggestedCulture != null)
  235. ThrowParseException (fmt +
  236. " Please try one of these: " + suggestedCulture);
  237. else
  238. ThrowParseException (fmt);
  239. }
  240. }
  241. uiculture = GetString (atts, "UICulture", null);
  242. if (uiculture != null) {
  243. CultureInfo ci = null;
  244. try {
  245. if (!uiculture.StartsWith ("auto"))
  246. ci = new CultureInfo (uiculture);
  247. } catch {
  248. ThrowParseException ("Unsupported Culture: " + uiculture);
  249. }
  250. if (ci != null && ci.IsNeutralCulture) {
  251. string suggestedCulture = SuggestCulture (uiculture);
  252. string fmt = "UICulture attribute must be set to a non-neutral Culture.";
  253. if (suggestedCulture != null)
  254. ThrowParseException (fmt +
  255. " Please try one of these: " + suggestedCulture);
  256. else
  257. ThrowParseException (fmt);
  258. }
  259. }
  260. string tracestr = GetString (atts, "Trace", null);
  261. if (tracestr != null) {
  262. haveTrace = true;
  263. atts ["Trace"] = tracestr;
  264. trace = GetBool (atts, "Trace", false);
  265. }
  266. string tracemodes = GetString (atts, "TraceMode", null);
  267. if (tracemodes != null) {
  268. bool valid = true;
  269. try {
  270. tracemode = (TraceMode) Enum.Parse (typeof (TraceMode), tracemodes, false);
  271. } catch {
  272. valid = false;
  273. }
  274. if (!valid || tracemode == TraceMode.Default)
  275. ThrowParseException ("The 'tracemode' attribute is case sensitive and must be " +
  276. "one of the following values: SortByTime, SortByCategory.");
  277. }
  278. errorPage = GetString (atts, "ErrorPage", null);
  279. validateRequest = GetBool (atts, "ValidateRequest", validateRequest);
  280. value = GetString (atts, "ClientTarget", null);
  281. if (value != null) {
  282. if (!BaseParser.IsExpression (value)) {
  283. value = value.Trim ();
  284. ClientTargetSection sec = GetConfigSection <ClientTargetSection> ("system.web/clientTarget");
  285. ClientTarget ct = null;
  286. if ((ct = sec.ClientTargets [value]) == null)
  287. value = value.ToLowerInvariant ();
  288. if (ct == null && (ct = sec.ClientTargets [value]) == null) {
  289. ThrowParseException (String.Format (
  290. "ClientTarget '{0}' is an invalid alias. See the " +
  291. "documentation for <clientTarget> config. section.",
  292. clientTarget));
  293. }
  294. value = ct.UserAgent;
  295. clientTarget = new MainDirectiveAttribute <string> (value, true);
  296. } else
  297. clientTarget = new MainDirectiveAttribute <string> (value);
  298. }
  299. notBuffer = !GetBool (atts, "Buffer", true);
  300. async = GetBool (atts, "Async", false);
  301. string asyncTimeoutVal = GetString (atts, "AsyncTimeout", null);
  302. if (asyncTimeoutVal != null) {
  303. try {
  304. asyncTimeout = Int32.Parse (asyncTimeoutVal);
  305. } catch (Exception) {
  306. ThrowParseException ("AsyncTimeout must be an integer value");
  307. }
  308. }
  309. value = GetString (atts, "MasterPageFile", masterPage != null ? masterPage.Value : null);
  310. if (!String.IsNullOrEmpty (value)) {
  311. if (!BaseParser.IsExpression (value)) {
  312. if (!HostingEnvironment.VirtualPathProvider.FileExists (value))
  313. ThrowParseFileNotFound (value);
  314. AddDependency (value);
  315. masterPage = new MainDirectiveAttribute <string> (value, true);
  316. } else
  317. masterPage = new MainDirectiveAttribute <string> (value);
  318. }
  319. value = GetString(atts, "Title", null);
  320. if (value != null) {
  321. if (!BaseParser.IsExpression (value))
  322. title = new MainDirectiveAttribute <string> (value, true);
  323. else
  324. title = new MainDirectiveAttribute <string> (value);
  325. }
  326. value = GetString (atts, "Theme", theme != null ? theme.Value : null);
  327. if (value != null) {
  328. if (!BaseParser.IsExpression (value))
  329. theme = new MainDirectiveAttribute <string> (value, true);
  330. else
  331. theme = new MainDirectiveAttribute <string> (value);
  332. }
  333. styleSheetTheme = GetString (atts, "StyleSheetTheme", styleSheetTheme);
  334. enable_event_validation = GetBool (atts, "EnableEventValidation", enable_event_validation);
  335. maintainScrollPositionOnPostBack = GetBool (atts, "MaintainScrollPositionOnPostBack", maintainScrollPositionOnPostBack);
  336. if (atts.Contains ("EnableViewState")) {
  337. enableViewStateMac = GetBool (atts, "EnableViewStateMac", enableViewStateMac);
  338. enableViewStateMacSet = true;
  339. }
  340. #if NET_4_0
  341. value = GetString (atts, "MetaDescription", null);
  342. if (value != null) {
  343. if (!BaseParser.IsExpression (value))
  344. metaDescription = new MainDirectiveAttribute <string> (value, true);
  345. else
  346. metaDescription = new MainDirectiveAttribute <string> (value);
  347. }
  348. value = GetString (atts, "MetaKeywords", null);
  349. if (value != null) {
  350. if (!BaseParser.IsExpression (value))
  351. metaKeywords = new MainDirectiveAttribute <string> (value, true);
  352. else
  353. metaKeywords = new MainDirectiveAttribute <string> (value);
  354. }
  355. #endif
  356. // Ignored by now
  357. GetString (atts, "SmartNavigation", null);
  358. base.ProcessMainAttributes (atts);
  359. }
  360. internal override void AddDirective (string directive, IDictionary atts)
  361. {
  362. bool isMasterType = String.Compare ("MasterType", directive, StringComparison.OrdinalIgnoreCase) == 0;
  363. bool isPreviousPageType = isMasterType ? false : String.Compare ("PreviousPageType", directive,
  364. StringComparison.OrdinalIgnoreCase) == 0;
  365. string typeName = null;
  366. string virtualPath = null;
  367. Type type = null;
  368. if (isMasterType || isPreviousPageType) {
  369. PageParserFilter pfilter = PageParserFilter;
  370. if (pfilter != null)
  371. pfilter.PreprocessDirective (directive.ToLowerInvariant (), atts);
  372. typeName = GetString (atts, "TypeName", null);
  373. virtualPath = GetString (atts, "VirtualPath", null);
  374. if (typeName != null && virtualPath != null)
  375. ThrowParseException (
  376. String.Format ("The '{0}' directive must have exactly one attribute: TypeName or VirtualPath", directive));
  377. if (typeName != null) {
  378. type = LoadType (typeName);
  379. if (type == null)
  380. ThrowParseException (String.Format ("Could not load type '{0}'.", typeName));
  381. if (isMasterType)
  382. masterType = type;
  383. else
  384. previousPageType = type;
  385. } else if (!String.IsNullOrEmpty (virtualPath)) {
  386. if (!HostingEnvironment.VirtualPathProvider.FileExists (virtualPath))
  387. ThrowParseFileNotFound (virtualPath);
  388. AddDependency (virtualPath);
  389. if (isMasterType)
  390. masterVirtualPath = virtualPath;
  391. else
  392. previousPageVirtualPath = virtualPath;
  393. } else
  394. ThrowParseException (String.Format ("The {0} directive must have either a TypeName or a VirtualPath attribute.", directive));
  395. if (type != null)
  396. AddAssembly (type.Assembly, true);
  397. } else
  398. base.AddDirective (directive, atts);
  399. }
  400. static string SuggestCulture (string culture)
  401. {
  402. string retval = null;
  403. foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.SpecificCultures)) {
  404. if (ci.Name.StartsWith (culture))
  405. retval += ci.Name + " ";
  406. }
  407. return retval;
  408. }
  409. #if !NET_4_0
  410. public static
  411. #endif
  412. Type GetCompiledPageType (string virtualPath, string inputFile, HttpContext context)
  413. {
  414. return BuildManager.GetCompiledType (virtualPath);
  415. }
  416. protected override Type CompileIntoType ()
  417. {
  418. AspGenerator generator = new AspGenerator (this);
  419. return generator.GetCompiledType ();
  420. }
  421. internal bool EnableSessionState {
  422. get {
  423. return enableSessionState == PagesEnableSessionState.True ||
  424. ReadOnlySessionState;
  425. }
  426. }
  427. internal bool EnableViewStateMac {
  428. get { return enableViewStateMac; }
  429. }
  430. internal bool EnableViewStateMacSet {
  431. get { return enableViewStateMacSet; }
  432. }
  433. internal bool SmartNavigation {
  434. get { return smartNavigation; }
  435. }
  436. internal bool ReadOnlySessionState {
  437. get {
  438. return enableSessionState == PagesEnableSessionState.ReadOnly;
  439. }
  440. }
  441. internal bool HaveTrace {
  442. get { return haveTrace; }
  443. }
  444. internal bool Trace {
  445. get { return trace; }
  446. }
  447. internal TraceMode TraceMode {
  448. get { return tracemode; }
  449. }
  450. internal override string DefaultBaseTypeName {
  451. get { return PagesConfig.PageBaseType; }
  452. }
  453. internal override string DefaultDirectiveName {
  454. get { return "page"; }
  455. }
  456. internal string ContentType {
  457. get { return contentType; }
  458. }
  459. internal MainDirectiveAttribute <string> ResponseEncoding {
  460. get { return responseEncoding; }
  461. }
  462. internal MainDirectiveAttribute <int> CodePage {
  463. get { return codepage; }
  464. }
  465. internal MainDirectiveAttribute <int> LCID {
  466. get { return lcid; }
  467. }
  468. internal MainDirectiveAttribute <string> ClientTarget {
  469. get { return clientTarget; }
  470. }
  471. internal MainDirectiveAttribute <string> MasterPageFile {
  472. get { return masterPage; }
  473. }
  474. internal MainDirectiveAttribute <string> Title {
  475. get { return title; }
  476. }
  477. internal MainDirectiveAttribute <string> Theme {
  478. get { return theme; }
  479. }
  480. #if NET_4_0
  481. internal MainDirectiveAttribute <string> MetaDescription {
  482. get { return metaDescription; }
  483. }
  484. internal MainDirectiveAttribute <string> MetaKeywords {
  485. get { return metaKeywords; }
  486. }
  487. #endif
  488. internal string Culture {
  489. get { return culture; }
  490. }
  491. internal string UICulture {
  492. get { return uiculture; }
  493. }
  494. internal string ErrorPage {
  495. get { return errorPage; }
  496. }
  497. internal bool ValidateRequest {
  498. get { return validateRequest; }
  499. }
  500. internal bool NotBuffer {
  501. get { return notBuffer; }
  502. }
  503. internal bool Async {
  504. get { return async; }
  505. }
  506. internal int AsyncTimeout {
  507. get { return asyncTimeout; }
  508. }
  509. internal string StyleSheetTheme {
  510. get { return styleSheetTheme; }
  511. }
  512. internal Type MasterType {
  513. get {
  514. if (masterType == null && !String.IsNullOrEmpty (masterVirtualPath))
  515. masterType = BuildManager.GetCompiledType (masterVirtualPath);
  516. return masterType;
  517. }
  518. }
  519. internal bool EnableEventValidation {
  520. get { return enable_event_validation; }
  521. }
  522. internal bool MaintainScrollPositionOnPostBack {
  523. get { return maintainScrollPositionOnPostBack; }
  524. }
  525. internal int MaxPageStateFieldLength {
  526. get { return maxPageStateFieldLength; }
  527. }
  528. internal Type PreviousPageType {
  529. get {
  530. if (previousPageType == null && !String.IsNullOrEmpty (previousPageVirtualPath)) {
  531. string mappedPath = MapPath (previousPageVirtualPath);
  532. previousPageType = GetCompiledPageType (previousPageVirtualPath, mappedPath, HttpContext.Current);
  533. }
  534. return previousPageType;
  535. }
  536. }
  537. }
  538. }