AssemblyResourceLoader.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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.Collections.Specialized;
  38. using System.Security.Cryptography;
  39. using System.Text;
  40. using System.Text.RegularExpressions;
  41. using System.Threading;
  42. using System.Web.Configuration;
  43. using System.Web.Util;
  44. namespace System.Web.Handlers
  45. {
  46. #if SYSTEM_WEB_EXTENSIONS
  47. partial class ScriptResourceHandler
  48. {
  49. const string HandlerFileName = "ScriptResource.axd";
  50. static Assembly currAsm = typeof (ScriptResourceHandler).Assembly;
  51. #else
  52. public sealed class AssemblyResourceLoader : IHttpHandler
  53. {
  54. const string HandlerFileName = "WebResource.axd";
  55. static Assembly currAsm = typeof (AssemblyResourceLoader).Assembly;
  56. #endif
  57. const char QueryParamSeparator = '&';
  58. static readonly Dictionary <string, AssemblyEmbeddedResources> _embeddedResources = new Dictionary <string, AssemblyEmbeddedResources> (StringComparer.Ordinal);
  59. static readonly ReaderWriterLockSlim _embeddedResourcesLock = new ReaderWriterLockSlim ();
  60. static readonly ReaderWriterLockSlim _stringHashCacheLock = new ReaderWriterLockSlim ();
  61. static readonly Dictionary <string, string> stringHashCache = new Dictionary <string, string> (StringComparer.Ordinal);
  62. [ThreadStatic]
  63. static KeyedHashAlgorithm hashAlg;
  64. static bool canReuseHashAlg = true;
  65. static KeyedHashAlgorithm ReusableHashAlgorithm {
  66. get {
  67. if (!canReuseHashAlg)
  68. return null;
  69. if (hashAlg == null) {
  70. MachineKeySection mks = MachineKeySection.Config;
  71. hashAlg = MachineKeySectionUtils.GetValidationAlgorithm (mks);
  72. if (!hashAlg.CanReuseTransform) {
  73. canReuseHashAlg = false;
  74. hashAlg = null;
  75. return null;
  76. }
  77. hashAlg.Key = MachineKeySectionUtils.GetValidationKey (mks);
  78. }
  79. if (hashAlg != null)
  80. hashAlg.Initialize ();
  81. return hashAlg;
  82. }
  83. }
  84. static string GetStringHash (KeyedHashAlgorithm kha, string str)
  85. {
  86. if (String.IsNullOrEmpty (str))
  87. return String.Empty;
  88. string result;
  89. try {
  90. _stringHashCacheLock.EnterUpgradeableReadLock ();
  91. if (stringHashCache.TryGetValue (str, out result))
  92. return result;
  93. try {
  94. _stringHashCacheLock.EnterWriteLock ();
  95. if (stringHashCache.TryGetValue (str, out result))
  96. return result;
  97. result = Convert.ToBase64String (kha.ComputeHash (Encoding.UTF8.GetBytes (str)));
  98. stringHashCache.Add (str, result);
  99. } finally {
  100. _stringHashCacheLock.ExitWriteLock ();
  101. }
  102. } finally {
  103. _stringHashCacheLock.ExitUpgradeableReadLock ();
  104. }
  105. return result;
  106. }
  107. static void InitEmbeddedResourcesUrls (KeyedHashAlgorithm kha, Assembly assembly, string assemblyName, string assemblyHash, AssemblyEmbeddedResources entry)
  108. {
  109. WebResourceAttribute [] attrs = (WebResourceAttribute []) assembly.GetCustomAttributes (typeof (WebResourceAttribute), false);
  110. WebResourceAttribute attr;
  111. string apath = assembly.Location;
  112. for (int i = 0; i < attrs.Length; i++) {
  113. attr = attrs [i];
  114. string resourceName = attr.WebResource;
  115. if (!String.IsNullOrEmpty (resourceName)) {
  116. string resourceNameHash = GetStringHash (kha, resourceName);
  117. #if SYSTEM_WEB_EXTENSIONS
  118. bool debug = resourceName.EndsWith (".debug.js", StringComparison.OrdinalIgnoreCase);
  119. string dbgTail = debug ? "d" : String.Empty;
  120. string rkNoNotify = resourceNameHash + "f" + dbgTail;
  121. string rkNotify = resourceNameHash + "t" + dbgTail;
  122. if (!entry.Resources.ContainsKey (rkNoNotify)) {
  123. var er = new EmbeddedResource () {
  124. Name = resourceName,
  125. Attribute = attr,
  126. Url = CreateResourceUrl (kha, assemblyName, assemblyHash, apath, rkNoNotify, debug, false, true)
  127. };
  128. entry.Resources.Add (rkNoNotify, er);
  129. }
  130. if (!entry.Resources.ContainsKey (rkNotify)) {
  131. var er = new EmbeddedResource () {
  132. Name = resourceName,
  133. Attribute = attr,
  134. Url = CreateResourceUrl (kha, assemblyName, assemblyHash, apath, rkNotify, debug, true, true)
  135. };
  136. entry.Resources.Add (rkNotify, er);
  137. }
  138. #else
  139. if (!entry.Resources.ContainsKey (resourceNameHash)) {
  140. var er = new EmbeddedResource () {
  141. Name = resourceName,
  142. Attribute = attr,
  143. Url = CreateResourceUrl (kha, assemblyName, assemblyHash, apath, resourceNameHash, false, false, true)
  144. };
  145. entry.Resources.Add (resourceNameHash, er);
  146. }
  147. #endif
  148. }
  149. }
  150. }
  151. #if !SYSTEM_WEB_EXTENSIONS
  152. internal static string GetResourceUrl (Type type, string resourceName)
  153. {
  154. return GetResourceUrl (type.Assembly, resourceName, false);
  155. }
  156. #endif
  157. static EmbeddedResource DecryptAssemblyResource (string val, out AssemblyEmbeddedResources entry)
  158. {
  159. entry = null;
  160. string[] parts = val.Split ('_');
  161. if (parts.Length != 3)
  162. return null;
  163. string asmNameHash = parts [0];
  164. string resNameHash = parts [1];
  165. try {
  166. _embeddedResourcesLock.EnterReadLock ();
  167. if (!_embeddedResources.TryGetValue (asmNameHash, out entry) || entry == null)
  168. return null;
  169. EmbeddedResource res;
  170. if (!entry.Resources.TryGetValue (resNameHash, out res) || res == null) {
  171. #if SYSTEM_WEB_EXTENSIONS
  172. bool debug = parts [2] == "t";
  173. if (!debug)
  174. return null;
  175. if (!entry.Resources.TryGetValue (resNameHash.Substring (0, resNameHash.Length - 1), out res))
  176. return null;
  177. #else
  178. return null;
  179. #endif
  180. }
  181. return res;
  182. } finally {
  183. _embeddedResourcesLock.ExitReadLock ();
  184. }
  185. }
  186. static void GetAssemblyNameAndHashes (KeyedHashAlgorithm kha, Assembly assembly, string resourceName, out string assemblyName, out string assemblyNameHash, out string resourceNameHash)
  187. {
  188. assemblyName = assembly == currAsm ? "s" : assembly.GetName ().FullName;
  189. assemblyNameHash = GetStringHash (kha, assemblyName);
  190. resourceNameHash = GetStringHash (kha, resourceName);
  191. }
  192. // MUST be called with the _embeddedResourcesLock taken in the upgradeable read lock mode
  193. static AssemblyEmbeddedResources GetAssemblyEmbeddedResource (KeyedHashAlgorithm kha, Assembly assembly, string assemblyNameHash, string assemblyName)
  194. {
  195. AssemblyEmbeddedResources entry;
  196. if (!_embeddedResources.TryGetValue (assemblyNameHash, out entry) || entry == null) {
  197. try {
  198. _embeddedResourcesLock.EnterWriteLock ();
  199. entry = new AssemblyEmbeddedResources () {
  200. AssemblyName = assemblyName
  201. };
  202. InitEmbeddedResourcesUrls (kha, assembly, assemblyName, assemblyNameHash, entry);
  203. _embeddedResources.Add (assemblyNameHash, entry);
  204. } finally {
  205. _embeddedResourcesLock.ExitWriteLock ();
  206. }
  207. }
  208. return entry;
  209. }
  210. internal static string GetResourceUrl (Assembly assembly, string resourceName, bool notifyScriptLoaded)
  211. {
  212. if (assembly == null)
  213. return String.Empty;
  214. KeyedHashAlgorithm kha = ReusableHashAlgorithm;
  215. if (kha != null) {
  216. return GetResourceUrl (kha, assembly, resourceName, notifyScriptLoaded);
  217. } else {
  218. MachineKeySection mks = MachineKeySection.Config;
  219. using (kha = MachineKeySectionUtils.GetValidationAlgorithm (mks)) {
  220. kha.Key = MachineKeySectionUtils.GetValidationKey (mks);
  221. return GetResourceUrl (kha, assembly, resourceName, notifyScriptLoaded);
  222. }
  223. }
  224. }
  225. static string GetResourceUrl (KeyedHashAlgorithm kha, Assembly assembly, string resourceName, bool notifyScriptLoaded)
  226. {
  227. string assemblyName;
  228. string assemblyNameHash;
  229. string resourceNameHash;
  230. GetAssemblyNameAndHashes (kha, assembly, resourceName, out assemblyName, out assemblyNameHash, out resourceNameHash);
  231. bool debug = false;
  232. string url;
  233. AssemblyEmbeddedResources entry;
  234. bool includeTimeStamp = true;
  235. try {
  236. _embeddedResourcesLock.EnterUpgradeableReadLock ();
  237. entry = GetAssemblyEmbeddedResource (kha, assembly, assemblyNameHash, assemblyName);
  238. string lookupKey;
  239. #if SYSTEM_WEB_EXTENSIONS
  240. debug = resourceName.EndsWith (".debug.js", StringComparison.OrdinalIgnoreCase);
  241. string dbgTail = debug ? "d" : String.Empty;
  242. lookupKey = resourceNameHash + (notifyScriptLoaded ? "t" : "f") + dbgTail;
  243. CheckIfResourceIsCompositeScript (resourceName, ref includeTimeStamp);
  244. #else
  245. lookupKey = resourceNameHash;
  246. #endif
  247. EmbeddedResource res;
  248. if (entry.Resources.TryGetValue (lookupKey, out res) && res != null)
  249. url = res.Url;
  250. else {
  251. #if SYSTEM_WEB_EXTENSIONS
  252. if (debug) {
  253. resourceNameHash = GetStringHash (kha, resourceName.Substring (0, resourceName.Length - 9) + ".js");
  254. lookupKey = resourceNameHash + (notifyScriptLoaded ? "t" : "f");
  255. if (entry.Resources.TryGetValue (lookupKey, out res) && res != null)
  256. url = res.Url;
  257. else
  258. url = null;
  259. } else
  260. #endif
  261. url = null;
  262. }
  263. } finally {
  264. _embeddedResourcesLock.ExitUpgradeableReadLock ();
  265. }
  266. if (url == null)
  267. url = CreateResourceUrl (kha, assemblyName, assemblyNameHash, assembly.Location, resourceNameHash, debug, notifyScriptLoaded, includeTimeStamp);
  268. return url;
  269. }
  270. static string CreateResourceUrl (KeyedHashAlgorithm kha, string assemblyName, string assemblyNameHash, string assemblyPath, string resourceNameHash, bool debug,
  271. bool notifyScriptLoaded, bool includeTimeStamp)
  272. {
  273. string atime = String.Empty;
  274. string extra = String.Empty;
  275. #if SYSTEM_WEB_EXTENSIONS
  276. extra = QueryParamSeparator + "n=" + (notifyScriptLoaded ? "t" : "f");
  277. #endif
  278. if (includeTimeStamp) {
  279. if (!String.IsNullOrEmpty (assemblyPath) && File.Exists (assemblyPath))
  280. atime = QueryParamSeparator + "t=" + File.GetLastWriteTimeUtc (assemblyPath).Ticks;
  281. else
  282. atime = QueryParamSeparator + "t=" + DateTime.UtcNow.Ticks;
  283. }
  284. string d = HttpUtility.UrlEncode (assemblyNameHash + "_" + resourceNameHash + (debug ? "_t" : "_f"));
  285. string href = HandlerFileName + "?d=" + d + atime + extra;
  286. HttpContext ctx = HttpContext.Current;
  287. HttpRequest req = ctx != null ? ctx.Request : null;
  288. if (req != null) {
  289. string appPath = VirtualPathUtility.AppendTrailingSlash (req.ApplicationPath);
  290. href = appPath + href;
  291. }
  292. return href;
  293. }
  294. bool HasIfModifiedSince (HttpRequest request, out DateTime modified)
  295. {
  296. string modif_since = request.Headers ["If-Modified-Since"];
  297. if (String.IsNullOrEmpty (modif_since)) {
  298. modified = DateTime.MinValue;
  299. return false;
  300. }
  301. try {
  302. if (DateTime.TryParseExact (modif_since, "r", null, 0, out modified))
  303. return true;
  304. } catch {
  305. modified = DateTime.MinValue;
  306. }
  307. return false;
  308. }
  309. void RespondWithNotModified (HttpContext context)
  310. {
  311. HttpResponse response = context.Response;
  312. response.Clear ();
  313. response.StatusCode = 304;
  314. response.ContentType = null;
  315. context.ApplicationInstance.CompleteRequest ();
  316. }
  317. void SendEmbeddedResource (HttpContext context, out EmbeddedResource res, out Assembly assembly)
  318. {
  319. HttpRequest request = context.Request;
  320. NameValueCollection queryString = request.QueryString;
  321. // val is URL-encoded, which means every + has been replaced with ' ', we
  322. // need to revert that or the base64 conversion will fail.
  323. string d = queryString ["d"];
  324. if (!String.IsNullOrEmpty (d))
  325. d = d.Replace (' ', '+');
  326. AssemblyEmbeddedResources entry;
  327. res = DecryptAssemblyResource (d, out entry);
  328. WebResourceAttribute wra = res != null ? res.Attribute : null;
  329. if (wra == null)
  330. throw new HttpException (404, "Resource not found");
  331. if (entry.AssemblyName == "s")
  332. assembly = currAsm;
  333. else
  334. assembly = Assembly.Load (entry.AssemblyName);
  335. DateTime modified;
  336. if (HasIfModifiedSince (request, out modified)) {
  337. if (File.GetLastWriteTimeUtc (assembly.Location) <= modified) {
  338. RespondWithNotModified (context);
  339. return;
  340. }
  341. }
  342. HttpResponse response = context.Response;
  343. response.ContentType = wra.ContentType;
  344. DateTime utcnow = DateTime.UtcNow;
  345. response.Headers.Add ("Last-Modified", utcnow.ToString ("r"));
  346. response.ExpiresAbsolute = utcnow.AddYears (1);
  347. response.CacheControl = "public";
  348. Stream s = assembly.GetManifestResourceStream (res.Name);
  349. if (s == null)
  350. throw new HttpException (404, "Resource " + res.Name + " not found");
  351. if (wra.PerformSubstitution) {
  352. using (StreamReader r = new StreamReader (s)) {
  353. TextWriter w = response.Output;
  354. new PerformSubstitutionHelper (assembly).PerformSubstitution (r, w);
  355. }
  356. } else if (response.OutputStream is HttpResponseStream) {
  357. UnmanagedMemoryStream st = (UnmanagedMemoryStream) s;
  358. HttpResponseStream hstream = (HttpResponseStream) response.OutputStream;
  359. unsafe {
  360. hstream.WritePtr (new IntPtr (st.PositionPointer), (int) st.Length);
  361. }
  362. } else {
  363. byte [] buf = new byte [1024];
  364. Stream output = response.OutputStream;
  365. int c;
  366. do {
  367. c = s.Read (buf, 0, 1024);
  368. output.Write (buf, 0, c);
  369. } while (c > 0);
  370. }
  371. }
  372. #if !SYSTEM_WEB_EXTENSIONS
  373. void System.Web.IHttpHandler.ProcessRequest (HttpContext context)
  374. {
  375. EmbeddedResource res;
  376. Assembly assembly;
  377. SendEmbeddedResource (context, out res, out assembly);
  378. }
  379. #endif
  380. sealed class PerformSubstitutionHelper
  381. {
  382. readonly Assembly _assembly;
  383. static readonly Regex _regex = new Regex (@"\<%=[ ]*WebResource[ ]*\([ ]*""([^""]+)""[ ]*\)[ ]*%\>");
  384. public PerformSubstitutionHelper (Assembly assembly) {
  385. _assembly = assembly;
  386. }
  387. public void PerformSubstitution (TextReader reader, TextWriter writer) {
  388. string line = reader.ReadLine ();
  389. while (line != null) {
  390. if (line.Length > 0 && _regex.IsMatch (line))
  391. line = _regex.Replace (line, new MatchEvaluator (PerformSubstitutionReplace));
  392. writer.WriteLine (line);
  393. line = reader.ReadLine ();
  394. }
  395. }
  396. string PerformSubstitutionReplace (Match m) {
  397. string resourceName = m.Groups [1].Value;
  398. #if SYSTEM_WEB_EXTENSIONS
  399. return ScriptResourceHandler.GetResourceUrl (_assembly, resourceName, false);
  400. #else
  401. return AssemblyResourceLoader.GetResourceUrl (_assembly, resourceName, false);
  402. #endif
  403. }
  404. }
  405. #if !SYSTEM_WEB_EXTENSIONS
  406. bool System.Web.IHttpHandler.IsReusable { get { return true; } }
  407. #endif
  408. sealed class EmbeddedResource
  409. {
  410. public string Name;
  411. public string Url;
  412. public WebResourceAttribute Attribute;
  413. }
  414. sealed class AssemblyEmbeddedResources
  415. {
  416. public string AssemblyName = String.Empty;
  417. public Dictionary <string, EmbeddedResource> Resources = new Dictionary <string, EmbeddedResource> (StringComparer.Ordinal);
  418. }
  419. }
  420. }