SimpleWebHandlerParser.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. //
  2. // System.Web.UI.SimpleWebHandlerParser
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
  8. // Copyright (C) 2005 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.CodeDom.Compiler;
  30. using System.Collections;
  31. using System.IO;
  32. using System.Reflection;
  33. using System.Security.Permissions;
  34. using System.Text;
  35. using System.Web.Compilation;
  36. using System.Web.Configuration;
  37. using System.Web.Util;
  38. namespace System.Web.UI
  39. {
  40. // CAS
  41. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  42. [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  43. public abstract class SimpleWebHandlerParser
  44. {
  45. HttpContext context;
  46. string vPath;
  47. string physPath;
  48. string className;
  49. bool debug;
  50. string language;
  51. string program;
  52. bool gotDefault;
  53. ArrayList assemblies;
  54. ArrayList dependencies;
  55. Hashtable anames;
  56. string privateBinPath;
  57. string baseDir;
  58. string baseVDir;
  59. #if !NET_2_0
  60. CompilationConfiguration compilationConfig;
  61. #else
  62. TextReader reader;
  63. #endif
  64. int appAssemblyIndex = -1;
  65. Type cachedType;
  66. protected SimpleWebHandlerParser (HttpContext context, string virtualPath, string physicalPath)
  67. {
  68. cachedType = CachingCompiler.GetTypeFromCache (physicalPath);
  69. if (cachedType != null)
  70. return; // We don't need anything else.
  71. this.context = context;
  72. this.vPath = virtualPath;
  73. this.physPath = physicalPath;
  74. AddDependency (physicalPath);
  75. assemblies = new ArrayList ();
  76. string location = Context.ApplicationInstance.AssemblyLocation;
  77. if (location != typeof (TemplateParser).Assembly.Location)
  78. appAssemblyIndex = assemblies.Add (location);
  79. #if NET_2_0
  80. bool addAssembliesInBin = false;
  81. foreach (AssemblyInfo info in CompilationConfig.Assemblies) {
  82. if (info.Assembly == "*")
  83. addAssembliesInBin = true;
  84. else
  85. assemblies.Add (info.Assembly);
  86. }
  87. if (addAssembliesInBin)
  88. AddAssembliesInBin ();
  89. #else
  90. assemblies.AddRange (CompilationConfig.Assemblies);
  91. if (CompilationConfig.AssembliesInBin)
  92. AddAssembliesInBin ();
  93. #endif
  94. language = CompilationConfig.DefaultLanguage;
  95. GetDirectivesAndContent ();
  96. }
  97. #if NET_2_0
  98. internal SimpleWebHandlerParser (HttpContext context, string virtualPath, string physicalPath, TextReader reader)
  99. : this (context, virtualPath, physicalPath)
  100. {
  101. this.reader = reader;
  102. }
  103. #endif
  104. protected Type GetCompiledTypeFromCache ()
  105. {
  106. return cachedType;
  107. }
  108. void GetDirectivesAndContent ()
  109. {
  110. StreamReader reader = new StreamReader (File.OpenRead (physPath));
  111. string line;
  112. bool directiveFound = false;
  113. StringBuilder content = new StringBuilder ();
  114. while ((line = reader.ReadLine ()) != null && cachedType == null) {
  115. string trimmed = line.Trim ();
  116. if (!directiveFound && trimmed == String.Empty)
  117. continue;
  118. if (trimmed.StartsWith ("<")) {
  119. ParseDirective (trimmed);
  120. directiveFound = true;
  121. if (gotDefault) {
  122. cachedType = CachingCompiler.GetTypeFromCache (physPath);
  123. if (cachedType != null)
  124. break;
  125. }
  126. continue;
  127. }
  128. content.Append (line + "\n");
  129. content.Append (reader.ReadToEnd ());
  130. }
  131. reader.Close ();
  132. if (!gotDefault)
  133. throw new ParseException (null, "No @" + DefaultDirectiveName +
  134. " directive found");
  135. if (cachedType == null)
  136. this.program = content.ToString ();
  137. }
  138. void TagParsed (ILocation location, System.Web.Compilation.TagType tagtype, string tagid, TagAttributes attributes)
  139. {
  140. if (tagtype != System.Web.Compilation.TagType.Directive)
  141. throw new ParseException (location, "Unexpected tag");
  142. if (String.Compare (tagid, DefaultDirectiveName, true) == 0) {
  143. AddDefaultDirective (location, attributes);
  144. } else if (String.Compare (tagid, "Assembly", true) == 0) {
  145. AddAssemblyDirective (location, attributes);
  146. } else {
  147. throw new ParseException (location, "Unexpected directive: " + tagid);
  148. }
  149. }
  150. void TextParsed (ILocation location, string text)
  151. {
  152. if (text.Trim () != "")
  153. throw new ParseException (location, "Text not allowed here");
  154. }
  155. void ParseError (ILocation location, string message)
  156. {
  157. throw new ParseException (location, message);
  158. }
  159. static string GetAndRemove (Hashtable table, string key)
  160. {
  161. string o = table [key] as string;
  162. table.Remove (key);
  163. return o;
  164. }
  165. void ParseDirective (string line)
  166. {
  167. AspParser parser = new AspParser (physPath, new StringReader (line));
  168. parser.Error += new ParseErrorHandler (ParseError);
  169. parser.TagParsed += new TagParsedHandler (TagParsed);
  170. parser.TextParsed += new TextParsedHandler (TextParsed);
  171. parser.Parse ();
  172. }
  173. internal virtual void AddDefaultDirective (ILocation location, TagAttributes attrs)
  174. {
  175. if (gotDefault)
  176. throw new ParseException (location, "duplicate " + DefaultDirectiveName + " directive");
  177. gotDefault = true;
  178. Hashtable attributes = attrs.GetDictionary (null);
  179. className = GetAndRemove (attributes, "class");
  180. if (className == null)
  181. throw new ParseException (null, "No Class attribute found.");
  182. string d = GetAndRemove (attributes, "debug");
  183. if (d != null) {
  184. debug = (String.Compare (d, "true", true) == 0);
  185. if (debug == false && String.Compare (d, "false", true) != 0)
  186. throw new ParseException (null, "Invalid value for Debug attribute");
  187. }
  188. language = GetAndRemove (attributes, "language");
  189. if (language == null)
  190. language = CompilationConfig.DefaultLanguage;
  191. GetAndRemove (attributes, "codebehind");
  192. if (attributes.Count > 0)
  193. throw new ParseException (location, "Unrecognized attribute in " +
  194. DefaultDirectiveName + " directive");
  195. }
  196. internal virtual void AddAssemblyDirective (ILocation location, TagAttributes attrs)
  197. {
  198. Hashtable tbl = attrs.GetDictionary (null);
  199. string name = GetAndRemove (tbl, "Name");
  200. string src = GetAndRemove (tbl, "Src");
  201. if (name == null && src == null)
  202. throw new ParseException (location, "You gotta specify Src or Name");
  203. if (name != null && src != null)
  204. throw new ParseException (location, "Src and Name cannot be used together");
  205. if (name != null) {
  206. AddAssemblyByName (name, location);
  207. } else {
  208. GetAssemblyFromSource (src, location);
  209. }
  210. if (tbl.Count > 0)
  211. throw new ParseException (location, "Unrecognized attribute in Assembly directive");
  212. }
  213. internal virtual void AddAssembly (Assembly assembly, bool fullPath)
  214. {
  215. if (anames == null)
  216. anames = new Hashtable ();
  217. string name = assembly.GetName ().Name;
  218. string loc = assembly.Location;
  219. if (fullPath) {
  220. if (!assemblies.Contains (loc)) {
  221. assemblies.Add (loc);
  222. }
  223. anames [name] = loc;
  224. anames [loc] = assembly;
  225. } else {
  226. if (!assemblies.Contains (name)) {
  227. assemblies.Add (name);
  228. }
  229. anames [name] = assembly;
  230. }
  231. }
  232. internal virtual Assembly AddAssemblyByName (string name, ILocation location)
  233. {
  234. if (anames == null)
  235. anames = new Hashtable ();
  236. if (anames.Contains (name)) {
  237. object o = anames [name];
  238. if (o is string)
  239. o = anames [o];
  240. return (Assembly) o;
  241. }
  242. Assembly assembly = LoadAssemblyFromBin (name);
  243. if (assembly != null) {
  244. AddAssembly (assembly, true);
  245. return assembly;
  246. }
  247. try {
  248. assembly = Assembly.LoadWithPartialName (name);
  249. } catch (Exception e) {
  250. throw new ParseException (location, "Assembly " + name + " not found", e);
  251. }
  252. AddAssembly (assembly, true);
  253. return assembly;
  254. }
  255. void AddAssembliesInBin ()
  256. {
  257. if (!Directory.Exists (PrivateBinPath))
  258. return;
  259. string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
  260. foreach (string dll in binDlls) {
  261. try {
  262. Assembly assembly = Assembly.LoadFrom (dll);
  263. AddAssembly (assembly, true);
  264. } catch (Exception e) {
  265. throw new Exception ("Error while loading " + dll, e);
  266. }
  267. }
  268. }
  269. Assembly LoadAssemblyFromBin (string name)
  270. {
  271. Assembly assembly;
  272. if (!Directory.Exists (PrivateBinPath))
  273. return null;
  274. string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
  275. foreach (string dll in binDlls) {
  276. string fn = Path.GetFileName (dll);
  277. fn = Path.ChangeExtension (fn, null);
  278. if (fn != name)
  279. continue;
  280. assembly = Assembly.LoadFrom (dll);
  281. return assembly;
  282. }
  283. return null;
  284. }
  285. Assembly GetAssemblyFromSource (string vpath, ILocation location)
  286. {
  287. vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
  288. string realPath = context.Request.MapPath (vpath);
  289. if (!File.Exists (realPath))
  290. throw new ParseException (location, "File " + vpath + " not found");
  291. AddDependency (realPath);
  292. CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
  293. if (result.NativeCompilerReturnValue != 0) {
  294. StreamReader reader = new StreamReader (realPath);
  295. throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
  296. }
  297. AddAssembly (result.CompiledAssembly, true);
  298. return result.CompiledAssembly;
  299. }
  300. internal Type GetTypeFromBin (string typeName)
  301. {
  302. if (!Directory.Exists (PrivateBinPath))
  303. throw new HttpException (String.Format ("Type {0} not found.", typeName));
  304. string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
  305. Type result = null;
  306. foreach (string dll in binDlls) {
  307. Assembly assembly = Assembly.LoadFrom (dll);
  308. Type type = assembly.GetType (typeName, false);
  309. if (type != null) {
  310. if (result != null)
  311. throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
  312. result = type;
  313. }
  314. }
  315. if (result == null)
  316. throw new HttpException (String.Format ("Type {0} not found.", typeName));
  317. return result;
  318. }
  319. internal virtual void AddDependency (string filename)
  320. {
  321. if (dependencies == null)
  322. dependencies = new ArrayList ();
  323. if (!dependencies.Contains (filename))
  324. dependencies.Add (filename);
  325. }
  326. // Properties
  327. protected abstract string DefaultDirectiveName { get; }
  328. internal HttpContext Context {
  329. get { return context; }
  330. }
  331. internal string VirtualPath {
  332. get { return vPath; }
  333. }
  334. internal string PhysicalPath {
  335. get { return physPath; }
  336. }
  337. internal string ClassName {
  338. get { return className; }
  339. }
  340. internal bool Debug {
  341. get { return debug; }
  342. }
  343. internal string Language {
  344. get { return language; }
  345. }
  346. internal string Program {
  347. get { return program; }
  348. }
  349. internal ArrayList Assemblies {
  350. get {
  351. if (appAssemblyIndex != -1) {
  352. object o = assemblies [appAssemblyIndex];
  353. assemblies.RemoveAt (appAssemblyIndex);
  354. assemblies.Add (o);
  355. appAssemblyIndex = -1;
  356. }
  357. return assemblies;
  358. }
  359. }
  360. internal ArrayList Dependencies {
  361. get { return dependencies; }
  362. }
  363. internal string PrivateBinPath {
  364. get {
  365. if (privateBinPath != null)
  366. return privateBinPath;
  367. AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
  368. privateBinPath = setup.PrivateBinPath;
  369. if (!Path.IsPathRooted (privateBinPath)) {
  370. string appbase = setup.ApplicationBase;
  371. if (appbase.StartsWith ("file://")) {
  372. appbase = appbase.Substring (7);
  373. if (Path.DirectorySeparatorChar != '/')
  374. appbase = appbase.Replace ('/', Path.DirectorySeparatorChar);
  375. }
  376. privateBinPath = Path.Combine (appbase, privateBinPath);
  377. }
  378. return privateBinPath;
  379. }
  380. }
  381. internal string BaseDir {
  382. get {
  383. if (baseDir == null)
  384. baseDir = context.Request.MapPath (BaseVirtualDir);
  385. return baseDir;
  386. }
  387. }
  388. internal virtual string BaseVirtualDir {
  389. get {
  390. if (baseVDir == null)
  391. baseVDir = UrlUtils.GetDirectory (context.Request.FilePath);
  392. return baseVDir;
  393. }
  394. }
  395. #if NET_2_0
  396. CompilationSection CompilationConfig {
  397. get {
  398. return (CompilationSection)WebConfigurationManager.GetSection ("system.web/compilation");
  399. }
  400. }
  401. internal TextReader Reader {
  402. get { return reader; }
  403. set { reader = value; }
  404. }
  405. #else
  406. internal CompilationConfiguration CompilationConfig {
  407. get {
  408. if (compilationConfig == null)
  409. compilationConfig = CompilationConfiguration.GetInstance (context);
  410. return compilationConfig;
  411. }
  412. }
  413. #endif
  414. }
  415. }