AssemblyResourceLoader.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. //
  2. // System.Web.Handlers.AssemblyResourceLoader
  3. //
  4. // Authors:
  5. // Ben Maurer ([email protected])
  6. //
  7. // (C) 2003 Ben Maurer
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System.Web.UI;
  30. using System.Globalization;
  31. using System.Reflection;
  32. using System.IO;
  33. using System.Resources;
  34. using System.Collections;
  35. using System.Text;
  36. using System.Text.RegularExpressions;
  37. using System.Web.Configuration;
  38. using System.Web.Util;
  39. namespace System.Web.Handlers {
  40. #if SYSTEM_WEB_EXTENSIONS
  41. partial class ScriptResourceHandler
  42. {
  43. const string HandlerFileName = "ScriptResource.axd";
  44. static Assembly currAsm = typeof (ScriptResourceHandler).Assembly;
  45. #else
  46. #if NET_2_0
  47. public sealed
  48. #else
  49. internal // since this is in the .config file, we need to support it, since we dont have versoned support.
  50. #endif
  51. class AssemblyResourceLoader : IHttpHandler {
  52. const string HandlerFileName = "WebResource.axd";
  53. static Assembly currAsm = typeof (AssemblyResourceLoader).Assembly;
  54. #endif
  55. const char QueryParamSeparator = '&';
  56. static readonly Hashtable _embeddedResources = Hashtable.Synchronized (new Hashtable ());
  57. static void InitEmbeddedResourcesUrls (Assembly assembly, Hashtable hashtable)
  58. {
  59. WebResourceAttribute [] attrs = (WebResourceAttribute []) assembly.GetCustomAttributes (typeof (WebResourceAttribute), false);
  60. for (int i = 0; i < attrs.Length; i++) {
  61. string resourceName = attrs [i].WebResource;
  62. if (resourceName != null && resourceName.Length > 0) {
  63. #if SYSTEM_WEB_EXTENSIONS
  64. ResourceKey rkNoNotify = new ResourceKey (resourceName, false);
  65. ResourceKey rkNotify = new ResourceKey (resourceName, true);
  66. if (!hashtable.Contains (rkNoNotify))
  67. hashtable.Add (rkNoNotify, CreateResourceUrl (assembly, resourceName, false));
  68. if (!hashtable.Contains (rkNotify))
  69. hashtable.Add (rkNotify, CreateResourceUrl (assembly, resourceName, true));
  70. #else
  71. if (!hashtable.Contains (resourceName))
  72. hashtable.Add (resourceName, CreateResourceUrl (assembly, resourceName, false));
  73. #endif
  74. }
  75. }
  76. }
  77. #if !SYSTEM_WEB_EXTENSIONS
  78. internal static string GetResourceUrl (Type type, string resourceName)
  79. {
  80. return GetResourceUrl (type.Assembly, resourceName, false);
  81. }
  82. #endif
  83. static string EncryptAssemblyResource (string asmName, string resName)
  84. {
  85. byte[] bytes = Encoding.UTF8.GetBytes (String.Concat (asmName, ";", resName));
  86. bytes = MachineKeySectionUtils.Encrypt (MachineKeySection.Config, bytes);
  87. return Convert.ToBase64String (bytes);
  88. }
  89. static void DecryptAssemblyResource (string val, out string asmName, out string resName)
  90. {
  91. byte[] bytes = Convert.FromBase64String (val);
  92. asmName = null;
  93. resName = null;
  94. byte[] result = MachineKeySectionUtils.Decrypt (MachineKeySection.Config, bytes);
  95. bytes = null;
  96. // null will be returned if, for any reason, decryption fails
  97. if (result == null)
  98. return;
  99. string data = Encoding.UTF8.GetString (result);
  100. result = null;
  101. string[] parts = data.Split (';');
  102. if (parts.Length != 2)
  103. return;
  104. asmName = parts [0];
  105. resName = parts [1];
  106. }
  107. internal static string GetResourceUrl (Assembly assembly, string resourceName, bool notifyScriptLoaded)
  108. {
  109. Hashtable hashtable = (Hashtable)_embeddedResources [assembly];
  110. if (hashtable == null) {
  111. hashtable = new Hashtable ();
  112. InitEmbeddedResourcesUrls (assembly, hashtable);
  113. _embeddedResources [assembly] = hashtable;
  114. }
  115. #if SYSTEM_WEB_EXTENSIONS
  116. string url = (string) hashtable [new ResourceKey (resourceName, notifyScriptLoaded)];
  117. #else
  118. string url = (string) hashtable [resourceName];
  119. #endif
  120. if (url == null)
  121. url = CreateResourceUrl (assembly, resourceName, notifyScriptLoaded);
  122. return url;
  123. }
  124. static string CreateResourceUrl (Assembly assembly, string resourceName, bool notifyScriptLoaded)
  125. {
  126. string aname = assembly == currAsm ? "s" : assembly.GetName ().FullName;
  127. string apath = assembly.Location;
  128. string atime = String.Empty;
  129. string extra = String.Empty;
  130. #if SYSTEM_WEB_EXTENSIONS
  131. extra = String.Concat (QueryParamSeparator, "n=", notifyScriptLoaded ? "t" : "f");
  132. #endif
  133. #if TARGET_JVM
  134. atime = String.Format ("{0}t={1}", QueryParamSeparator, assembly.GetHashCode ());
  135. #else
  136. if (apath != String.Empty)
  137. atime = String.Concat (QueryParamSeparator, "t=", File.GetLastWriteTimeUtc (apath).Ticks);
  138. #endif
  139. string href = HandlerFileName + "?d=" + EncryptAssemblyResource (aname, resourceName) + atime + extra;
  140. HttpContext ctx = HttpContext.Current;
  141. if (ctx != null && ctx.Request != null) {
  142. string appPath = VirtualPathUtility.AppendTrailingSlash (ctx.Request.ApplicationPath);
  143. href = appPath + href;
  144. }
  145. return href;
  146. }
  147. #if SYSTEM_WEB_EXTENSIONS
  148. protected virtual void ProcessRequest (HttpContext context)
  149. #else
  150. [MonoTODO ("Substitution not implemented")]
  151. void System.Web.IHttpHandler.ProcessRequest (HttpContext context)
  152. #endif
  153. {
  154. HttpRequest request = context.Request;
  155. HttpResponse response = context.Response;
  156. string resourceName;
  157. string asmName;
  158. Assembly assembly;
  159. DecryptAssemblyResource (request.QueryString ["d"], out asmName, out resourceName);
  160. if (resourceName == null)
  161. throw new HttpException (404, "No resource name given");
  162. if (asmName == null || asmName == "s")
  163. assembly = currAsm;
  164. else
  165. assembly = Assembly.Load (asmName);
  166. WebResourceAttribute wra = null;
  167. WebResourceAttribute [] attrs = (WebResourceAttribute []) assembly.GetCustomAttributes (typeof (WebResourceAttribute), false);
  168. for (int i = 0; i < attrs.Length; i++) {
  169. if (attrs [i].WebResource == resourceName) {
  170. wra = attrs [i];
  171. break;
  172. }
  173. }
  174. #if SYSTEM_WEB_EXTENSIONS
  175. if (wra == null && resourceName.Length > 9 && resourceName.EndsWith (".debug.js", StringComparison.OrdinalIgnoreCase)) {
  176. resourceName = String.Concat (resourceName.Substring (0, resourceName.Length - 9), ".js");
  177. for (int i = 0; i < attrs.Length; i++) {
  178. if (attrs [i].WebResource == resourceName) {
  179. wra = attrs [i];
  180. break;
  181. }
  182. }
  183. }
  184. #endif
  185. if (wra == null)
  186. throw new HttpException (404, String.Concat ("Resource ", resourceName, " not found"));
  187. string req_cache = request.Headers ["Cache-Control"];
  188. if (req_cache == "max-age=0") {
  189. long atime;
  190. #if NET_2_0
  191. if (Int64.TryParse (request.QueryString ["t"], out atime)) {
  192. #else
  193. atime = -1;
  194. try {
  195. atime = Int64.Parse (request.QueryString ["t"]);
  196. } catch {}
  197. if (atime > -1) {
  198. #endif
  199. if (atime == File.GetLastWriteTimeUtc (assembly.Location).Ticks) {
  200. response.Clear ();
  201. response.StatusCode = 304;
  202. response.ContentType = null;
  203. response.CacheControl = "public"; // easier to set it to public as MS than remove it
  204. context.ApplicationInstance.CompleteRequest ();
  205. return;
  206. }
  207. }
  208. }
  209. string modif_since = request.Headers ["If-Modified-Since"];
  210. if (modif_since != null && modif_since != "") {
  211. try {
  212. DateTime modif;
  213. #if NET_2_0
  214. if (DateTime.TryParseExact (modif_since, "r", null, 0, out modif))
  215. #else
  216. modif = DateTime.MinValue;
  217. try {
  218. modif = DateTime.ParseExact (modif_since, "r", null, 0);
  219. } catch { }
  220. if (modif != DateTime.MinValue)
  221. #endif
  222. if (File.GetLastWriteTimeUtc (assembly.Location) <= modif) {
  223. response.Clear ();
  224. response.StatusCode = 304;
  225. response.ContentType = null;
  226. response.CacheControl = "public"; // easier to set it to public as MS than remove it
  227. context.ApplicationInstance.CompleteRequest ();
  228. return;
  229. }
  230. } catch {}
  231. }
  232. response.ContentType = wra.ContentType;
  233. DateTime utcnow = DateTime.UtcNow;
  234. response.Headers.Add ("Last-Modified", utcnow.ToString ("r"));
  235. response.ExpiresAbsolute = utcnow.AddYears (1);
  236. response.CacheControl = "public";
  237. Stream s = assembly.GetManifestResourceStream (resourceName);
  238. if (s == null)
  239. throw new HttpException (404, String.Concat ("Resource ", resourceName, " not found"));
  240. if (wra.PerformSubstitution) {
  241. using (StreamReader r = new StreamReader (s)) {
  242. TextWriter w = response.Output;
  243. new PerformSubstitutionHelper (assembly).PerformSubstitution (r, w);
  244. }
  245. #if NET_2_0
  246. } else if (response.OutputStream is HttpResponseStream) {
  247. UnmanagedMemoryStream st = (UnmanagedMemoryStream) s;
  248. HttpResponseStream hstream = (HttpResponseStream) response.OutputStream;
  249. unsafe {
  250. hstream.WritePtr (new IntPtr (st.PositionPointer), (int) st.Length);
  251. }
  252. #endif
  253. } else {
  254. byte [] buf = new byte [1024];
  255. Stream output = response.OutputStream;
  256. int c;
  257. do {
  258. c = s.Read (buf, 0, 1024);
  259. output.Write (buf, 0, c);
  260. } while (c > 0);
  261. }
  262. #if SYSTEM_WEB_EXTENSIONS
  263. TextWriter writer = response.Output;
  264. foreach (ScriptResourceAttribute sra in assembly.GetCustomAttributes (typeof (ScriptResourceAttribute), false)) {
  265. if (sra.ScriptName == resourceName) {
  266. string scriptResourceName = sra.ScriptResourceName;
  267. ResourceSet rset = null;
  268. try {
  269. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  270. }
  271. catch (MissingManifestResourceException) {
  272. #if TARGET_JVM // GetResourceSet does not throw MissingManifestResourceException if ressource is not exists
  273. }
  274. if (rset == null) {
  275. #endif
  276. if (scriptResourceName.EndsWith (".resources")) {
  277. scriptResourceName = scriptResourceName.Substring (0, scriptResourceName.Length - 10);
  278. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  279. }
  280. #if !TARGET_JVM
  281. else
  282. throw;
  283. #endif
  284. }
  285. if (rset == null)
  286. break;
  287. writer.WriteLine ();
  288. string ns = sra.TypeName;
  289. int indx = ns.LastIndexOf ('.');
  290. if (indx > 0)
  291. writer.WriteLine ("Type.registerNamespace('" + ns.Substring (0, indx) + "')");
  292. writer.Write ("{0}={{", sra.TypeName);
  293. bool first = true;
  294. foreach (DictionaryEntry entry in rset) {
  295. string value = entry.Value as string;
  296. if (value != null) {
  297. if (first)
  298. first = false;
  299. else
  300. writer.Write (',');
  301. writer.WriteLine ();
  302. writer.Write ("{0}:{1}", GetScriptStringLiteral ((string) entry.Key), GetScriptStringLiteral (value));
  303. }
  304. }
  305. writer.WriteLine ();
  306. writer.WriteLine ("};");
  307. break;
  308. }
  309. }
  310. bool notifyScriptLoaded = request.QueryString ["n"] == "t";
  311. if (notifyScriptLoaded) {
  312. writer.WriteLine ();
  313. writer.WriteLine ("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
  314. }
  315. #endif
  316. }
  317. sealed class PerformSubstitutionHelper
  318. {
  319. readonly Assembly _assembly;
  320. static readonly Regex _regex = new Regex (@"\<%=[ ]*WebResource[ ]*\([ ]*""([^""]+)""[ ]*\)[ ]*%\>");
  321. public PerformSubstitutionHelper (Assembly assembly) {
  322. _assembly = assembly;
  323. }
  324. public void PerformSubstitution (TextReader reader, TextWriter writer) {
  325. string line = reader.ReadLine ();
  326. while (line != null) {
  327. if (line.Length > 0 && _regex.IsMatch (line))
  328. line = _regex.Replace (line, new MatchEvaluator (PerformSubstitutionReplace));
  329. writer.WriteLine (line);
  330. line = reader.ReadLine ();
  331. }
  332. }
  333. string PerformSubstitutionReplace (Match m) {
  334. string resourceName = m.Groups [1].Value;
  335. #if SYSTEM_WEB_EXTENSIONS
  336. return ScriptResourceHandler.GetResourceUrl (_assembly, resourceName, false);
  337. #else
  338. return AssemblyResourceLoader.GetResourceUrl (_assembly, resourceName, false);
  339. #endif
  340. }
  341. }
  342. #if !SYSTEM_WEB_EXTENSIONS
  343. bool System.Web.IHttpHandler.IsReusable { get { return true; } }
  344. #endif
  345. }
  346. }