AssemblyResourceLoader.cs 13 KB

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