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";
51 internal // since this is in the .config file, we need to support it, since we dont have versoned support.
53 class AssemblyResourceLoader : IHttpHandler {
54 const string HandlerFileName = "WebResource.axd";
56 const char QueryParamSeparator = '&';
58 static readonly Hashtable _embeddedResources;
59 #if SYSTEM_WEB_EXTENSIONS
60 static ScriptResourceHandler()
62 static AssemblyResourceLoader()
65 _embeddedResources = new Hashtable ();
66 InitEmbeddedResourcesUrls ();
69 static void InitEmbeddedResourcesUrls ()
71 Assembly currAsm = typeof (AssemblyResourceLoader).Assembly;
72 WebResourceAttribute [] attrs = (WebResourceAttribute []) currAsm.GetCustomAttributes (typeof (WebResourceAttribute), false);
73 for (int i = 0; i < attrs.Length; i++) {
74 string resourceName = attrs [i].WebResource;
75 if (resourceName != null && resourceName.Length > 0)
76 _embeddedResources.Add (resourceName, GetResourceUrl (currAsm, resourceName, false));
80 internal static string GetResourceUrl (Type type, string resourceName)
83 Assembly assembly = type.Assembly;
85 if (assembly == typeof (AssemblyResourceLoader).Assembly)
86 url = (string) _embeddedResources [resourceName];
88 return (url != null) ? url : GetResourceUrl (assembly, resourceName, false);
91 static string GetHexString (byte [] bytes)
93 const int letterPart = 55;
94 const int numberPart = 48;
95 char [] result = new char [bytes.Length * 2];
96 for (int i = 0; i < bytes.Length; i++) {
97 int tmp = (int) bytes [i];
98 int second = tmp & 15;
99 int first = (tmp >> 4) & 15;
100 result [(i * 2)] = (char) (first > 9 ? letterPart + first : numberPart + first);
101 result [(i * 2) + 1] = (char) (second > 9 ? letterPart + second : numberPart + second);
103 return new string (result);
106 static byte[] GetEncryptionKey ()
109 return MachineKeySectionUtils.DecryptionKey192Bits ();
111 MachineKeyConfig config = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig;
112 return config.DecryptionKey192Bits;
116 static byte[] GetBytes (string val)
119 return MachineKeySectionUtils.GetBytes (val, val.Length);
121 return MachineKeyConfig.GetBytes (val, val.Length);
125 static byte [] init_vector = { 0xD, 0xE, 0xA, 0xD, 0xB, 0xE, 0xE, 0xF };
127 static string EncryptAssemblyResource (string asmName, string resName)
129 byte[] key = GetEncryptionKey ();
130 byte[] bytes = Encoding.UTF8.GetBytes (String.Format ("{0};{1}", asmName, resName));
133 ICryptoTransform encryptor = TripleDES.Create ().CreateEncryptor (key, init_vector);
134 result = GetHexString (encryptor.TransformFinalBlock (bytes, 0, bytes.Length));
137 return String.Format ("d={0}", result.ToLower (CultureInfo.InvariantCulture));
140 static void DecryptAssemblyResource (string val, out string asmName, out string resName)
142 byte[] key = GetEncryptionKey ();
143 byte[] bytes = GetBytes (val);
149 ICryptoTransform decryptor = TripleDES.Create ().CreateDecryptor (key, init_vector);
150 result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
153 string data = Encoding.UTF8.GetString (result);
156 string[] parts = data.Split (';');
157 if (parts.Length != 2)
164 internal static string GetResourceUrl (Assembly assembly, string resourceName, bool notifyScriptLoaded)
166 string aname = assembly == typeof (AssemblyResourceLoader).Assembly ? "s" : assembly.GetName ().FullName;
167 string apath = assembly.Location;
168 string atime = String.Empty;
169 string extra = String.Empty;
170 #if SYSTEM_WEB_EXTENSIONS
171 extra = String.Format ("{0}n={1}", QueryParamSeparator, notifyScriptLoaded ? "t" : "f");
175 atime = String.Format ("{0}t={1}", QueryParamSeparator, assembly.GetHashCode ());
177 if (apath != String.Empty)
178 atime = String.Format ("{0}t={1}", QueryParamSeparator, File.GetLastWriteTimeUtc (apath).Ticks);
180 string href = String.Format ("{0}?{1}{2}{3}", HandlerFileName,
181 EncryptAssemblyResource (aname, resourceName), atime, extra);
183 HttpContext ctx = HttpContext.Current;
184 if (ctx != null && ctx.Request != null) {
185 string appPath = VirtualPathUtility.AppendTrailingSlash (ctx.Request.ApplicationPath);
186 href = appPath + href;
193 #if SYSTEM_WEB_EXTENSIONS
194 protected virtual void ProcessRequest (HttpContext context)
196 [MonoTODO ("Substitution not implemented")]
197 void System.Web.IHttpHandler.ProcessRequest (HttpContext context)
204 DecryptAssemblyResource (context.Request.QueryString ["d"], out asmName, out resourceName);
205 if (resourceName == null)
206 throw new HttpException (404, "No resource name given");
208 if (asmName == null || asmName == "s")
209 assembly = typeof (AssemblyResourceLoader).Assembly;
211 assembly = Assembly.Load (asmName);
213 WebResourceAttribute wra = null;
214 WebResourceAttribute [] attrs = (WebResourceAttribute []) assembly.GetCustomAttributes (typeof (WebResourceAttribute), false);
215 for (int i = 0; i < attrs.Length; i++) {
216 if (attrs [i].WebResource == resourceName) {
221 #if SYSTEM_WEB_EXTENSIONS
222 if (wra == null && resourceName.Length > 9 && resourceName.EndsWith (".debug.js", StringComparison.OrdinalIgnoreCase)) {
223 resourceName = String.Concat (resourceName.Substring (0, resourceName.Length - 9), ".js");
224 for (int i = 0; i < attrs.Length; i++) {
225 if (attrs [i].WebResource == resourceName) {
233 throw new HttpException (404, string.Format ("Resource {0} not found", resourceName));
235 context.Response.ContentType = wra.ContentType;
237 /* tell the client they can cache resources for 1 year */
238 context.Response.ExpiresAbsolute = DateTime.Now.AddYears (1);
239 context.Response.CacheControl = "private";
241 Stream s = assembly.GetManifestResourceStream (resourceName);
243 throw new HttpException (404, string.Format ("Resource {0} not found", resourceName));
245 if (wra.PerformSubstitution) {
246 StreamReader r = new StreamReader (s);
247 TextWriter w = context.Response.Output;
248 new PerformSubstitutionHelper (assembly).PerformSubstitution (r, w);
251 byte [] buf = new byte [1024];
252 Stream output = context.Response.OutputStream;
255 c = s.Read (buf, 0, 1024);
256 output.Write (buf, 0, c);
259 #if SYSTEM_WEB_EXTENSIONS
260 TextWriter writer = context.Response.Output;
261 foreach (ScriptResourceAttribute sra in assembly.GetCustomAttributes (typeof (ScriptResourceAttribute), false)) {
262 if (sra.ScriptName == resourceName) {
263 string scriptResourceName = sra.ScriptResourceName;
264 ResourceSet rset = null;
266 rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
268 catch (MissingManifestResourceException) {
269 #if TARGET_JVM // GetResourceSet does not throw MissingManifestResourceException if ressource is not exists
273 if (scriptResourceName.EndsWith (".resources")) {
274 scriptResourceName = scriptResourceName.Substring (0, scriptResourceName.Length - 10);
275 rset = new ResourceManager (scriptResourceName, assembly).GetResourceSet (Threading.Thread.CurrentThread.CurrentUICulture, true, true);
285 writer.Write ("{0}={{", sra.TypeName);
287 foreach (DictionaryEntry entry in rset) {
288 string value = entry.Value as string;
295 writer.Write ("{0}:{1}", GetScriptStringLiteral ((string) entry.Key), GetScriptStringLiteral (value));
299 writer.WriteLine ("};");
304 bool notifyScriptLoaded = context.Request.QueryString ["n"] == "t";
305 if (notifyScriptLoaded) {
307 writer.WriteLine ("if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();");
312 sealed class PerformSubstitutionHelper
314 readonly Assembly _assembly;
315 static readonly Regex _regex = new Regex (@"\<%=[ ]*WebResource[ ]*\([ ]*""([^""]+)""[ ]*\)[ ]*%\>");
317 public PerformSubstitutionHelper (Assembly assembly) {
318 _assembly = assembly;
321 public void PerformSubstitution (TextReader reader, TextWriter writer) {
322 string line = reader.ReadLine ();
323 while (line != null) {
324 if (line.Length > 0 && _regex.IsMatch (line))
325 line = _regex.Replace (line, new MatchEvaluator (PerformSubstitutionReplace));
326 writer.WriteLine (line);
327 line = reader.ReadLine ();
331 string PerformSubstitutionReplace (Match m) {
332 string resourceName = m.Groups [1].Value;
333 #if SYSTEM_WEB_EXTENSIONS
334 return ScriptResourceHandler.GetResourceUrl (_assembly, resourceName, false);
336 return AssemblyResourceLoader.GetResourceUrl (_assembly, resourceName, false);
341 #if !SYSTEM_WEB_EXTENSIONS
342 bool System.Web.IHttpHandler.IsReusable { get { return true; } }