PageMapper.cs 16 KB

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