SimpleWebHandlerParser.cs 13 KB

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