AssemblyResourceLoader.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. #if NET_3_5
  242. CheckIfResourceIsCompositeScript (resourceName, ref includeTimeStamp);
  243. #endif
  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 TARGET_JVM
  279. atime = QueryParamSeparator + "t=" + assemblyName.GetHashCode ();
  280. #else
  281. if (includeTimeStamp) {
  282. if (!String.IsNullOrEmpty (assemblyPath) && File.Exists (assemblyPath))
  283. atime = QueryParamSeparator + "t=" + File.GetLastWriteTimeUtc (assemblyPath).Ticks;
  284. else
  285. atime = QueryParamSeparator + "t=" + DateTime.UtcNow.Ticks;
  286. }
  287. #endif
  288. string d = assemblyNameHash + "_" + resourceNameHash + (debug ? "_t" : "_f");
  289. string href = HandlerFileName + "?d=" + d + atime + extra;
  290. HttpContext ctx = HttpContext.Current;
  291. HttpRequest req = ctx != null ? ctx.Request : null;
  292. if (req != null) {
  293. string appPath = VirtualPathUtility.AppendTrailingSlash (req.ApplicationPath);
  294. href = appPath + href;
  295. }
  296. return href;
  297. }
  298. bool HasCacheControl (HttpRequest request, NameValueCollection queryString, out long atime)
  299. {
  300. if (String.Compare (request.Headers ["Cache-Control"], "max-age=0", StringComparison.Ordinal) != 0) {
  301. atime = 0;
  302. return false;
  303. }
  304. if (Int64.TryParse (request.QueryString ["t"], out atime))
  305. return true;
  306. return false;
  307. }
  308. bool HasIfModifiedSince (HttpRequest request, out DateTime modified)
  309. {
  310. string modif_since = request.Headers ["If-Modified-Since"];
  311. if (String.IsNullOrEmpty (modif_since)) {
  312. modified = DateTime.MinValue;
  313. return false;
  314. }
  315. try {
  316. if (DateTime.TryParseExact (modif_since, "r", null, 0, out modified))
  317. return true;
  318. } catch {
  319. }
  320. return false;
  321. }
  322. void RespondWithNotModified (HttpContext context)
  323. {
  324. HttpResponse response = context.Response;
  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. }
  331. void SendEmbeddedResource (HttpContext context, out EmbeddedResource res, out Assembly assembly)
  332. {
  333. HttpRequest request = context.Request;
  334. NameValueCollection queryString = request.QueryString;
  335. // val is URL-encoded, which means every + has been replaced with ' ', we
  336. // need to revert that or the base64 conversion will fail.
  337. string d = queryString ["d"];
  338. if (!String.IsNullOrEmpty (d))
  339. d = d.Replace (' ', '+');
  340. AssemblyEmbeddedResources entry;
  341. res = DecryptAssemblyResource (d, out entry);
  342. WebResourceAttribute wra = res != null ? res.Attribute : null;
  343. if (wra == null)
  344. throw new HttpException (404, "Resource not found");
  345. if (entry.AssemblyName == "s")
  346. assembly = currAsm;
  347. else
  348. assembly = Assembly.Load (entry.AssemblyName);
  349. long atime;
  350. if (HasCacheControl (request, queryString, out atime)) {
  351. if (atime == File.GetLastWriteTimeUtc (assembly.Location).Ticks) {
  352. RespondWithNotModified (context);
  353. return;
  354. }
  355. }
  356. DateTime modified;
  357. if (HasIfModifiedSince (request, out modified)) {
  358. if (File.GetLastWriteTimeUtc (assembly.Location) <= modified) {
  359. RespondWithNotModified (context);
  360. return;
  361. }
  362. }
  363. HttpResponse response = context.Response;
  364. response.ContentType = wra.ContentType;
  365. DateTime utcnow = DateTime.UtcNow;
  366. response.Headers.Add ("Last-Modified", utcnow.ToString ("r"));
  367. response.ExpiresAbsolute = utcnow.AddYears (1);
  368. response.CacheControl = "public";
  369. Stream s = assembly.GetManifestResourceStream (res.Name);
  370. if (s == null)
  371. throw new HttpException (404, "Resource " + res.Name + " not found");
  372. if (wra.PerformSubstitution) {
  373. using (StreamReader r = new StreamReader (s)) {
  374. TextWriter w = response.Output;
  375. new PerformSubstitutionHelper (assembly).PerformSubstitution (r, w);
  376. }
  377. } else if (response.OutputStream is HttpResponseStream) {
  378. UnmanagedMemoryStream st = (UnmanagedMemoryStream) s;
  379. HttpResponseStream hstream = (HttpResponseStream) response.OutputStream;
  380. unsafe {
  381. hstream.WritePtr (new IntPtr (st.PositionPointer), (int) st.Length);
  382. }
  383. } else {
  384. byte [] buf = new byte [1024];
  385. Stream output = response.OutputStream;
  386. int c;
  387. do {
  388. c = s.Read (buf, 0, 1024);
  389. output.Write (buf, 0, c);
  390. } while (c > 0);
  391. }
  392. }
  393. #if !SYSTEM_WEB_EXTENSIONS
  394. void System.Web.IHttpHandler.ProcessRequest (HttpContext context)
  395. {
  396. EmbeddedResource res;
  397. Assembly assembly;
  398. SendEmbeddedResource (context, out res, out assembly);
  399. }
  400. #endif
  401. sealed class PerformSubstitutionHelper
  402. {
  403. readonly Assembly _assembly;
  404. static readonly Regex _regex = new Regex (@"\<%=[ ]*WebResource[ ]*\([ ]*""([^""]+)""[ ]*\)[ ]*%\>");
  405. public PerformSubstitutionHelper (Assembly assembly) {
  406. _assembly = assembly;
  407. }
  408. public void PerformSubstitution (TextReader reader, TextWriter writer) {
  409. string line = reader.ReadLine ();
  410. while (line != null) {
  411. if (line.Length > 0 && _regex.IsMatch (line))
  412. line = _regex.Replace (line, new MatchEvaluator (PerformSubstitutionReplace));
  413. writer.WriteLine (line);
  414. line = reader.ReadLine ();
  415. }
  416. }
  417. string PerformSubstitutionReplace (Match m) {
  418. string resourceName = m.Groups [1].Value;
  419. #if SYSTEM_WEB_EXTENSIONS
  420. return ScriptResourceHandler.GetResourceUrl (_assembly, resourceName, false);
  421. #else
  422. return AssemblyResourceLoader.GetResourceUrl (_assembly, resourceName, false);
  423. #endif
  424. }
  425. }
  426. #if !SYSTEM_WEB_EXTENSIONS
  427. bool System.Web.IHttpHandler.IsReusable { get { return true; } }
  428. #endif
  429. sealed class EmbeddedResource
  430. {
  431. public string Name;
  432. public string Url;
  433. public WebResourceAttribute Attribute;
  434. }
  435. sealed class AssemblyEmbeddedResources
  436. {
  437. public string AssemblyName = String.Empty;
  438. public Dictionary <string, EmbeddedResource> Resources = new Dictionary <string, EmbeddedResource> (StringComparer.Ordinal);
  439. }
  440. }
  441. }