2 // System.Web.Handlers.AssemblyResourceLoader
5 // Ben Maurer (bmaurer@users.sourceforge.net)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Globalization;
33 using System.Reflection;
35 using System.Resources;
36 using System.Collections;
37 using System.Security.Cryptography;
39 using System.Text.RegularExpressions;
40 using System.Web.Configuration;
42 namespace System.Web.Handlers {
43 #if SYSTEM_WEB_EXTENSIONS
44 partial class ScriptResourceHandler
46 const string HandlerFileName = "ScriptResource.axd";
47 static Assembly currAsm = typeof (ScriptResourceHandler).Assembly;
52 internal // since this is in the .config file, we need to support it, since we dont have versoned support.
54 class AssemblyResourceLoader : IHttpHandler {
55 const string HandlerFileName = "WebResource.axd";
56 static Assembly currAsm = typeof (AssemblyResourceLoader).Assembly;
58 const char QueryParamSeparator = '&';
60 static readonly Hashtable _embeddedResources = Hashtable.Synchronized (new Hashtable ());
61 #if SYSTEM_WEB_EXTENSIONS
62 static ScriptResourceHandler () {
63 MachineKeySectionUtils.AutoGenKeys ();
67 static void InitEmbeddedResourcesUrls (Assembly assembly, Hashtable hashtable)
69 WebResourceAttribute [] attrs = (WebResourceAttribute []) assembly.GetCustomAttributes (typeof (WebResourceAttribute), false);
70 for (int i = 0; i < attrs.Length; i++) {
71 string resourceName = attrs [i].WebResource;
72 if (resourceName != null && resourceName.Length > 0) {
73 #if SYSTEM_WEB_EXTENSIONS
74 hashtable.Add (new ResourceKey (resourceName, false), CreateResourceUrl (assembly, resourceName, false));
75 hashtable.Add (new ResourceKey (resourceName, true), CreateResourceUrl (assembly, resourceName, true));
77 hashtable.Add (resourceName, CreateResourceUrl (assembly, resourceName, false));
83 #if !SYSTEM_WEB_EXTENSIONS
84 internal static string GetResourceUrl (Type type, string resourceName)
86 return GetResourceUrl (type.Assembly, resourceName, false);
90 static string GetHexString (byte [] bytes)
92 const int letterPart = 55;
93 const int numberPart = 48;
94 char [] result = new char [bytes.Length * 2];
95 for (int i = 0; i < bytes.Length; i++) {
96 int tmp = (int) bytes [i];
97 int second = tmp & 15;
98 int first = (tmp >> 4) & 15;
99 result [(i * 2)] = (char) (first > 9 ? letterPart + first : numberPart + first);
100 result [(i * 2) + 1] = (char) (second > 9 ? letterPart + second : numberPart + second);
102 return new string (result);
105 static byte[] GetEncryptionKey ()
108 return MachineKeySectionUtils.DecryptionKey192Bits ();
110 MachineKeyConfig config = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig;
111 return config.DecryptionKey192Bits;
115 static byte[] GetBytes (string val)
118 return MachineKeySectionUtils.GetBytes (val, val.Length);
120 return MachineKeyConfig.GetBytes (val, val.Length);
124 static byte [] init_vector = { 0xD, 0xE, 0xA, 0xD, 0xB, 0xE, 0xE, 0xF };
126 static string EncryptAssemblyResource (string asmName, string resName)
128 byte[] key = GetEncryptionKey ();
129 byte[] bytes = Encoding.UTF8.GetBytes (String.Concat (asmName, ";", resName));
132 ICryptoTransform encryptor = TripleDES.Create ().CreateEncryptor (key, init_vector);
133 result = GetHexString (encryptor.TransformFinalBlock (bytes, 0, bytes.Length));
136 return String.Concat ("d=", result.ToLower (CultureInfo.InvariantCulture));
139 static void DecryptAssemblyResource (string val, out string asmName, out string resName)
141 byte[] key = GetEncryptionKey ();
142 byte[] bytes = GetBytes (val);
148 ICryptoTransform decryptor = TripleDES.Create ().CreateDecryptor (key, init_vector);
149 result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
152 string data = Encoding.UTF8.GetString (result);
155 string[] parts = data.Split (';');
156 if (parts.Length != 2)
163 internal static string GetResourceUrl (Assembly assembly, string resourceName, bool notifyScriptLoaded)
165 Hashtable hashtable = (Hashtable)_embeddedResources [assembly];
166 if (hashtable == null) {
167 hashtable = new Hashtable ();
168 InitEmbeddedResourcesUrls (assembly, hashtable);
169 _embeddedResources [assembly] = hashtable;
171 #if SYSTEM_WEB_EXTENSIONS
172 string url = (string) hashtable [new ResourceKey (resourceName, notifyScriptLoaded)];
174 string url = (string) hashtable [resourceName];
177 url = CreateResourceUrl (assembly, resourceName, notifyScriptLoaded);
181 static string CreateResourceUrl (Assembly assembly, string resourceName, bool notifyScriptLoaded)
184 string aname = assembly == currAsm ? "s" : assembly.GetName ().FullName;
185 string apath = assembly.Location;
186 string atime = String.Empty;
187 string extra = String.Empty;
188 #if SYSTEM_WEB_EXTENSIONS
189 extra = String.Concat (QueryParamSeparator, "n=", notifyScriptLoaded ? "t" : "f");
193 atime = String.Format ("{0}t={1}", QueryParamSeparator, assembly.GetHashCode ());
195 if (apath != String.Empty)
196 atime = String.Concat (QueryParamSeparator, "t=", File.GetLastWriteTimeUtc (apath).Ticks);
198 string href = HandlerFileName + "?" + EncryptAssemblyResource (aname, resourceName) + atime + extra;
200 HttpContext ctx = HttpContext.Current;
201 if (ctx != null && ctx.Request != null) {
202 string appPath = VirtualPathUtility.AppendTrailingSlash (ctx.Request.ApplicationPath);
203 href = appPath + href;
210 #if SYSTEM_WEB_EXTENSIONS
211 protected virtual void ProcessRequest (HttpContext context)
213 [MonoTODO ("Substitution not implemented")]
214 void System.Web.IHttpHandler.ProcessRequest (HttpContext context)
221 DecryptAssemblyResource (context.Request.QueryString ["d"], out asmName, out resourceName);
222 if (resourceName == null)
223 throw new HttpException (404, "No resource name given");
225 if (asmName == null || asmName == "s")
228 assembly = Assembly.Load (asmName);
230 WebResourceAttribute wra = null;
231 WebResourceAttribute [] attrs = (WebResourceAttribute []) assembly.GetCustomAttributes (typeof (WebResourceAttribute), false);
232 for (int i = 0; i < attrs.Length; i++) {
233 if (attrs [i].WebResource == resourceName) {
238 #if SYSTEM_WEB_EXTENSIONS
239 if (wra == null && resourceName.Length > 9 && resourceName.EndsWith (".debug.js", StringComparison.OrdinalIgnoreCase)) {
240 resourceName = String.Concat (resourceName.Substring (0, resourceName.Length - 9), ".js");
241 for (int i = 0; i < attrs.Length; i++) {
242 if (attrs [i].WebResource == resourceName) {
250 throw new HttpException (404, String.Concat ("Resource ", resourceName, " not found"));
252 context.Response.ContentType = wra.ContentType;
254 /* tell the client they can cache resources for 1 year */
255 context.Response.ExpiresAbsolute = DateTime.Now.AddYears (1);
256 context.Response.CacheControl = "private";
258 Stream s = assembly.GetManifestResourceStream (resourceName);
260 throw new HttpException (404, String.Concat ("Resource ", resourceName, " not found"));
262 if (wra.PerformSubstitution) {
263 StreamReader r = new StreamReader (s);
264 TextWriter w = context.Response.Output;
265 new PerformSubstitutionHelper (assembly).PerformSubstitution (r, w);
268 byte [] buf = new byte [1024];
269 Stream output = context.Response.OutputStream;
272 c = s.Read (buf, 0, 1024);
273 output.Write (buf, 0, c);
276 #if SYSTEM_WEB_EXTENSIONS
277 TextWriter writer = context.Response.Output;
278 foreach (ScriptResourceAttribute sra in assembly.GetCustomAttributes (typeof (ScriptResourceAttribute), false)) {
279 if (sra.ScriptName == resourceName) {
280 string scriptResourceName = sra.ScriptResourceName;
281 ResourceSet rset = null;
283 rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
285 catch (MissingManifestResourceException) {
286 #if TARGET_JVM // GetResourceSet does not throw MissingManifestResourceException if ressource is not exists
290 if (scriptResourceName.EndsWith (".resources")) {
291 scriptResourceName = scriptResourceName.Substring (0, scriptResourceName.Length - 10);
292 rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
302 string ns = sra.TypeName;
303 int indx = ns.LastIndexOf ('.');
305 writer.WriteLine ("Type.registerNamespace('" + ns.Substring (0, indx) + "')");
306 writer.Write ("{0}={{", sra.TypeName);
308 foreach (DictionaryEntry entry in rset) {
309 string value = entry.Value as string;
316 writer.Write ("{0}:{1}", GetScriptStringLiteral ((string) entry.Key), GetScriptStringLiteral (value));
320 writer.WriteLine ("};");
325 bool notifyScriptLoaded = context.Request.QueryString ["n"] == "t";
326 if (notifyScriptLoaded) {
328 writer.WriteLine ("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
333 sealed class PerformSubstitutionHelper
335 readonly Assembly _assembly;
336 static readonly Regex _regex = new Regex (@"\<%=[ ]*WebResource[ ]*\([ ]*""([^""]+)""[ ]*\)[ ]*%\>");
338 public PerformSubstitutionHelper (Assembly assembly) {
339 _assembly = assembly;
342 public void PerformSubstitution (TextReader reader, TextWriter writer) {
343 string line = reader.ReadLine ();
344 while (line != null) {
345 if (line.Length > 0 && _regex.IsMatch (line))
346 line = _regex.Replace (line, new MatchEvaluator (PerformSubstitutionReplace));
347 writer.WriteLine (line);
348 line = reader.ReadLine ();
352 string PerformSubstitutionReplace (Match m) {
353 string resourceName = m.Groups [1].Value;
354 #if SYSTEM_WEB_EXTENSIONS
355 return ScriptResourceHandler.GetResourceUrl (_assembly, resourceName, false);
357 return AssemblyResourceLoader.GetResourceUrl (_assembly, resourceName, false);
362 #if !SYSTEM_WEB_EXTENSIONS
363 bool System.Web.IHttpHandler.IsReusable { get { return true; } }