2 // System.Web.Handlers.AssemblyResourceLoader
5 // Ben Maurer (bmaurer@users.sourceforge.net)
6 // Marek Habersack <grendel@twistedcode.net>
9 // (C) 2010 Novell, Inc (http://novell.com/)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Globalization;
34 using System.Reflection;
36 using System.Resources;
37 using System.Collections;
38 using System.Collections.Generic;
39 using System.Collections.Specialized;
40 using System.Security.Cryptography;
42 using System.Text.RegularExpressions;
43 using System.Threading;
44 using System.Web.Configuration;
45 using System.Web.Util;
47 namespace System.Web.Handlers
49 #if SYSTEM_WEB_EXTENSIONS
50 partial class ScriptResourceHandler
52 const string HandlerFileName = "ScriptResource.axd";
53 static Assembly currAsm = typeof (ScriptResourceHandler).Assembly;
55 public sealed class AssemblyResourceLoader : IHttpHandler
57 const string HandlerFileName = "WebResource.axd";
58 static Assembly currAsm = typeof (AssemblyResourceLoader).Assembly;
60 const char QueryParamSeparator = '&';
62 static readonly Dictionary <string, AssemblyEmbeddedResources> _embeddedResources = new Dictionary <string, AssemblyEmbeddedResources> (StringComparer.Ordinal);
63 static readonly ReaderWriterLockSlim _embeddedResourcesLock = new ReaderWriterLockSlim ();
64 static readonly ReaderWriterLockSlim _stringHashCacheLock = new ReaderWriterLockSlim ();
65 static readonly Dictionary <string, string> stringHashCache = new Dictionary <string, string> (StringComparer.Ordinal);
68 static KeyedHashAlgorithm hashAlg;
69 static bool canReuseHashAlg = true;
71 static KeyedHashAlgorithm ReusableHashAlgorithm {
76 if (hashAlg == null) {
77 MachineKeySection mks = MachineKeySection.Config;
78 hashAlg = MachineKeySectionUtils.GetValidationAlgorithm (mks);
79 if (!hashAlg.CanReuseTransform) {
80 canReuseHashAlg = false;
86 hashAlg.Initialize ();
92 static string GetStringHash (KeyedHashAlgorithm kha, string str)
94 if (String.IsNullOrEmpty (str))
99 _stringHashCacheLock.EnterUpgradeableReadLock ();
100 if (stringHashCache.TryGetValue (str, out result))
104 _stringHashCacheLock.EnterWriteLock ();
105 if (stringHashCache.TryGetValue (str, out result))
108 result = Convert.ToBase64String (kha.ComputeHash (Encoding.UTF8.GetBytes (str)));
109 stringHashCache.Add (str, result);
111 _stringHashCacheLock.ExitWriteLock ();
114 _stringHashCacheLock.ExitUpgradeableReadLock ();
120 static void InitEmbeddedResourcesUrls (KeyedHashAlgorithm kha, Assembly assembly, string assemblyName, string assemblyHash, AssemblyEmbeddedResources entry)
122 WebResourceAttribute [] attrs = (WebResourceAttribute []) assembly.GetCustomAttributes (typeof (WebResourceAttribute), false);
123 WebResourceAttribute attr;
124 string apath = assembly.Location;
125 for (int i = 0; i < attrs.Length; i++) {
127 string resourceName = attr.WebResource;
128 if (!String.IsNullOrEmpty (resourceName)) {
129 string resourceNameHash = GetStringHash (kha, resourceName);
130 #if SYSTEM_WEB_EXTENSIONS
131 bool debug = resourceName.EndsWith (".debug.js", StringComparison.OrdinalIgnoreCase);
132 string dbgTail = debug ? "d" : String.Empty;
133 string rkNoNotify = resourceNameHash + "f" + dbgTail;
134 string rkNotify = resourceNameHash + "t" + dbgTail;
136 if (!entry.Resources.ContainsKey (rkNoNotify)) {
137 var er = new EmbeddedResource () {
140 Url = CreateResourceUrl (kha, assemblyName, assemblyHash, apath, rkNoNotify, debug, false, true)
143 entry.Resources.Add (rkNoNotify, er);
146 if (!entry.Resources.ContainsKey (rkNotify)) {
147 var er = new EmbeddedResource () {
150 Url = CreateResourceUrl (kha, assemblyName, assemblyHash, apath, rkNotify, debug, true, true)
153 entry.Resources.Add (rkNotify, er);
156 if (!entry.Resources.ContainsKey (resourceNameHash)) {
157 var er = new EmbeddedResource () {
160 Url = CreateResourceUrl (kha, assemblyName, assemblyHash, apath, resourceNameHash, false, false, true)
162 entry.Resources.Add (resourceNameHash, er);
169 #if !SYSTEM_WEB_EXTENSIONS
170 internal static string GetResourceUrl (Type type, string resourceName)
172 return GetResourceUrl (type.Assembly, resourceName, false);
175 static EmbeddedResource DecryptAssemblyResource (string val, out AssemblyEmbeddedResources entry)
179 string[] parts = val.Split ('_');
180 if (parts.Length != 3)
183 string asmNameHash = parts [0];
184 string resNameHash = parts [1];
186 _embeddedResourcesLock.EnterReadLock ();
187 if (!_embeddedResources.TryGetValue (asmNameHash, out entry) || entry == null)
190 EmbeddedResource res;
191 if (!entry.Resources.TryGetValue (resNameHash, out res) || res == null) {
192 #if SYSTEM_WEB_EXTENSIONS
193 bool debug = parts [2] == "t";
197 if (!entry.Resources.TryGetValue (resNameHash.Substring (0, resNameHash.Length - 1), out res))
206 _embeddedResourcesLock.ExitReadLock ();
210 static void GetAssemblyNameAndHashes (KeyedHashAlgorithm kha, Assembly assembly, string resourceName, out string assemblyName, out string assemblyNameHash, out string resourceNameHash)
212 assemblyName = assembly == currAsm ? "s" : assembly.GetName ().FullName;
213 assemblyNameHash = GetStringHash (kha, assemblyName);
214 resourceNameHash = GetStringHash (kha, resourceName);
217 // MUST be called with the _embeddedResourcesLock taken in the upgradeable read lock mode
218 static AssemblyEmbeddedResources GetAssemblyEmbeddedResource (KeyedHashAlgorithm kha, Assembly assembly, string assemblyNameHash, string assemblyName)
220 AssemblyEmbeddedResources entry;
222 if (!_embeddedResources.TryGetValue (assemblyNameHash, out entry) || entry == null) {
224 _embeddedResourcesLock.EnterWriteLock ();
225 entry = new AssemblyEmbeddedResources () {
226 AssemblyName = assemblyName
228 InitEmbeddedResourcesUrls (kha, assembly, assemblyName, assemblyNameHash, entry);
229 _embeddedResources.Add (assemblyNameHash, entry);
231 _embeddedResourcesLock.ExitWriteLock ();
238 internal static string GetResourceUrl (Assembly assembly, string resourceName, bool notifyScriptLoaded)
240 if (assembly == null)
243 KeyedHashAlgorithm kha = ReusableHashAlgorithm;
245 return GetResourceUrl (kha, assembly, resourceName, notifyScriptLoaded);
247 MachineKeySection mks = MachineKeySection.Config;
248 using (kha = MachineKeySectionUtils.GetValidationAlgorithm (mks)) {
249 kha.Key = MachineKeySectionUtils.GetValidationKey (mks);
250 return GetResourceUrl (kha, assembly, resourceName, notifyScriptLoaded);
255 static string GetResourceUrl (KeyedHashAlgorithm kha, Assembly assembly, string resourceName, bool notifyScriptLoaded)
258 string assemblyNameHash;
259 string resourceNameHash;
261 GetAssemblyNameAndHashes (kha, assembly, resourceName, out assemblyName, out assemblyNameHash, out resourceNameHash);
264 AssemblyEmbeddedResources entry;
265 bool includeTimeStamp = true;
268 _embeddedResourcesLock.EnterUpgradeableReadLock ();
269 entry = GetAssemblyEmbeddedResource (kha, assembly, assemblyNameHash, assemblyName);
271 #if SYSTEM_WEB_EXTENSIONS
272 debug = resourceName.EndsWith (".debug.js", StringComparison.OrdinalIgnoreCase);
273 string dbgTail = debug ? "d" : String.Empty;
274 lookupKey = resourceNameHash + (notifyScriptLoaded ? "t" : "f") + dbgTail;
275 CheckIfResourceIsCompositeScript (resourceName, ref includeTimeStamp);
277 lookupKey = resourceNameHash;
279 EmbeddedResource res;
280 if (entry.Resources.TryGetValue (lookupKey, out res) && res != null)
283 #if SYSTEM_WEB_EXTENSIONS
285 resourceNameHash = GetStringHash (kha, resourceName.Substring (0, resourceName.Length - 9) + ".js");
286 lookupKey = resourceNameHash + (notifyScriptLoaded ? "t" : "f");
288 if (entry.Resources.TryGetValue (lookupKey, out res) && res != null)
297 _embeddedResourcesLock.ExitUpgradeableReadLock ();
301 url = CreateResourceUrl (kha, assemblyName, assemblyNameHash, assembly.Location, resourceNameHash, debug, notifyScriptLoaded, includeTimeStamp);
306 static string CreateResourceUrl (KeyedHashAlgorithm kha, string assemblyName, string assemblyNameHash, string assemblyPath, string resourceNameHash, bool debug,
307 bool notifyScriptLoaded, bool includeTimeStamp)
309 string atime = String.Empty;
310 string extra = String.Empty;
311 #if SYSTEM_WEB_EXTENSIONS
312 extra = QueryParamSeparator + "n=" + (notifyScriptLoaded ? "t" : "f");
315 if (includeTimeStamp) {
316 if (!String.IsNullOrEmpty (assemblyPath) && File.Exists (assemblyPath))
317 atime = QueryParamSeparator + "t=" + File.GetLastWriteTimeUtc (assemblyPath).Ticks;
319 atime = QueryParamSeparator + "t=" + DateTime.UtcNow.Ticks;
321 string d = HttpUtility.UrlEncode (assemblyNameHash + "_" + resourceNameHash + (debug ? "_t" : "_f"));
322 string href = HandlerFileName + "?d=" + d + atime + extra;
323 HttpContext ctx = HttpContext.Current;
324 HttpRequest req = ctx != null ? ctx.Request : null;
326 string appPath = VirtualPathUtility.AppendTrailingSlash (req.ApplicationPath);
327 href = appPath + href;
333 bool HasIfModifiedSince (HttpRequest request, out DateTime modified)
335 string modif_since = request.Headers ["If-Modified-Since"];
336 if (String.IsNullOrEmpty (modif_since)) {
337 modified = DateTime.MinValue;
342 if (DateTime.TryParseExact (modif_since, "r", null, 0, out modified))
345 modified = DateTime.MinValue;
351 void RespondWithNotModified (HttpContext context)
353 HttpResponse response = context.Response;
355 response.StatusCode = 304;
356 response.ContentType = null;
357 context.ApplicationInstance.CompleteRequest ();
360 void SendEmbeddedResource (HttpContext context, out EmbeddedResource res, out Assembly assembly)
362 HttpRequest request = context.Request;
363 NameValueCollection queryString = request.QueryString;
365 // val is URL-encoded, which means every + has been replaced with ' ', we
366 // need to revert that or the base64 conversion will fail.
367 string d = queryString ["d"];
368 if (!String.IsNullOrEmpty (d))
369 d = d.Replace (' ', '+');
371 AssemblyEmbeddedResources entry;
372 res = DecryptAssemblyResource (d, out entry);
373 WebResourceAttribute wra = res != null ? res.Attribute : null;
375 throw new HttpException (404, "Resource not found");
377 if (entry.AssemblyName == "s")
380 assembly = Assembly.Load (entry.AssemblyName);
383 if (HasIfModifiedSince (request, out modified)) {
384 if (File.GetLastWriteTimeUtc (assembly.Location) <= modified) {
385 RespondWithNotModified (context);
390 HttpResponse response = context.Response;
391 response.ContentType = wra.ContentType;
393 DateTime utcnow = DateTime.UtcNow;
394 response.Headers.Add ("Last-Modified", utcnow.ToString ("r"));
395 response.ExpiresAbsolute = utcnow.AddYears (1);
396 response.CacheControl = "public";
398 Stream s = assembly.GetManifestResourceStream (res.Name);
400 throw new HttpException (404, "Resource " + res.Name + " not found");
402 if (wra.PerformSubstitution) {
403 using (StreamReader r = new StreamReader (s)) {
404 TextWriter w = response.Output;
405 new PerformSubstitutionHelper (assembly).PerformSubstitution (r, w);
407 } else if (response.OutputStream is HttpResponseStream) {
408 UnmanagedMemoryStream st = (UnmanagedMemoryStream) s;
409 HttpResponseStream hstream = (HttpResponseStream) response.OutputStream;
411 hstream.WritePtr (new IntPtr (st.PositionPointer), (int) st.Length);
414 byte [] buf = new byte [1024];
415 Stream output = response.OutputStream;
418 c = s.Read (buf, 0, 1024);
419 output.Write (buf, 0, c);
424 #if !SYSTEM_WEB_EXTENSIONS
425 void System.Web.IHttpHandler.ProcessRequest (HttpContext context)
427 EmbeddedResource res;
430 SendEmbeddedResource (context, out res, out assembly);
433 sealed class PerformSubstitutionHelper
435 readonly Assembly _assembly;
436 static readonly Regex _regex = new Regex (@"\<%=[ ]*WebResource[ ]*\([ ]*""([^""]+)""[ ]*\)[ ]*%\>");
438 public PerformSubstitutionHelper (Assembly assembly) {
439 _assembly = assembly;
442 public void PerformSubstitution (TextReader reader, TextWriter writer) {
443 string line = reader.ReadLine ();
444 while (line != null) {
445 if (line.Length > 0 && _regex.IsMatch (line))
446 line = _regex.Replace (line, new MatchEvaluator (PerformSubstitutionReplace));
447 writer.WriteLine (line);
448 line = reader.ReadLine ();
452 string PerformSubstitutionReplace (Match m) {
453 string resourceName = m.Groups [1].Value;
454 #if SYSTEM_WEB_EXTENSIONS
455 return ScriptResourceHandler.GetResourceUrl (_assembly, resourceName, false);
457 return AssemblyResourceLoader.GetResourceUrl (_assembly, resourceName, false);
462 #if !SYSTEM_WEB_EXTENSIONS
463 bool System.Web.IHttpHandler.IsReusable { get { return true; } }
465 sealed class EmbeddedResource
469 public WebResourceAttribute Attribute;
472 sealed class AssemblyEmbeddedResources
474 public string AssemblyName = String.Empty;
475 public Dictionary <string, EmbeddedResource> Resources = new Dictionary <string, EmbeddedResource> (StringComparer.Ordinal);