PageParser.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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 = true;
  47. bool smartNavigation;
  48. bool haveTrace;
  49. bool trace;
  50. bool notBuffer;
  51. TraceMode tracemode = TraceMode.Default;
  52. string responseEncoding;
  53. string contentType;
  54. int codepage = -1;
  55. int lcid = -1;
  56. string culture;
  57. string uiculture;
  58. string errorPage;
  59. bool validateRequest;
  60. string clientTarget;
  61. bool async;
  62. int asyncTimeout = -1;
  63. string masterPage;
  64. Type masterType;
  65. string masterVirtualPath;
  66. string title;
  67. string theme;
  68. string styleSheetTheme;
  69. bool enable_event_validation;
  70. bool maintainScrollPositionOnPostBack;
  71. int maxPageStateFieldLength = -1;
  72. Type previousPageType;
  73. string previousPageVirtualPath;
  74. public PageParser ()
  75. {
  76. LoadConfigDefaults ();
  77. }
  78. internal PageParser (string virtualPath, string inputFile, HttpContext context)
  79. {
  80. this.VirtualPath = new VirtualPath (virtualPath);
  81. Context = context;
  82. BaseVirtualDir = VirtualPathUtility.GetDirectory (virtualPath, false);
  83. InputFile = inputFile;
  84. SetBaseType (null);
  85. AddApplicationAssembly ();
  86. LoadConfigDefaults ();
  87. }
  88. internal PageParser (VirtualPath virtualPath, TextReader reader, HttpContext context)
  89. : this (virtualPath, null, reader, context)
  90. {
  91. }
  92. internal PageParser (VirtualPath virtualPath, string inputFile, TextReader reader, HttpContext context)
  93. {
  94. this.VirtualPath = virtualPath;
  95. Context = context;
  96. BaseVirtualDir = virtualPath.DirectoryNoNormalize;
  97. Reader = reader;
  98. if (String.IsNullOrEmpty (inputFile))
  99. InputFile = virtualPath.PhysicalPath;
  100. else
  101. InputFile = inputFile;
  102. SetBaseType (null);
  103. AddApplicationAssembly ();
  104. LoadConfigDefaults ();
  105. }
  106. internal override void LoadConfigDefaults ()
  107. {
  108. base.LoadConfigDefaults ();
  109. PagesSection ps = PagesConfig;
  110. notBuffer = !ps.Buffer;
  111. enableSessionState = ps.EnableSessionState;
  112. enableViewStateMac = ps.EnableViewStateMac;
  113. smartNavigation = ps.SmartNavigation;
  114. validateRequest = ps.ValidateRequest;
  115. masterPage = ps.MasterPageFile;
  116. if (masterPage.Length == 0)
  117. masterPage = null;
  118. enable_event_validation = ps.EnableEventValidation;
  119. maxPageStateFieldLength = ps.MaxPageStateFieldLength;
  120. theme = ps.Theme;
  121. if (theme.Length == 0)
  122. theme = null;
  123. styleSheetTheme = ps.StyleSheetTheme;
  124. if (styleSheetTheme.Length == 0)
  125. styleSheetTheme = null;
  126. maintainScrollPositionOnPostBack = ps.MaintainScrollPositionOnPostBack;
  127. }
  128. public static IHttpHandler GetCompiledPageInstance (string virtualPath, string inputFile, HttpContext context)
  129. {
  130. bool isFake = false;
  131. if (!String.IsNullOrEmpty (inputFile))
  132. isFake = !inputFile.StartsWith (HttpRuntime.AppDomainAppPath);
  133. return BuildManager.CreateInstanceFromVirtualPath (new VirtualPath (virtualPath, inputFile, isFake), typeof (IHttpHandler)) as IHttpHandler;
  134. }
  135. internal override void ProcessMainAttributes (Hashtable atts)
  136. {
  137. // note: the 'enableSessionState' configuration property is
  138. // processed in a case-sensitive manner while the page-level
  139. // attribute is processed case-insensitive
  140. string enabless = GetString (atts, "EnableSessionState", null);
  141. if (enabless != null) {
  142. if (String.Compare (enabless, "readonly", true, Helpers.InvariantCulture) == 0)
  143. enableSessionState = PagesEnableSessionState.ReadOnly;
  144. else if (String.Compare (enabless, "true", true, Helpers.InvariantCulture) == 0)
  145. enableSessionState = PagesEnableSessionState.True;
  146. else if (String.Compare (enabless, "false", true, Helpers.InvariantCulture) == 0)
  147. enableSessionState = PagesEnableSessionState.False;
  148. else
  149. ThrowParseException ("Invalid value for enableSessionState: " + enabless);
  150. }
  151. string cp = GetString (atts, "CodePage", null);
  152. if (cp != null) {
  153. if (responseEncoding != null)
  154. ThrowParseException ("CodePage and ResponseEncoding are " +
  155. "mutually exclusive.");
  156. int codepage = 0;
  157. try {
  158. codepage = (int) UInt32.Parse (cp);
  159. } catch {
  160. ThrowParseException ("Invalid value for CodePage: " + cp);
  161. }
  162. try {
  163. Encoding.GetEncoding (codepage);
  164. } catch {
  165. ThrowParseException ("Unsupported codepage: " + cp);
  166. }
  167. }
  168. responseEncoding = GetString (atts, "ResponseEncoding", null);
  169. if (responseEncoding != null) {
  170. if (codepage != -1)
  171. ThrowParseException ("CodePage and ResponseEncoding are " +
  172. "mutually exclusive.");
  173. try {
  174. Encoding.GetEncoding (responseEncoding);
  175. } catch {
  176. ThrowParseException ("Unsupported encoding: " + responseEncoding);
  177. }
  178. }
  179. contentType = GetString (atts, "ContentType", null);
  180. string lcidStr = GetString (atts, "LCID", null);
  181. if (lcidStr != null) {
  182. try {
  183. lcid = (int) UInt32.Parse (lcidStr);
  184. } catch {
  185. ThrowParseException ("Invalid value for LCID: " + lcid);
  186. }
  187. CultureInfo ci = null;
  188. try {
  189. ci = new CultureInfo (lcid);
  190. } catch {
  191. ThrowParseException ("Unsupported LCID: " + lcid);
  192. }
  193. if (ci.IsNeutralCulture) {
  194. string suggestedCulture = SuggestCulture (ci.Name);
  195. string fmt = "LCID attribute must be set to a non-neutral Culture.";
  196. if (suggestedCulture != null) {
  197. ThrowParseException (fmt + " Please try one of these: " +
  198. suggestedCulture);
  199. } else {
  200. ThrowParseException (fmt);
  201. }
  202. }
  203. }
  204. culture = GetString (atts, "Culture", null);
  205. if (culture != null) {
  206. if (lcidStr != null)
  207. ThrowParseException ("Culture and LCID are mutually exclusive.");
  208. CultureInfo ci = null;
  209. try {
  210. if (!culture.StartsWith ("auto"))
  211. ci = new CultureInfo (culture);
  212. } catch {
  213. ThrowParseException ("Unsupported Culture: " + culture);
  214. }
  215. if (ci != null && ci.IsNeutralCulture) {
  216. string suggestedCulture = SuggestCulture (culture);
  217. string fmt = "Culture attribute must be set to a non-neutral Culture.";
  218. if (suggestedCulture != null)
  219. ThrowParseException (fmt +
  220. " Please try one of these: " + suggestedCulture);
  221. else
  222. ThrowParseException (fmt);
  223. }
  224. }
  225. uiculture = GetString (atts, "UICulture", null);
  226. if (uiculture != null) {
  227. CultureInfo ci = null;
  228. try {
  229. if (!uiculture.StartsWith ("auto"))
  230. ci = new CultureInfo (uiculture);
  231. } catch {
  232. ThrowParseException ("Unsupported Culture: " + uiculture);
  233. }
  234. if (ci != null && ci.IsNeutralCulture) {
  235. string suggestedCulture = SuggestCulture (uiculture);
  236. string fmt = "UICulture attribute must be set to a non-neutral Culture.";
  237. if (suggestedCulture != null)
  238. ThrowParseException (fmt +
  239. " Please try one of these: " + suggestedCulture);
  240. else
  241. ThrowParseException (fmt);
  242. }
  243. }
  244. string tracestr = GetString (atts, "Trace", null);
  245. if (tracestr != null) {
  246. haveTrace = true;
  247. atts ["Trace"] = tracestr;
  248. trace = GetBool (atts, "Trace", false);
  249. }
  250. string tracemodes = GetString (atts, "TraceMode", null);
  251. if (tracemodes != null) {
  252. bool valid = true;
  253. try {
  254. tracemode = (TraceMode) Enum.Parse (typeof (TraceMode), tracemodes, false);
  255. } catch {
  256. valid = false;
  257. }
  258. if (!valid || tracemode == TraceMode.Default)
  259. ThrowParseException ("The 'tracemode' attribute is case sensitive and must be " +
  260. "one of the following values: SortByTime, SortByCategory.");
  261. }
  262. errorPage = GetString (atts, "ErrorPage", null);
  263. validateRequest = GetBool (atts, "ValidateRequest", validateRequest);
  264. clientTarget = GetString (atts, "ClientTarget", null);
  265. if (clientTarget != null) {
  266. clientTarget = clientTarget.Trim ();
  267. ClientTargetSection sec = GetConfigSection <ClientTargetSection> ("system.web/clientTarget");
  268. ClientTarget ct = null;
  269. if ((ct = sec.ClientTargets [clientTarget]) == null)
  270. clientTarget = clientTarget.ToLowerInvariant ();
  271. if (ct == null && (ct = sec.ClientTargets [clientTarget]) == null) {
  272. ThrowParseException (String.Format (
  273. "ClientTarget '{0}' is an invalid alias. See the " +
  274. "documentation for <clientTarget> config. section.",
  275. clientTarget));
  276. }
  277. clientTarget = ct.UserAgent;
  278. }
  279. notBuffer = !GetBool (atts, "Buffer", true);
  280. async = GetBool (atts, "Async", false);
  281. string asyncTimeoutVal = GetString (atts, "AsyncTimeout", null);
  282. if (asyncTimeoutVal != null) {
  283. try {
  284. asyncTimeout = Int32.Parse (asyncTimeoutVal);
  285. } catch (Exception) {
  286. ThrowParseException ("AsyncTimeout must be an integer value");
  287. }
  288. }
  289. masterPage = GetString (atts, "MasterPageFile", masterPage);
  290. if (!String.IsNullOrEmpty (masterPage)) {
  291. if (!HostingEnvironment.VirtualPathProvider.FileExists (masterPage))
  292. ThrowParseFileNotFound (masterPage);
  293. AddDependency (masterPage);
  294. }
  295. title = GetString(atts, "Title", null);
  296. theme = GetString (atts, "Theme", theme);
  297. styleSheetTheme = GetString (atts, "StyleSheetTheme", styleSheetTheme);
  298. enable_event_validation = GetBool (atts, "EnableEventValidation", enable_event_validation);
  299. maintainScrollPositionOnPostBack = GetBool (atts, "MaintainScrollPositionOnPostBack", maintainScrollPositionOnPostBack);
  300. enableViewStateMac = GetBool (atts, "EnableViewStateMac", enableViewStateMac);
  301. smartNavigation = GetBool (atts, "SmartNavigation", smartNavigation);
  302. base.ProcessMainAttributes (atts);
  303. }
  304. internal override void AddDirective (string directive, Hashtable atts)
  305. {
  306. bool isMasterType = String.Compare ("MasterType", directive, StringComparison.OrdinalIgnoreCase) == 0;
  307. bool isPreviousPageType = isMasterType ? false : String.Compare ("PreviousPageType", directive,
  308. StringComparison.OrdinalIgnoreCase) == 0;
  309. string typeName = null;
  310. string virtualPath = null;
  311. Type type = null;
  312. if (isMasterType || isPreviousPageType) {
  313. PageParserFilter pfilter = PageParserFilter;
  314. if (pfilter != null)
  315. pfilter.PreprocessDirective (directive.ToLowerInvariant (), atts);
  316. typeName = GetString (atts, "TypeName", null);
  317. virtualPath = GetString (atts, "VirtualPath", null);
  318. if (typeName != null && virtualPath != null)
  319. ThrowParseException (
  320. String.Format ("The '{0}' directive must have exactly one attribute: TypeName or VirtualPath", directive));
  321. if (typeName != null) {
  322. type = LoadType (typeName);
  323. if (type == null)
  324. ThrowParseException (String.Format ("Could not load type '{0}'.", typeName));
  325. if (isMasterType)
  326. masterType = type;
  327. else
  328. previousPageType = type;
  329. } else if (!String.IsNullOrEmpty (virtualPath)) {
  330. if (!HostingEnvironment.VirtualPathProvider.FileExists (virtualPath))
  331. ThrowParseFileNotFound (virtualPath);
  332. AddDependency (virtualPath);
  333. if (isMasterType)
  334. masterVirtualPath = virtualPath;
  335. else
  336. previousPageVirtualPath = virtualPath;
  337. } else
  338. ThrowParseException (String.Format ("The {0} directive must have either a TypeName or a VirtualPath attribute.", directive));
  339. if (type != null)
  340. AddAssembly (type.Assembly, true);
  341. } else
  342. base.AddDirective (directive, atts);
  343. }
  344. static string SuggestCulture (string culture)
  345. {
  346. string retval = null;
  347. foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.SpecificCultures)) {
  348. if (ci.Name.StartsWith (culture))
  349. retval += ci.Name + " ";
  350. }
  351. return retval;
  352. }
  353. public static Type GetCompiledPageType (string virtualPath, string inputFile, HttpContext context)
  354. {
  355. return BuildManager.GetCompiledType (virtualPath);
  356. }
  357. protected override Type CompileIntoType ()
  358. {
  359. AspGenerator generator = new AspGenerator (this);
  360. return generator.GetCompiledType ();
  361. }
  362. internal bool EnableSessionState {
  363. get {
  364. return enableSessionState == PagesEnableSessionState.True ||
  365. ReadOnlySessionState;
  366. }
  367. }
  368. internal bool EnableViewStateMac {
  369. get { return enableViewStateMac; }
  370. }
  371. internal bool SmartNavigation {
  372. get { return smartNavigation; }
  373. }
  374. internal bool ReadOnlySessionState {
  375. get {
  376. return enableSessionState == PagesEnableSessionState.ReadOnly;
  377. }
  378. }
  379. internal bool HaveTrace {
  380. get { return haveTrace; }
  381. }
  382. internal bool Trace {
  383. get { return trace; }
  384. }
  385. internal TraceMode TraceMode {
  386. get { return tracemode; }
  387. }
  388. internal override string DefaultBaseTypeName {
  389. get { return PagesConfig.PageBaseType; }
  390. }
  391. internal override string DefaultDirectiveName {
  392. get { return "page"; }
  393. }
  394. internal string ResponseEncoding {
  395. get { return responseEncoding; }
  396. }
  397. internal string ContentType {
  398. get { return contentType; }
  399. }
  400. internal int CodePage {
  401. get { return codepage; }
  402. }
  403. internal string Culture {
  404. get { return culture; }
  405. }
  406. internal string UICulture {
  407. get { return uiculture; }
  408. }
  409. internal int LCID {
  410. get { return lcid; }
  411. }
  412. internal string ErrorPage {
  413. get { return errorPage; }
  414. }
  415. internal bool ValidateRequest {
  416. get { return validateRequest; }
  417. }
  418. internal string ClientTarget {
  419. get { return clientTarget; }
  420. }
  421. internal bool NotBuffer {
  422. get { return notBuffer; }
  423. }
  424. internal bool Async {
  425. get { return async; }
  426. }
  427. internal int AsyncTimeout {
  428. get { return asyncTimeout; }
  429. }
  430. internal string Theme {
  431. get { return theme; }
  432. }
  433. internal string StyleSheetTheme {
  434. get { return styleSheetTheme; }
  435. }
  436. internal string MasterPageFile {
  437. get { return masterPage; }
  438. }
  439. internal Type MasterType {
  440. get {
  441. if (masterType == null && !String.IsNullOrEmpty (masterVirtualPath))
  442. masterType = BuildManager.GetCompiledType (masterVirtualPath);
  443. return masterType;
  444. }
  445. }
  446. internal string Title {
  447. get { return title; }
  448. }
  449. internal bool EnableEventValidation {
  450. get { return enable_event_validation; }
  451. }
  452. internal bool MaintainScrollPositionOnPostBack {
  453. get { return maintainScrollPositionOnPostBack; }
  454. }
  455. internal int MaxPageStateFieldLength {
  456. get { return maxPageStateFieldLength; }
  457. }
  458. internal Type PreviousPageType {
  459. get {
  460. if (previousPageType == null && !String.IsNullOrEmpty (previousPageVirtualPath)) {
  461. string mappedPath = MapPath (previousPageVirtualPath);
  462. previousPageType = GetCompiledPageType (previousPageVirtualPath, mappedPath, HttpContext.Current);
  463. }
  464. return previousPageType;
  465. }
  466. }
  467. }
  468. }