AssemblyResourceLoader.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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 = HttpUtility.UrlEncode (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 HasIfModifiedSince (HttpRequest request, out DateTime modified)
  299. {
  300. string modif_since = request.Headers ["If-Modified-Since"];
  301. if (String.IsNullOrEmpty (modif_since)) {
  302. modified = DateTime.MinValue;
  303. return false;
  304. }
  305. try {
  306. if (DateTime.TryParseExact (modif_since, "r", null, 0, out modified))
  307. return true;
  308. } catch {
  309. modified = DateTime.MinValue;
  310. }
  311. return false;
  312. }
  313. void RespondWithNotModified (HttpContext context)
  314. {
  315. HttpResponse response = context.Response;
  316. response.Clear ();
  317. response.StatusCode = 304;
  318. response.ContentType = null;
  319. context.ApplicationInstance.CompleteRequest ();
  320. }
  321. void SendEmbeddedResource (HttpContext context, out EmbeddedResource res, out Assembly assembly)
  322. {
  323. HttpRequest request = context.Request;
  324. NameValueCollection queryString = request.QueryString;
  325. // val is URL-encoded, which means every + has been replaced with ' ', we
  326. // need to revert that or the base64 conversion will fail.
  327. string d = queryString ["d"];
  328. if (!String.IsNullOrEmpty (d))
  329. d = d.Replace (' ', '+');
  330. AssemblyEmbeddedResources entry;
  331. res = DecryptAssemblyResource (d, out entry);
  332. WebResourceAttribute wra = res != null ? res.Attribute : null;
  333. if (wra == null)
  334. throw new HttpException (404, "Resource not found");
  335. if (entry.AssemblyName == "s")
  336. assembly = currAsm;
  337. else
  338. assembly = Assembly.Load (entry.AssemblyName);
  339. DateTime modified;
  340. if (HasIfModifiedSince (request, out modified)) {
  341. if (File.GetLastWriteTimeUtc (assembly.Location) <= modified) {
  342. RespondWithNotModified (context);
  343. return;
  344. }
  345. }
  346. HttpResponse response = context.Response;
  347. response.ContentType = wra.ContentType;
  348. DateTime utcnow = DateTime.UtcNow;
  349. response.Headers.Add ("Last-Modified", utcnow.ToString ("r"));
  350. response.ExpiresAbsolute = utcnow.AddYears (1);
  351. response.CacheControl = "public";
  352. Stream s = assembly.GetManifestResourceStream (res.Name);
  353. if (s == null)
  354. throw new HttpException (404, "Resource " + res.Name + " not found");
  355. if (wra.PerformSubstitution) {
  356. using (StreamReader r = new StreamReader (s)) {
  357. TextWriter w = response.Output;
  358. new PerformSubstitutionHelper (assembly).PerformSubstitution (r, w);
  359. }
  360. } else if (response.OutputStream is HttpResponseStream) {
  361. UnmanagedMemoryStream st = (UnmanagedMemoryStream) s;
  362. HttpResponseStream hstream = (HttpResponseStream) response.OutputStream;
  363. unsafe {
  364. hstream.WritePtr (new IntPtr (st.PositionPointer), (int) st.Length);
  365. }
  366. } else {
  367. byte [] buf = new byte [1024];
  368. Stream output = response.OutputStream;
  369. int c;
  370. do {
  371. c = s.Read (buf, 0, 1024);
  372. output.Write (buf, 0, c);
  373. } while (c > 0);
  374. }
  375. }
  376. #if !SYSTEM_WEB_EXTENSIONS
  377. void System.Web.IHttpHandler.ProcessRequest (HttpContext context)
  378. {
  379. EmbeddedResource res;
  380. Assembly assembly;
  381. SendEmbeddedResource (context, out res, out assembly);
  382. }
  383. #endif
  384. sealed class PerformSubstitutionHelper
  385. {
  386. readonly Assembly _assembly;
  387. static readonly Regex _regex = new Regex (@"\<%=[ ]*WebResource[ ]*\([ ]*""([^""]+)""[ ]*\)[ ]*%\>");
  388. public PerformSubstitutionHelper (Assembly assembly) {
  389. _assembly = assembly;
  390. }
  391. public void PerformSubstitution (TextReader reader, TextWriter writer) {
  392. string line = reader.ReadLine ();
  393. while (line != null) {
  394. if (line.Length > 0 && _regex.IsMatch (line))
  395. line = _regex.Replace (line, new MatchEvaluator (PerformSubstitutionReplace));
  396. writer.WriteLine (line);
  397. line = reader.ReadLine ();
  398. }
  399. }
  400. string PerformSubstitutionReplace (Match m) {
  401. string resourceName = m.Groups [1].Value;
  402. #if SYSTEM_WEB_EXTENSIONS
  403. return ScriptResourceHandler.GetResourceUrl (_assembly, resourceName, false);
  404. #else
  405. return AssemblyResourceLoader.GetResourceUrl (_assembly, resourceName, false);
  406. #endif
  407. }
  408. }
  409. #if !SYSTEM_WEB_EXTENSIONS
  410. bool System.Web.IHttpHandler.IsReusable { get { return true; } }
  411. #endif
  412. sealed class EmbeddedResource
  413. {
  414. public string Name;
  415. public string Url;
  416. public WebResourceAttribute Attribute;
  417. }
  418. sealed class AssemblyEmbeddedResources
  419. {
  420. public string AssemblyName = String.Empty;
  421. public Dictionary <string, EmbeddedResource> Resources = new Dictionary <string, EmbeddedResource> (StringComparer.Ordinal);
  422. }
  423. }
  424. }