AssemblyResourceLoader.cs 11 KB

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