PageMapper.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. //
  2. // (C) 2005 Mainsoft Corporation (http://www.mainsoft.com)
  3. //
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining
  6. // a copy of this software and associated documentation files (the
  7. // "Software"), to deal in the Software without restriction, including
  8. // without limitation the rights to use, copy, modify, merge, publish,
  9. // distribute, sublicense, and/or sell copies of the Software, and to
  10. // permit persons to whom the Software is furnished to do so, subject to
  11. // the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  20. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  21. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  22. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. //
  24. using System;
  25. using System.Xml;
  26. using System.IO;
  27. using System.Collections;
  28. using System.Web.Compilation;
  29. using System.Collections.Specialized;
  30. using System.Threading;
  31. using vmw.common;
  32. using System.Reflection;
  33. namespace System.Web.J2EE
  34. {
  35. /// <summary>
  36. /// Class that allows reading assemblies.xml file for getting information about different types.
  37. /// </summary>
  38. public class PageMapper
  39. {
  40. //private static readonly string _fileListName = "/filelist.xml";
  41. private static readonly object LOCK_GETASSEMBLIESCACHEDDOCUMENT = new object();
  42. //private static readonly object LOCK_GETFROMMAPPATHCACHE = new object();
  43. static Assembly CurrentDomain_AssemblyResolve (object sender, ResolveEventArgs args)
  44. {
  45. Assembly resolvedAssembly = null;
  46. try
  47. {
  48. resolvedAssembly = GetCachedAssembly (HttpContext.Current, String.Concat (HttpContext.Current.Request.ApplicationPath, "/", args.Name));
  49. }
  50. catch (Exception ex)
  51. {
  52. #if DEBUG
  53. Console.WriteLine (ex.ToString ());
  54. #endif
  55. resolvedAssembly = null;
  56. }
  57. return resolvedAssembly;
  58. }
  59. #if UNUSED
  60. public static string GetFromMapPathCache(string key)
  61. {
  62. Hashtable answer = null;
  63. lock(LOCK_GETFROMMAPPATHCACHE)
  64. {
  65. answer = (Hashtable) AppDomain.CurrentDomain.GetData(J2EEConsts.MAP_PATH_CACHE);
  66. if (answer == null)
  67. {
  68. answer = new Hashtable();
  69. CachedDocumentTypeStorage storage = (CachedDocumentTypeStorage)GetAssembliesCachedDocument();
  70. IDictionaryEnumerator e = storage.GetEnumerator();
  71. e.Reset();
  72. while (e.MoveNext())
  73. {
  74. string currentFile = (string)((DictionaryEntry)e.Current).Key;
  75. answer[currentFile]= IAppDomainConfig.WAR_ROOT_SYMBOL + currentFile;
  76. }
  77. AppDomain.CurrentDomain.SetData(J2EEConsts.MAP_PATH_CACHE,answer);
  78. }
  79. }
  80. return (string)answer[key];
  81. }
  82. // UNUSED METHOD
  83. //The method was used by runtime to force file names casesensitivity
  84. // problem. The filelist.xml file should contain correct file names,
  85. // but currently it is unused
  86. public static void LoadFileList()
  87. {
  88. Hashtable hashTable = (Hashtable) AppDomain.CurrentDomain.GetData(J2EEConsts.FILE_LIST_FILE);
  89. if (hashTable == null)
  90. {
  91. XmlDocument doc;
  92. try
  93. {
  94. Stream fs = (Stream)IOUtils.getStream(_fileListName);
  95. if (fs == null)
  96. {
  97. AppDomain.CurrentDomain.SetData(J2EEConsts.FILE_LIST_FILE, new Hashtable());
  98. return;
  99. }
  100. doc = new XmlDocument();
  101. doc.Load(fs);
  102. }
  103. catch (Exception)
  104. {
  105. // Console.WriteLine("filelist.xml was not found!!!");
  106. AppDomain.CurrentDomain.SetData(J2EEConsts.FILE_LIST_FILE, new Hashtable());
  107. return;
  108. }
  109. // Console.WriteLine("filelist.xml was found!!!");
  110. if (doc != null && doc.DocumentElement.HasChildNodes)
  111. {
  112. hashTable = CollectionsUtil.CreateCaseInsensitiveHashtable();
  113. XmlNodeList nodeList = doc.DocumentElement.ChildNodes;
  114. for (int i = 0;i < nodeList.Count ; i++)
  115. {
  116. string fileName = nodeList.Item(i).InnerText;
  117. hashTable.Add(fileName,fileName);
  118. }
  119. AppDomain.CurrentDomain.SetData(J2EEConsts.FILE_LIST_FILE, hashTable);
  120. }
  121. }
  122. }
  123. #endif
  124. private static ICachedXmlDoc GetAssembliesCachedDocument(HttpContext context)
  125. {
  126. ICachedXmlDoc doc = (ICachedXmlDoc) AppDomain.CurrentDomain.GetData (J2EEConsts.ASSEMBLIES_FILE);
  127. if (doc == null) {
  128. lock (LOCK_GETASSEMBLIESCACHEDDOCUMENT) {
  129. doc = (ICachedXmlDoc) AppDomain.CurrentDomain.GetData (J2EEConsts.ASSEMBLIES_FILE);
  130. if (doc == null) {
  131. doc = CreateDocument ();
  132. if (doc != null) {
  133. AppDomain.CurrentDomain.SetData (J2EEConsts.ASSEMBLIES_FILE, doc);
  134. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler (CurrentDomain_AssemblyResolve);
  135. try {
  136. //Try to load the global resources
  137. HttpContext.AppGlobalResourcesAssembly = GetCachedAssembly (context, context.Request.ApplicationPath + "/app_globalresources");
  138. }
  139. catch (Exception ex) {
  140. #if DEBUG
  141. Console.WriteLine (ex.ToString ());
  142. #endif
  143. }
  144. }
  145. }
  146. }
  147. }
  148. return doc;
  149. }
  150. private static String NormalizeName(string url)
  151. {
  152. #if NET_2_0
  153. url = System.Web.Util.UrlUtils.RemoveDoubleSlashes(url);
  154. #endif
  155. if (url.StartsWith(IAppDomainConfig.WAR_ROOT_SYMBOL))
  156. url = url.Substring(IAppDomainConfig.WAR_ROOT_SYMBOL.Length);
  157. return url;
  158. }
  159. private static ICachedXmlDoc CreateDocument()
  160. {
  161. return new CachedDocumentTypeStorage();
  162. }
  163. public static Type GetObjectType (HttpContext context, string url)
  164. {
  165. return GetCachedType(context, NormalizeName(url), true);
  166. }
  167. public static Type GetObjectType (HttpContext context, string url, bool throwException) {
  168. return GetCachedType (context, NormalizeName (url), throwException);
  169. }
  170. public static Assembly GetObjectAssembly (HttpContext context, string url)
  171. {
  172. return GetCachedAssembly (context, NormalizeName (url));
  173. }
  174. public static string GetAssemblyResource (HttpContext context, string url)
  175. {
  176. return GetCachedResource (context, NormalizeName (url));
  177. }
  178. private static string GetCachedResource (HttpContext context, string url)
  179. {
  180. ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument(context);
  181. return doc.GetAssemblyResourceName (context, url);
  182. }
  183. private static Assembly GetCachedAssembly (HttpContext context, string url)
  184. {
  185. ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument(context);
  186. return doc.GetAssembly (context, url);
  187. }
  188. private static Type GetCachedType (HttpContext context, string url) {
  189. return GetCachedType (context, url, true);
  190. }
  191. private static Type GetCachedType (HttpContext context, string url, bool throwException)
  192. {
  193. ICachedXmlDoc doc = PageMapper.GetAssembliesCachedDocument(context);
  194. Type t = doc.GetType(context, url);
  195. if (t == null && throwException)
  196. throw new HttpException(404,"The requested resource (" + url + ") is not available.");
  197. return t;
  198. }
  199. #region ICachedXmlDoc interface
  200. interface ICachedXmlDoc
  201. {
  202. Type GetType (HttpContext context, string key);
  203. Assembly GetAssembly (HttpContext context, string key);
  204. string GetAssemblyResourceName (HttpContext context, string key);
  205. }
  206. #endregion
  207. #region CachedDocumentTypeStorage class
  208. class CachedDocumentTypeStorage : ICachedXmlDoc
  209. {
  210. private static readonly object _fuse = new object();
  211. public static readonly ICachedXmlDoc DEFAULT_DOC =
  212. new CachedDocumentTypeStorage(0);
  213. private static readonly int DEFAULT_PAGES_NUMBER = 25;
  214. private Hashtable _table;
  215. private CachedDocumentTypeStorage(int initTableSize)
  216. {
  217. _table = Hashtable.Synchronized(new Hashtable(initTableSize));
  218. }
  219. public CachedDocumentTypeStorage() :
  220. this(DEFAULT_PAGES_NUMBER)
  221. {}
  222. string ICachedXmlDoc.GetAssemblyResourceName (HttpContext context, string o)
  223. {
  224. MetaProvider p = GetMetaByURL (context, o);
  225. if (p == null)
  226. return null;
  227. return p.Resource;
  228. }
  229. Type ICachedXmlDoc.GetType (HttpContext context, string o)
  230. {
  231. MetaProvider p = GetMetaByURL (context, o);
  232. if (p == null)
  233. return null;
  234. return p.Type;
  235. }
  236. Assembly ICachedXmlDoc.GetAssembly (HttpContext context, string o)
  237. {
  238. MetaProvider p = GetMetaByURL (context, o);
  239. if (p == null)
  240. return null;
  241. return p.Assembly;
  242. }
  243. internal IDictionaryEnumerator GetEnumerator()
  244. {
  245. return _table.GetEnumerator();
  246. }
  247. //rewamped for perfomance reasons
  248. //It looks like issue is not important in development mode,
  249. //but only will became important in production mode when dynamyc compilation will be enabled
  250. //Anyway, locking whole table and compiling under lock looks odd
  251. //spivak.December 07 2006
  252. //
  253. //prevent DOS attack. dont cache MetaProvider for not valid resource
  254. //igorz. May 16 2007
  255. public MetaProvider GetMetaByURL(HttpContext context, string url)
  256. {
  257. string lwUrl = url.ToLowerInvariant ();
  258. MetaProvider retVal = (MetaProvider) _table [lwUrl];
  259. if (retVal == null) {
  260. retVal = PageCompiler.GetCompiler (context, url);
  261. if (retVal.Type == null && retVal.Assembly == null)
  262. return null;
  263. _table [lwUrl] = retVal;
  264. }
  265. return retVal;
  266. }
  267. }
  268. #endregion
  269. }
  270. public interface MetaProvider
  271. {
  272. Type Type { get;}
  273. Assembly Assembly {get;}
  274. string Resource { get;}
  275. }
  276. public class PageCompiler : MetaProvider
  277. {
  278. private static readonly string PAGE_XPATH = "preserve";
  279. private static readonly string ASSEM_ATTRIB_NAME = "assem";
  280. private static readonly string TYPE_ATTRIB_NAME = "type";
  281. private static string _parser = null;
  282. private Type _type = null;
  283. private string _typeName = null;
  284. private Assembly _assembly = null;
  285. private string _origAssemblyName = null;
  286. private string _xmlDescriptor = null;
  287. private string _url = null;
  288. private string _session = null;
  289. readonly private HttpContext _context;
  290. PageCompiler(HttpContext context, string url)
  291. {
  292. _url = url;
  293. _context = context;
  294. _xmlDescriptor = GetDescFromUrl();
  295. _session = DateTime.Now.Ticks.ToString();
  296. LoadTypeAndAssem();
  297. }
  298. public static PageCompiler GetCompiler(HttpContext context, string url)
  299. {
  300. return new PageCompiler(context, url);
  301. }
  302. Type MetaProvider.Type
  303. {
  304. get{
  305. return _type;
  306. }
  307. }
  308. Assembly MetaProvider.Assembly
  309. {
  310. get{
  311. return _assembly;
  312. }
  313. }
  314. string MetaProvider.Resource
  315. {
  316. get
  317. {
  318. return _origAssemblyName != null ? _origAssemblyName + ".ghres" : "dll.ghres";
  319. }
  320. }
  321. private void LoadTypeAndAssem()
  322. {
  323. if (_assembly == null)
  324. {
  325. string typeName = GetCachedTypeName();
  326. #if DEBUG
  327. Console.WriteLine ("Loading type:" + typeName);
  328. #endif
  329. if (typeName != null)
  330. {
  331. if ((_type = Type.GetType (typeName)) != null)
  332. _assembly = _type.Assembly;
  333. else {
  334. if (_origAssemblyName == null)
  335. throw new TypeLoadException ("Cannot load type '" + typeName + "'");
  336. _assembly = Assembly.Load (_origAssemblyName);
  337. }
  338. }
  339. #if DEBUG
  340. Console.WriteLine ("Loaded type:" + _type);
  341. Console.WriteLine ("Loaded assembly:" + _assembly);
  342. #endif
  343. }
  344. }
  345. private bool InternalCompile()
  346. {
  347. string fileName = VirtualPathUtility.GetFileName (_url);
  348. string fullFileName = (fileName.ToLower () == "global.asax") ? _url : _context.Request.MapPath (_url);
  349. #if DEBUG
  350. Console.WriteLine("fullFileName=" + fullFileName);
  351. #endif
  352. //type not found - run aspxparser
  353. if (false/*File.Exists(fullFileName) || Directory.Exists(fullFileName)*/) //dynamic compilation currently is not supported
  354. {
  355. string[] command = GetParserCmd(fileName.ToLower() == "global.asax");
  356. if (J2EEUtils.RunProc(command) != 0)
  357. throw GetCompilerError();
  358. return true;
  359. }
  360. else
  361. {
  362. return false;
  363. //string message = "The requested resource (" + _url + ") is not available.";
  364. //throw new HttpException(404, message);
  365. }
  366. }
  367. private string GetDescriptorPath()
  368. {
  369. return String.Join("/", new string[] { "assemblies", _xmlDescriptor });
  370. }
  371. private string GetTypeNameFromAppFolder()
  372. {
  373. try
  374. {
  375. using (StreamReader sr = new StreamReader(_context.Request.MapPath("~/" + GetDescriptorPath())))
  376. {
  377. return GetTypeFromDescStream(sr.BaseStream);
  378. }
  379. }
  380. catch (Exception ex)
  381. {
  382. Console.WriteLine(ex);
  383. throw ex;
  384. }
  385. }
  386. internal string GetTypeFromResources()
  387. {
  388. string typeName = null;
  389. //if the desciptor exists in the war - get the type
  390. string descPath = GetDescriptorPath();
  391. try
  392. {
  393. #if DEBUG
  394. Console.WriteLine(descPath);
  395. #endif
  396. using (Stream fs = (Stream)IOUtils.getStreamRecursive("/" + descPath))
  397. {
  398. if (fs != null)
  399. {
  400. return GetTypeFromDescStream(fs);
  401. }
  402. }
  403. }
  404. catch (Exception ex)
  405. {
  406. #if DEBUG
  407. Console.WriteLine(ex);
  408. #endif
  409. }
  410. return null;
  411. }
  412. internal string GetCachedTypeName()
  413. {
  414. string typeName = GetTypeFromResources();
  415. if (typeName == null)
  416. {
  417. //spawn dynamic compilation and lookup typename from created folder
  418. if (InternalCompile())
  419. typeName = GetTypeNameFromAppFolder();
  420. }
  421. return typeName;
  422. }
  423. private string GetTypeName()
  424. {
  425. return String.Format("{0}, {1}", _typeName, _origAssemblyName);
  426. }
  427. private bool LoadMetaFromXmlStream(Stream fs)
  428. {
  429. if (fs != null)
  430. {
  431. try
  432. {
  433. XmlDocument descXml = new XmlDocument();
  434. descXml.Load(fs);
  435. _origAssemblyName = descXml.SelectSingleNode(PAGE_XPATH).Attributes[ASSEM_ATTRIB_NAME].Value;
  436. _typeName = descXml.SelectSingleNode(PAGE_XPATH).Attributes[TYPE_ATTRIB_NAME].Value;
  437. return true;
  438. }
  439. catch
  440. {
  441. #if DEBUG
  442. Console.WriteLine("Failed to load typename from stream");
  443. #endif
  444. }
  445. }
  446. return false;
  447. }
  448. private string GetTypeFromDescStream(Stream fs)
  449. {
  450. if (LoadMetaFromXmlStream(fs))
  451. return GetTypeName();
  452. return null;
  453. }
  454. private string[] GetParserCmd(bool globalAsax)
  455. {
  456. string[] cmd = null;
  457. if (globalAsax)
  458. {
  459. cmd = new string[4];
  460. cmd[3] = "/buildglobalasax";
  461. }
  462. else
  463. {
  464. cmd = new string[5];
  465. cmd[3] = "/aspxFiles:" + _url;
  466. cmd[4] = "/compilepages";
  467. }
  468. cmd[0] = GetParser();
  469. cmd[1] = "/session:" + _session;
  470. cmd[2] = "/appDir:" + (string)AppDomain.CurrentDomain.GetData(IAppDomainConfig.APP_PHYS_DIR);
  471. return cmd;
  472. }
  473. private string GetParser()
  474. {
  475. if (_parser == null)
  476. {
  477. StreamReader sr =
  478. File.OpenText (_context.Request.MapPath ("~/AspxParser.params"));
  479. _parser = sr.ReadLine();
  480. sr.Close();
  481. }
  482. return _parser;
  483. }
  484. private string GetDescFromUrl()
  485. {
  486. string fileName = VirtualPathUtility.GetFileName (_url);
  487. if (fileName.ToLower() == "global.asax")
  488. return "global.asax.xml";
  489. string id = GetIdFromUrl(_url);
  490. string[] descName = new string[3] {fileName, id, ".xml"} ;
  491. return string.Concat(descName).ToLowerInvariant();
  492. }
  493. private string GetIdFromUrl(string path)
  494. {
  495. string fileName = VirtualPathUtility.GetFileName(path);
  496. string id = string.Empty;
  497. if (VirtualPathUtility.IsAbsolute (path))
  498. path = path.Substring (_context.Request.ApplicationPath.Length + 1);
  499. if (path.Length > fileName.Length)
  500. id = "." + path.Substring(0,path.Length - fileName.Length).Replace('/','_');
  501. return id;
  502. }
  503. private Exception GetCompilerError()
  504. {
  505. string _errFile = _context.Request.MapPath ("~/" + _session + ".vmwerr");
  506. if (!File.Exists(_errFile))
  507. throw new FileNotFoundException("Internal Error",_errFile);
  508. StreamReader sr = new StreamReader(_errFile);
  509. string message = string.Empty, line = null, file = null, lineInFile = "0";
  510. while ((line = sr.ReadLine()) != null)
  511. {
  512. if (line.StartsWith("Message: "))
  513. message = line.Substring("Message: ".Length);
  514. else if (line.StartsWith("File: "))
  515. file = line.Substring("File: ".Length);
  516. else if (line.StartsWith("Line: "))
  517. lineInFile = line.Substring("Line: ".Length);
  518. }
  519. sr.Close();
  520. if (file != null)
  521. {
  522. Location loc = new Location(null);
  523. loc.Filename = file;
  524. loc.BeginLine = int.Parse(lineInFile);
  525. return new ParseException(loc,message);
  526. }
  527. if (message.IndexOf(typeof(FileNotFoundException).Name) != -1 &&
  528. message.IndexOf(_url.Trim('\\','/').Replace('/','\\')) != -1)
  529. message = "The requested resource (" + _url + ") is not available.";
  530. return new HttpException(404,(message != null ? message : string.Empty));
  531. }
  532. }
  533. }