AssemblyResourceLoader.cs 16 KB

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