AssemblyResourceLoader.cs 15 KB

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