AssemblyResourceLoader.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. //
  2. // System.Web.Handlers.AssemblyResourceLoader
  3. //
  4. // Authors:
  5. // Ben Maurer ([email protected])
  6. // Marek Habersack <[email protected]>
  7. //
  8. // (C) 2003 Ben Maurer
  9. // (C) 2010 Novell, Inc (http://novell.com/)
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System.Web.UI;
  31. using System.Globalization;
  32. using System.Reflection;
  33. using System.IO;
  34. using System.Resources;
  35. using System.Collections;
  36. using System.Collections.Generic;
  37. using System.Security.Cryptography;
  38. using System.Text;
  39. using System.Text.RegularExpressions;
  40. using System.Threading;
  41. using System.Web.Configuration;
  42. using System.Web.Util;
  43. namespace System.Web.Handlers
  44. {
  45. #if SYSTEM_WEB_EXTENSIONS
  46. partial class ScriptResourceHandler
  47. {
  48. const string HandlerFileName = "ScriptResource.axd";
  49. static Assembly currAsm = typeof (ScriptResourceHandler).Assembly;
  50. #else
  51. #if NET_2_0
  52. public sealed
  53. #else
  54. internal // since this is in the .config file, we need to support it, since we dont have versoned support.
  55. #endif
  56. class AssemblyResourceLoader : IHttpHandler
  57. {
  58. const string HandlerFileName = "WebResource.axd";
  59. static Assembly currAsm = typeof (AssemblyResourceLoader).Assembly;
  60. #endif
  61. const char QueryParamSeparator = '&';
  62. static readonly Dictionary <string, AssemblyEmbeddedResources> _embeddedResources = new Dictionary <string, AssemblyEmbeddedResources> (StringComparer.Ordinal);
  63. static readonly ReaderWriterLockSlim _embeddedResourcesLock = new ReaderWriterLockSlim ();
  64. static readonly ReaderWriterLockSlim _stringHashCacheLock = new ReaderWriterLockSlim ();
  65. static readonly Dictionary <string, string> stringHashCache = new Dictionary <string, string> (StringComparer.Ordinal);
  66. [ThreadStatic]
  67. static KeyedHashAlgorithm hashAlg;
  68. static bool canReuseHashAlg = true;
  69. static KeyedHashAlgorithm ReusableHashAlgorithm {
  70. get {
  71. if (!canReuseHashAlg)
  72. return null;
  73. if (hashAlg == null) {
  74. MachineKeySection mks = MachineKeySection.Config;
  75. hashAlg = MachineKeySectionUtils.GetValidationAlgorithm (mks);
  76. if (!hashAlg.CanReuseTransform) {
  77. canReuseHashAlg = false;
  78. hashAlg = null;
  79. }
  80. }
  81. if (hashAlg != null)
  82. hashAlg.Initialize ();
  83. return hashAlg;
  84. }
  85. }
  86. static string GetStringHash (KeyedHashAlgorithm kha, string str)
  87. {
  88. if (String.IsNullOrEmpty (str))
  89. return String.Empty;
  90. string result;
  91. try {
  92. _stringHashCacheLock.EnterUpgradeableReadLock ();
  93. if (stringHashCache.TryGetValue (str, out result))
  94. return result;
  95. try {
  96. _stringHashCacheLock.EnterWriteLock ();
  97. if (stringHashCache.TryGetValue (str, out result))
  98. return result;
  99. result = Convert.ToBase64String (kha.ComputeHash (Encoding.UTF8.GetBytes (str)));
  100. stringHashCache.Add (str, result);
  101. } finally {
  102. _stringHashCacheLock.ExitWriteLock ();
  103. }
  104. } finally {
  105. _stringHashCacheLock.ExitUpgradeableReadLock ();
  106. }
  107. return result;
  108. }
  109. static void InitEmbeddedResourcesUrls (KeyedHashAlgorithm kha, Assembly assembly, string assemblyName, string assemblyHash, AssemblyEmbeddedResources entry)
  110. {
  111. WebResourceAttribute [] attrs = (WebResourceAttribute []) assembly.GetCustomAttributes (typeof (WebResourceAttribute), false);
  112. WebResourceAttribute attr;
  113. string apath = assembly.Location;
  114. for (int i = 0; i < attrs.Length; i++) {
  115. attr = attrs [i];
  116. string resourceName = attr.WebResource;
  117. if (!String.IsNullOrEmpty (resourceName)) {
  118. string resourceNameHash = GetStringHash (kha, resourceName);
  119. #if SYSTEM_WEB_EXTENSIONS
  120. bool debug = resourceName.EndsWith (".debug.js", StringComparison.OrdinalIgnoreCase);
  121. string dbgTail = debug ? "d" : String.Empty;
  122. string rkNoNotify = resourceNameHash + "f" + dbgTail;
  123. string rkNotify = resourceNameHash + "t" + dbgTail;
  124. if (!entry.Resources.ContainsKey (rkNoNotify)) {
  125. var er = new EmbeddedResource () {
  126. Name = resourceName,
  127. Attribute = attr,
  128. Url = CreateResourceUrl (kha, assemblyName, assemblyHash, apath, rkNoNotify, debug, false)
  129. };
  130. entry.Resources.Add (rkNoNotify, er);
  131. }
  132. if (!entry.Resources.ContainsKey (rkNotify)) {
  133. var er = new EmbeddedResource () {
  134. Name = resourceName,
  135. Attribute = attr,
  136. Url = CreateResourceUrl (kha, assemblyName, assemblyHash, apath, rkNotify, debug, true)
  137. };
  138. entry.Resources.Add (rkNotify, er);
  139. }
  140. #else
  141. if (!entry.Resources.ContainsKey (resourceNameHash)) {
  142. var er = new EmbeddedResource () {
  143. Name = resourceName,
  144. Attribute = attr,
  145. Url = CreateResourceUrl (kha, assemblyName, assemblyHash, apath, resourceNameHash, false, false)
  146. };
  147. entry.Resources.Add (resourceNameHash, er);
  148. }
  149. #endif
  150. }
  151. }
  152. }
  153. #if !SYSTEM_WEB_EXTENSIONS
  154. internal static string GetResourceUrl (Type type, string resourceName)
  155. {
  156. return GetResourceUrl (type.Assembly, resourceName, false);
  157. }
  158. #endif
  159. static EmbeddedResource DecryptAssemblyResource (string val, out AssemblyEmbeddedResources entry)
  160. {
  161. entry = null;
  162. string[] parts = val.Split ('_');
  163. if (parts.Length != 3)
  164. return null;
  165. Encoding enc = Encoding.UTF8;
  166. string asmNameHash = parts [0];
  167. string resNameHash = parts [1];
  168. bool debug = parts [2] == "t";
  169. try {
  170. _embeddedResourcesLock.EnterReadLock ();
  171. if (!_embeddedResources.TryGetValue (asmNameHash, out entry) || entry == null)
  172. return null;
  173. EmbeddedResource res;
  174. if (!entry.Resources.TryGetValue (resNameHash, out res) || res == null) {
  175. #if SYSTEM_WEB_EXTENSIONS
  176. if (!debug)
  177. return null;
  178. if (!entry.Resources.TryGetValue (resNameHash.Substring (0, resNameHash.Length - 1), out res))
  179. return null;
  180. #else
  181. return null;
  182. #endif
  183. }
  184. return res;
  185. } finally {
  186. _embeddedResourcesLock.ExitReadLock ();
  187. }
  188. }
  189. internal static string GetResourceUrl (Assembly assembly, string resourceName, bool notifyScriptLoaded)
  190. {
  191. if (assembly == null)
  192. return String.Empty;
  193. KeyedHashAlgorithm kha = ReusableHashAlgorithm;
  194. if (kha != null) {
  195. return GetResourceUrl (kha, assembly, resourceName, notifyScriptLoaded);
  196. } else {
  197. MachineKeySection mks = MachineKeySection.Config;
  198. using (kha = MachineKeySectionUtils.GetValidationAlgorithm (mks)) {
  199. kha.Key = MachineKeySectionUtils.GetValidationKey (mks);
  200. return GetResourceUrl (kha, assembly, resourceName, notifyScriptLoaded);
  201. }
  202. }
  203. }
  204. static string GetResourceUrl (KeyedHashAlgorithm kha, Assembly assembly, string resourceName, bool notifyScriptLoaded)
  205. {
  206. string assemblyName = assembly == currAsm ? "s" : assembly.GetName ().FullName;
  207. string assemblyNameHash = GetStringHash (kha, assemblyName);
  208. string resourceNameHash = GetStringHash (kha, resourceName);
  209. bool debug = false;
  210. string url;
  211. AssemblyEmbeddedResources entry;
  212. try {
  213. _embeddedResourcesLock.EnterUpgradeableReadLock ();
  214. if (!_embeddedResources.TryGetValue (assemblyNameHash, out entry) || entry == null) {
  215. try {
  216. _embeddedResourcesLock.EnterWriteLock ();
  217. entry = new AssemblyEmbeddedResources () {
  218. AssemblyName = assemblyName
  219. };
  220. InitEmbeddedResourcesUrls (kha, assembly, assemblyName, assemblyNameHash, entry);
  221. _embeddedResources.Add (assemblyNameHash, entry);
  222. } finally {
  223. _embeddedResourcesLock.ExitWriteLock ();
  224. }
  225. }
  226. string lookupKey;
  227. #if SYSTEM_WEB_EXTENSIONS
  228. debug = resourceName.EndsWith (".debug.js", StringComparison.OrdinalIgnoreCase);
  229. string dbgTail = debug ? "d" : String.Empty;
  230. lookupKey = resourceNameHash + (notifyScriptLoaded ? "t" : "f") + dbgTail;
  231. #else
  232. lookupKey = resourceNameHash;
  233. #endif
  234. EmbeddedResource res;
  235. if (entry.Resources.TryGetValue (lookupKey, out res) && res != null)
  236. url = res.Url;
  237. else {
  238. #if SYSTEM_WEB_EXTENSIONS
  239. if (debug) {
  240. resourceNameHash = GetStringHash (kha, resourceName.Substring (0, resourceName.Length - 9) + ".js");
  241. lookupKey = resourceNameHash + (notifyScriptLoaded ? "t" : "f");
  242. if (entry.Resources.TryGetValue (lookupKey, out res) && res != null)
  243. url = res.Url;
  244. else
  245. url = null;
  246. } else
  247. #endif
  248. url = null;
  249. }
  250. } finally {
  251. _embeddedResourcesLock.ExitUpgradeableReadLock ();
  252. }
  253. if (url == null)
  254. url = CreateResourceUrl (kha, assemblyName, assemblyNameHash, assembly.Location, resourceNameHash, debug, notifyScriptLoaded);
  255. return url;
  256. }
  257. static string CreateResourceUrl (KeyedHashAlgorithm kha, string assemblyName, string assemblyNameHash, string assemblyPath, string resourceNameHash, bool debug, bool notifyScriptLoaded)
  258. {
  259. string atime = String.Empty;
  260. string extra = String.Empty;
  261. #if SYSTEM_WEB_EXTENSIONS
  262. extra = QueryParamSeparator + "n=" + (notifyScriptLoaded ? "t" : "f");
  263. #endif
  264. #if TARGET_JVM
  265. atime = QueryParamSeparator + "t=" + assemblyName.GetHashCode ();
  266. #else
  267. if (!String.IsNullOrEmpty (assemblyPath) && File.Exists (assemblyPath))
  268. atime = QueryParamSeparator + "t=" + File.GetLastWriteTimeUtc (assemblyPath).Ticks;
  269. else
  270. atime = QueryParamSeparator + "t=" + DateTime.UtcNow.Ticks;
  271. #endif
  272. string d = assemblyNameHash + "_" + resourceNameHash + (debug ? "_t" : "_f");
  273. string href = HandlerFileName + "?d=" + d + atime + extra;
  274. HttpContext ctx = HttpContext.Current;
  275. HttpRequest req = ctx != null ? ctx.Request : null;
  276. if (req != null) {
  277. string appPath = VirtualPathUtility.AppendTrailingSlash (req.ApplicationPath);
  278. href = appPath + href;
  279. }
  280. return href;
  281. }
  282. #if SYSTEM_WEB_EXTENSIONS
  283. protected virtual void ProcessRequest (HttpContext context)
  284. #else
  285. void System.Web.IHttpHandler.ProcessRequest (HttpContext context)
  286. #endif
  287. {
  288. HttpRequest request = context.Request;
  289. // val is URL-encoded, which means every + has been replaced with ' ', we
  290. // need to revert that or the base64 conversion will fail.
  291. string d = request.QueryString ["d"];
  292. if (!String.IsNullOrEmpty (d))
  293. d = d.Replace (' ', '+');
  294. AssemblyEmbeddedResources entry;
  295. EmbeddedResource res = DecryptAssemblyResource (d, out entry);
  296. WebResourceAttribute wra = res != null ? res.Attribute : null;
  297. if (wra == null)
  298. throw new HttpException (404, "Resource not found");
  299. Assembly assembly;
  300. if (entry.AssemblyName == "s")
  301. assembly = currAsm;
  302. else
  303. assembly = Assembly.Load (entry.AssemblyName);
  304. HttpResponse response = context.Response;
  305. string req_cache = request.Headers ["Cache-Control"];
  306. if (String.Compare (req_cache, "max-age=0", StringComparison.Ordinal) == 0) {
  307. long atime;
  308. if (Int64.TryParse (request.QueryString ["t"], out atime)) {
  309. if (atime == File.GetLastWriteTimeUtc (assembly.Location).Ticks) {
  310. response.Clear ();
  311. response.StatusCode = 304;
  312. response.ContentType = null;
  313. response.CacheControl = "public"; // easier to set it to public as MS than remove it
  314. context.ApplicationInstance.CompleteRequest ();
  315. return;
  316. }
  317. }
  318. }
  319. string modif_since = request.Headers ["If-Modified-Since"];
  320. if (!String.IsNullOrEmpty (modif_since)) {
  321. try {
  322. DateTime modif;
  323. if (DateTime.TryParseExact (modif_since, "r", null, 0, out modif)) {
  324. if (File.GetLastWriteTimeUtc (assembly.Location) <= modif) {
  325. response.Clear ();
  326. response.StatusCode = 304;
  327. response.ContentType = null;
  328. response.CacheControl = "public"; // easier to set it to public as MS than remove it
  329. context.ApplicationInstance.CompleteRequest ();
  330. return;
  331. }
  332. }
  333. } catch {}
  334. }
  335. response.ContentType = wra.ContentType;
  336. DateTime utcnow = DateTime.UtcNow;
  337. response.Headers.Add ("Last-Modified", utcnow.ToString ("r"));
  338. response.ExpiresAbsolute = utcnow.AddYears (1);
  339. response.CacheControl = "public";
  340. Stream s = assembly.GetManifestResourceStream (res.Name);
  341. if (s == null)
  342. throw new HttpException (404, "Resource " + res.Name + " not found");
  343. if (wra.PerformSubstitution) {
  344. using (StreamReader r = new StreamReader (s)) {
  345. TextWriter w = response.Output;
  346. new PerformSubstitutionHelper (assembly).PerformSubstitution (r, w);
  347. }
  348. } else if (response.OutputStream is HttpResponseStream) {
  349. UnmanagedMemoryStream st = (UnmanagedMemoryStream) s;
  350. HttpResponseStream hstream = (HttpResponseStream) response.OutputStream;
  351. unsafe {
  352. hstream.WritePtr (new IntPtr (st.PositionPointer), (int) st.Length);
  353. }
  354. } else {
  355. byte [] buf = new byte [1024];
  356. Stream output = response.OutputStream;
  357. int c;
  358. do {
  359. c = s.Read (buf, 0, 1024);
  360. output.Write (buf, 0, c);
  361. } while (c > 0);
  362. }
  363. #if SYSTEM_WEB_EXTENSIONS
  364. TextWriter writer = response.Output;
  365. foreach (ScriptResourceAttribute sra in assembly.GetCustomAttributes (typeof (ScriptResourceAttribute), false)) {
  366. if (String.Compare (sra.ScriptName, res.Name, StringComparison.Ordinal) == 0) {
  367. string scriptResourceName = sra.ScriptResourceName;
  368. ResourceSet rset = null;
  369. try {
  370. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  371. }
  372. catch (MissingManifestResourceException) {
  373. #if TARGET_JVM // GetResourceSet does not throw MissingManifestResourceException if ressource is not exists
  374. }
  375. if (rset == null) {
  376. #endif
  377. if (scriptResourceName.EndsWith (".resources")) {
  378. scriptResourceName = scriptResourceName.Substring (0, scriptResourceName.Length - 10);
  379. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  380. }
  381. #if !TARGET_JVM
  382. else
  383. throw;
  384. #endif
  385. }
  386. if (rset == null)
  387. break;
  388. writer.WriteLine ();
  389. string ns = sra.TypeName;
  390. int indx = ns.LastIndexOf ('.');
  391. if (indx > 0)
  392. writer.WriteLine ("Type.registerNamespace('" + ns.Substring (0, indx) + "')");
  393. writer.Write ("{0}={{", sra.TypeName);
  394. bool first = true;
  395. foreach (DictionaryEntry de in rset) {
  396. string value = de.Value as string;
  397. if (value != null) {
  398. if (first)
  399. first = false;
  400. else
  401. writer.Write (',');
  402. writer.WriteLine ();
  403. writer.Write ("{0}:{1}", GetScriptStringLiteral ((string) de.Key), GetScriptStringLiteral (value));
  404. }
  405. }
  406. writer.WriteLine ();
  407. writer.WriteLine ("};");
  408. break;
  409. }
  410. }
  411. bool notifyScriptLoaded = request.QueryString ["n"] == "t";
  412. if (notifyScriptLoaded) {
  413. writer.WriteLine ();
  414. writer.WriteLine ("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
  415. }
  416. #endif
  417. }
  418. sealed class PerformSubstitutionHelper
  419. {
  420. readonly Assembly _assembly;
  421. static readonly Regex _regex = new Regex (@"\<%=[ ]*WebResource[ ]*\([ ]*""([^""]+)""[ ]*\)[ ]*%\>");
  422. public PerformSubstitutionHelper (Assembly assembly) {
  423. _assembly = assembly;
  424. }
  425. public void PerformSubstitution (TextReader reader, TextWriter writer) {
  426. string line = reader.ReadLine ();
  427. while (line != null) {
  428. if (line.Length > 0 && _regex.IsMatch (line))
  429. line = _regex.Replace (line, new MatchEvaluator (PerformSubstitutionReplace));
  430. writer.WriteLine (line);
  431. line = reader.ReadLine ();
  432. }
  433. }
  434. string PerformSubstitutionReplace (Match m) {
  435. string resourceName = m.Groups [1].Value;
  436. #if SYSTEM_WEB_EXTENSIONS
  437. return ScriptResourceHandler.GetResourceUrl (_assembly, resourceName, false);
  438. #else
  439. return AssemblyResourceLoader.GetResourceUrl (_assembly, resourceName, false);
  440. #endif
  441. }
  442. }
  443. #if !SYSTEM_WEB_EXTENSIONS
  444. bool System.Web.IHttpHandler.IsReusable { get { return true; } }
  445. #endif
  446. sealed class EmbeddedResource
  447. {
  448. public string Name;
  449. public string Url;
  450. public WebResourceAttribute Attribute;
  451. }
  452. sealed class AssemblyEmbeddedResources
  453. {
  454. public string AssemblyName = String.Empty;
  455. public Dictionary <string, EmbeddedResource> Resources = new Dictionary <string, EmbeddedResource> (StringComparer.Ordinal);
  456. }
  457. }
  458. }