AssemblyResourceLoader.cs 15 KB

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