AssemblyResourceLoader.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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.Security.Cryptography;
  36. using System.Text;
  37. using System.Text.RegularExpressions;
  38. using System.Web.Configuration;
  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. #if SYSTEM_WEB_EXTENSIONS
  58. static ScriptResourceHandler () {
  59. MachineKeySectionUtils.AutoGenKeys ();
  60. }
  61. #endif
  62. static void InitEmbeddedResourcesUrls (Assembly assembly, Hashtable hashtable)
  63. {
  64. WebResourceAttribute [] attrs = (WebResourceAttribute []) assembly.GetCustomAttributes (typeof (WebResourceAttribute), false);
  65. for (int i = 0; i < attrs.Length; i++) {
  66. string resourceName = attrs [i].WebResource;
  67. if (resourceName != null && resourceName.Length > 0) {
  68. #if SYSTEM_WEB_EXTENSIONS
  69. hashtable.Add (new ResourceKey (resourceName, false), CreateResourceUrl (assembly, resourceName, false));
  70. hashtable.Add (new ResourceKey (resourceName, true), CreateResourceUrl (assembly, resourceName, true));
  71. #else
  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 GetHexString (byte [] bytes)
  84. {
  85. const int letterPart = 55;
  86. const int numberPart = 48;
  87. char [] result = new char [bytes.Length * 2];
  88. for (int i = 0; i < bytes.Length; i++) {
  89. int tmp = (int) bytes [i];
  90. int second = tmp & 15;
  91. int first = (tmp >> 4) & 15;
  92. result [(i * 2)] = (char) (first > 9 ? letterPart + first : numberPart + first);
  93. result [(i * 2) + 1] = (char) (second > 9 ? letterPart + second : numberPart + second);
  94. }
  95. return new string (result);
  96. }
  97. static byte[] GetEncryptionKey ()
  98. {
  99. #if NET_2_0
  100. return MachineKeySectionUtils.DecryptionKey192Bits ();
  101. #else
  102. MachineKeyConfig config = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig;
  103. return config.DecryptionKey192Bits;
  104. #endif
  105. }
  106. static byte[] GetBytes (string val)
  107. {
  108. #if NET_2_0
  109. return MachineKeySectionUtils.GetBytes (val, val.Length);
  110. #else
  111. return MachineKeyConfig.GetBytes (val, val.Length);
  112. #endif
  113. }
  114. static byte [] init_vector = { 0xD, 0xE, 0xA, 0xD, 0xB, 0xE, 0xE, 0xF };
  115. static string EncryptAssemblyResource (string asmName, string resName)
  116. {
  117. byte[] key = GetEncryptionKey ();
  118. byte[] bytes = Encoding.UTF8.GetBytes (String.Concat (asmName, ";", resName));
  119. string result;
  120. ICryptoTransform encryptor = TripleDES.Create ().CreateEncryptor (key, init_vector);
  121. result = GetHexString (encryptor.TransformFinalBlock (bytes, 0, bytes.Length));
  122. bytes = null;
  123. return String.Concat ("d=", result.ToLower (CultureInfo.InvariantCulture));
  124. }
  125. static void DecryptAssemblyResource (string val, out string asmName, out string resName)
  126. {
  127. byte[] key = GetEncryptionKey ();
  128. byte[] bytes = GetBytes (val);
  129. byte[] result;
  130. asmName = null;
  131. resName = null;
  132. ICryptoTransform decryptor = TripleDES.Create ().CreateDecryptor (key, init_vector);
  133. result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
  134. bytes = null;
  135. string data = Encoding.UTF8.GetString (result);
  136. result = null;
  137. string[] parts = data.Split (';');
  138. if (parts.Length != 2)
  139. return;
  140. asmName = parts [0];
  141. resName = parts [1];
  142. }
  143. internal static string GetResourceUrl (Assembly assembly, string resourceName, bool notifyScriptLoaded)
  144. {
  145. Hashtable hashtable = (Hashtable)_embeddedResources [assembly];
  146. if (hashtable == null) {
  147. hashtable = new Hashtable ();
  148. InitEmbeddedResourcesUrls (assembly, hashtable);
  149. _embeddedResources [assembly] = hashtable;
  150. }
  151. #if SYSTEM_WEB_EXTENSIONS
  152. string url = (string) hashtable [new ResourceKey (resourceName, notifyScriptLoaded)];
  153. #else
  154. string url = (string) hashtable [resourceName];
  155. #endif
  156. if (url == null)
  157. url = CreateResourceUrl (assembly, resourceName, notifyScriptLoaded);
  158. return url;
  159. }
  160. static string CreateResourceUrl (Assembly assembly, string resourceName, bool notifyScriptLoaded)
  161. {
  162. string aname = assembly == currAsm ? "s" : assembly.GetName ().FullName;
  163. string apath = assembly.Location;
  164. string atime = String.Empty;
  165. string extra = String.Empty;
  166. #if SYSTEM_WEB_EXTENSIONS
  167. extra = String.Concat (QueryParamSeparator, "n=", notifyScriptLoaded ? "t" : "f");
  168. #endif
  169. #if TARGET_JVM
  170. atime = String.Format ("{0}t={1}", QueryParamSeparator, assembly.GetHashCode ());
  171. #else
  172. if (apath != String.Empty)
  173. atime = String.Concat (QueryParamSeparator, "t=", File.GetLastWriteTimeUtc (apath).Ticks);
  174. #endif
  175. string href = HandlerFileName + "?" + EncryptAssemblyResource (aname, resourceName) + atime + extra;
  176. HttpContext ctx = HttpContext.Current;
  177. if (ctx != null && ctx.Request != null) {
  178. string appPath = VirtualPathUtility.AppendTrailingSlash (ctx.Request.ApplicationPath);
  179. href = appPath + href;
  180. }
  181. return href;
  182. }
  183. #if SYSTEM_WEB_EXTENSIONS
  184. protected virtual void ProcessRequest (HttpContext context)
  185. #else
  186. [MonoTODO ("Substitution not implemented")]
  187. void System.Web.IHttpHandler.ProcessRequest (HttpContext context)
  188. #endif
  189. {
  190. string resourceName;
  191. string asmName;
  192. Assembly assembly;
  193. DecryptAssemblyResource (context.Request.QueryString ["d"], out asmName, out resourceName);
  194. if (resourceName == null)
  195. throw new HttpException (404, "No resource name given");
  196. if (asmName == null || asmName == "s")
  197. assembly = currAsm;
  198. else
  199. assembly = Assembly.Load (asmName);
  200. WebResourceAttribute wra = null;
  201. WebResourceAttribute [] attrs = (WebResourceAttribute []) assembly.GetCustomAttributes (typeof (WebResourceAttribute), false);
  202. for (int i = 0; i < attrs.Length; i++) {
  203. if (attrs [i].WebResource == resourceName) {
  204. wra = attrs [i];
  205. break;
  206. }
  207. }
  208. #if SYSTEM_WEB_EXTENSIONS
  209. if (wra == null && resourceName.Length > 9 && resourceName.EndsWith (".debug.js", StringComparison.OrdinalIgnoreCase)) {
  210. resourceName = String.Concat (resourceName.Substring (0, resourceName.Length - 9), ".js");
  211. for (int i = 0; i < attrs.Length; i++) {
  212. if (attrs [i].WebResource == resourceName) {
  213. wra = attrs [i];
  214. break;
  215. }
  216. }
  217. }
  218. #endif
  219. if (wra == null)
  220. throw new HttpException (404, String.Concat ("Resource ", resourceName, " not found"));
  221. context.Response.ContentType = wra.ContentType;
  222. /* tell the client they can cache resources for 1 year */
  223. context.Response.ExpiresAbsolute = DateTime.Now.AddYears (1);
  224. context.Response.CacheControl = "private";
  225. Stream s = assembly.GetManifestResourceStream (resourceName);
  226. if (s == null)
  227. throw new HttpException (404, String.Concat ("Resource ", resourceName, " not found"));
  228. if (wra.PerformSubstitution) {
  229. StreamReader r = new StreamReader (s);
  230. TextWriter w = context.Response.Output;
  231. new PerformSubstitutionHelper (assembly).PerformSubstitution (r, w);
  232. }
  233. else {
  234. byte [] buf = new byte [1024];
  235. Stream output = context.Response.OutputStream;
  236. int c;
  237. do {
  238. c = s.Read (buf, 0, 1024);
  239. output.Write (buf, 0, c);
  240. } while (c > 0);
  241. }
  242. #if SYSTEM_WEB_EXTENSIONS
  243. TextWriter writer = context.Response.Output;
  244. foreach (ScriptResourceAttribute sra in assembly.GetCustomAttributes (typeof (ScriptResourceAttribute), false)) {
  245. if (sra.ScriptName == resourceName) {
  246. string scriptResourceName = sra.ScriptResourceName;
  247. ResourceSet rset = null;
  248. try {
  249. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  250. }
  251. catch (MissingManifestResourceException) {
  252. #if TARGET_JVM // GetResourceSet does not throw MissingManifestResourceException if ressource is not exists
  253. }
  254. if (rset == null) {
  255. #endif
  256. if (scriptResourceName.EndsWith (".resources")) {
  257. scriptResourceName = scriptResourceName.Substring (0, scriptResourceName.Length - 10);
  258. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  259. }
  260. #if !TARGET_JVM
  261. else
  262. throw;
  263. #endif
  264. }
  265. if (rset == null)
  266. break;
  267. writer.WriteLine ();
  268. writer.Write ("{0}={{", sra.TypeName);
  269. bool first = true;
  270. foreach (DictionaryEntry entry in rset) {
  271. string value = entry.Value as string;
  272. if (value != null) {
  273. if (first)
  274. first = false;
  275. else
  276. writer.Write (',');
  277. writer.WriteLine ();
  278. writer.Write ("{0}:{1}", GetScriptStringLiteral ((string) entry.Key), GetScriptStringLiteral (value));
  279. }
  280. }
  281. writer.WriteLine ();
  282. writer.WriteLine ("};");
  283. break;
  284. }
  285. }
  286. bool notifyScriptLoaded = context.Request.QueryString ["n"] == "t";
  287. if (notifyScriptLoaded) {
  288. writer.WriteLine ();
  289. writer.WriteLine ("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
  290. }
  291. #endif
  292. }
  293. sealed class PerformSubstitutionHelper
  294. {
  295. readonly Assembly _assembly;
  296. static readonly Regex _regex = new Regex (@"\<%=[ ]*WebResource[ ]*\([ ]*""([^""]+)""[ ]*\)[ ]*%\>");
  297. public PerformSubstitutionHelper (Assembly assembly) {
  298. _assembly = assembly;
  299. }
  300. public void PerformSubstitution (TextReader reader, TextWriter writer) {
  301. string line = reader.ReadLine ();
  302. while (line != null) {
  303. if (line.Length > 0 && _regex.IsMatch (line))
  304. line = _regex.Replace (line, new MatchEvaluator (PerformSubstitutionReplace));
  305. writer.WriteLine (line);
  306. line = reader.ReadLine ();
  307. }
  308. }
  309. string PerformSubstitutionReplace (Match m) {
  310. string resourceName = m.Groups [1].Value;
  311. #if SYSTEM_WEB_EXTENSIONS
  312. return ScriptResourceHandler.GetResourceUrl (_assembly, resourceName, false);
  313. #else
  314. return AssemblyResourceLoader.GetResourceUrl (_assembly, resourceName, false);
  315. #endif
  316. }
  317. }
  318. #if !SYSTEM_WEB_EXTENSIONS
  319. bool System.Web.IHttpHandler.IsReusable { get { return true; } }
  320. #endif
  321. }
  322. }