AssemblyResourceLoader.cs 13 KB

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