AssemblyResourceLoader.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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.Format ("{0};{1}", 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.Format ("d={0}", 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.Format ("{0}n={1}", QueryParamSeparator, 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.Format ("{0}t={1}", QueryParamSeparator, File.GetLastWriteTimeUtc (apath).Ticks);
  174. #endif
  175. string href = String.Format ("{0}?{1}{2}{3}", HandlerFileName,
  176. EncryptAssemblyResource (aname, resourceName), atime, extra);
  177. HttpContext ctx = HttpContext.Current;
  178. if (ctx != null && ctx.Request != null) {
  179. string appPath = VirtualPathUtility.AppendTrailingSlash (ctx.Request.ApplicationPath);
  180. href = appPath + href;
  181. }
  182. return href;
  183. }
  184. #if SYSTEM_WEB_EXTENSIONS
  185. protected virtual void ProcessRequest (HttpContext context)
  186. #else
  187. [MonoTODO ("Substitution not implemented")]
  188. void System.Web.IHttpHandler.ProcessRequest (HttpContext context)
  189. #endif
  190. {
  191. string resourceName;
  192. string asmName;
  193. Assembly assembly;
  194. DecryptAssemblyResource (context.Request.QueryString ["d"], out asmName, out resourceName);
  195. if (resourceName == null)
  196. throw new HttpException (404, "No resource name given");
  197. if (asmName == null || asmName == "s")
  198. assembly = currAsm;
  199. else
  200. assembly = Assembly.Load (asmName);
  201. WebResourceAttribute wra = null;
  202. WebResourceAttribute [] attrs = (WebResourceAttribute []) assembly.GetCustomAttributes (typeof (WebResourceAttribute), false);
  203. for (int i = 0; i < attrs.Length; i++) {
  204. if (attrs [i].WebResource == resourceName) {
  205. wra = attrs [i];
  206. break;
  207. }
  208. }
  209. #if SYSTEM_WEB_EXTENSIONS
  210. if (wra == null && resourceName.Length > 9 && resourceName.EndsWith (".debug.js", StringComparison.OrdinalIgnoreCase)) {
  211. resourceName = String.Concat (resourceName.Substring (0, resourceName.Length - 9), ".js");
  212. for (int i = 0; i < attrs.Length; i++) {
  213. if (attrs [i].WebResource == resourceName) {
  214. wra = attrs [i];
  215. break;
  216. }
  217. }
  218. }
  219. #endif
  220. if (wra == null)
  221. throw new HttpException (404, string.Format ("Resource {0} not found", resourceName));
  222. context.Response.ContentType = wra.ContentType;
  223. /* tell the client they can cache resources for 1 year */
  224. context.Response.ExpiresAbsolute = DateTime.Now.AddYears (1);
  225. context.Response.CacheControl = "private";
  226. Stream s = assembly.GetManifestResourceStream (resourceName);
  227. if (s == null)
  228. throw new HttpException (404, string.Format ("Resource {0} not found", resourceName));
  229. if (wra.PerformSubstitution) {
  230. StreamReader r = new StreamReader (s);
  231. TextWriter w = context.Response.Output;
  232. new PerformSubstitutionHelper (assembly).PerformSubstitution (r, w);
  233. }
  234. else {
  235. byte [] buf = new byte [1024];
  236. Stream output = context.Response.OutputStream;
  237. int c;
  238. do {
  239. c = s.Read (buf, 0, 1024);
  240. output.Write (buf, 0, c);
  241. } while (c > 0);
  242. }
  243. #if SYSTEM_WEB_EXTENSIONS
  244. TextWriter writer = context.Response.Output;
  245. foreach (ScriptResourceAttribute sra in assembly.GetCustomAttributes (typeof (ScriptResourceAttribute), false)) {
  246. if (sra.ScriptName == resourceName) {
  247. string scriptResourceName = sra.ScriptResourceName;
  248. ResourceSet rset = null;
  249. try {
  250. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  251. }
  252. catch (MissingManifestResourceException) {
  253. #if TARGET_JVM // GetResourceSet does not throw MissingManifestResourceException if ressource is not exists
  254. }
  255. if (rset == null) {
  256. #endif
  257. if (scriptResourceName.EndsWith (".resources")) {
  258. scriptResourceName = scriptResourceName.Substring (0, scriptResourceName.Length - 10);
  259. rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
  260. }
  261. #if !TARGET_JVM
  262. else
  263. throw;
  264. #endif
  265. }
  266. if (rset == null)
  267. break;
  268. writer.WriteLine ();
  269. writer.Write ("{0}={{", sra.TypeName);
  270. bool first = true;
  271. foreach (DictionaryEntry entry in rset) {
  272. string value = entry.Value as string;
  273. if (value != null) {
  274. if (first)
  275. first = false;
  276. else
  277. writer.Write (',');
  278. writer.WriteLine ();
  279. writer.Write ("{0}:{1}", GetScriptStringLiteral ((string) entry.Key), GetScriptStringLiteral (value));
  280. }
  281. }
  282. writer.WriteLine ();
  283. writer.WriteLine ("};");
  284. break;
  285. }
  286. }
  287. bool notifyScriptLoaded = context.Request.QueryString ["n"] == "t";
  288. if (notifyScriptLoaded) {
  289. writer.WriteLine ();
  290. writer.WriteLine ("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
  291. }
  292. #endif
  293. }
  294. sealed class PerformSubstitutionHelper
  295. {
  296. readonly Assembly _assembly;
  297. static readonly Regex _regex = new Regex (@"\<%=[ ]*WebResource[ ]*\([ ]*""([^""]+)""[ ]*\)[ ]*%\>");
  298. public PerformSubstitutionHelper (Assembly assembly) {
  299. _assembly = assembly;
  300. }
  301. public void PerformSubstitution (TextReader reader, TextWriter writer) {
  302. string line = reader.ReadLine ();
  303. while (line != null) {
  304. if (line.Length > 0 && _regex.IsMatch (line))
  305. line = _regex.Replace (line, new MatchEvaluator (PerformSubstitutionReplace));
  306. writer.WriteLine (line);
  307. line = reader.ReadLine ();
  308. }
  309. }
  310. string PerformSubstitutionReplace (Match m) {
  311. string resourceName = m.Groups [1].Value;
  312. #if SYSTEM_WEB_EXTENSIONS
  313. return ScriptResourceHandler.GetResourceUrl (_assembly, resourceName, false);
  314. #else
  315. return AssemblyResourceLoader.GetResourceUrl (_assembly, resourceName, false);
  316. #endif
  317. }
  318. }
  319. #if !SYSTEM_WEB_EXTENSIONS
  320. bool System.Web.IHttpHandler.IsReusable { get { return true; } }
  321. #endif
  322. }
  323. }