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;
276 CheckIfResourceIsCompositeScript (resourceName, ref includeTimeStamp);
279 lookupKey = resourceNameHash;
281 EmbeddedResource res;
282 if (entry.Resources.TryGetValue (lookupKey, out res) && res != null)
285 #if SYSTEM_WEB_EXTENSIONS
287 resourceNameHash = GetStringHash (kha, resourceName.Substring (0, resourceName.Length - 9) + ".js");
288 lookupKey = resourceNameHash + (notifyScriptLoaded ? "t" : "f");
290 if (entry.Resources.TryGetValue (lookupKey, out res) && res != null)
299 _embeddedResourcesLock.ExitUpgradeableReadLock ();
303 url = CreateResourceUrl (kha, assemblyName, assemblyNameHash, assembly.Location, resourceNameHash, debug, notifyScriptLoaded, includeTimeStamp);
308 static string CreateResourceUrl (KeyedHashAlgorithm kha, string assemblyName, string assemblyNameHash, string assemblyPath, string resourceNameHash, bool debug,
309 bool notifyScriptLoaded, bool includeTimeStamp)
311 string atime = String.Empty;
312 string extra = String.Empty;
313 #if SYSTEM_WEB_EXTENSIONS
314 extra = QueryParamSeparator + "n=" + (notifyScriptLoaded ? "t" : "f");
318 atime = QueryParamSeparator + "t=" + assemblyName.GetHashCode ();
320 if (includeTimeStamp) {
321 if (!String.IsNullOrEmpty (assemblyPath) && File.Exists (assemblyPath))
322 atime = QueryParamSeparator + "t=" + File.GetLastWriteTimeUtc (assemblyPath).Ticks;
324 atime = QueryParamSeparator + "t=" + DateTime.UtcNow.Ticks;
327 string d = HttpUtility.UrlEncode (assemblyNameHash + "_" + resourceNameHash + (debug ? "_t" : "_f"));
328 string href = HandlerFileName + "?d=" + d + atime + extra;
329 HttpContext ctx = HttpContext.Current;
330 HttpRequest req = ctx != null ? ctx.Request : null;
332 string appPath = VirtualPathUtility.AppendTrailingSlash (req.ApplicationPath);
333 href = appPath + href;
339 bool HasIfModifiedSince (HttpRequest request, out DateTime modified)
341 string modif_since = request.Headers ["If-Modified-Since"];
342 if (String.IsNullOrEmpty (modif_since)) {
343 modified = DateTime.MinValue;
348 if (DateTime.TryParseExact (modif_since, "r", null, 0, out modified))
351 modified = DateTime.MinValue;
357 void RespondWithNotModified (HttpContext context)
359 HttpResponse response = context.Response;
361 response.StatusCode = 304;
362 response.ContentType = null;
363 context.ApplicationInstance.CompleteRequest ();
366 void SendEmbeddedResource (HttpContext context, out EmbeddedResource res, out Assembly assembly)
368 HttpRequest request = context.Request;
369 NameValueCollection queryString = request.QueryString;
371 // val is URL-encoded, which means every + has been replaced with ' ', we
372 // need to revert that or the base64 conversion will fail.
373 string d = queryString ["d"];
374 if (!String.IsNullOrEmpty (d))
375 d = d.Replace (' ', '+');
377 AssemblyEmbeddedResources entry;
378 res = DecryptAssemblyResource (d, out entry);
379 WebResourceAttribute wra = res != null ? res.Attribute : null;
381 throw new HttpException (404, "Resource not found");
383 if (entry.AssemblyName == "s")
386 assembly = Assembly.Load (entry.AssemblyName);
389 if (HasIfModifiedSince (request, out modified)) {
390 if (File.GetLastWriteTimeUtc (assembly.Location) <= modified) {
391 RespondWithNotModified (context);
396 HttpResponse response = context.Response;
397 response.ContentType = wra.ContentType;
399 DateTime utcnow = DateTime.UtcNow;
400 response.Headers.Add ("Last-Modified", utcnow.ToString ("r"));
401 response.ExpiresAbsolute = utcnow.AddYears (1);
402 response.CacheControl = "public";
404 Stream s = assembly.GetManifestResourceStream (res.Name);
406 throw new HttpException (404, "Resource " + res.Name + " not found");
408 if (wra.PerformSubstitution) {
409 using (StreamReader r = new StreamReader (s)) {
410 TextWriter w = response.Output;
411 new PerformSubstitutionHelper (assembly).PerformSubstitution (r, w);
413 } else if (response.OutputStream is HttpResponseStream) {
414 UnmanagedMemoryStream st = (UnmanagedMemoryStream) s;
415 HttpResponseStream hstream = (HttpResponseStream) response.OutputStream;
417 hstream.WritePtr (new IntPtr (st.PositionPointer), (int) st.Length);
420 byte [] buf = new byte [1024];
421 Stream output = response.OutputStream;
424 c = s.Read (buf, 0, 1024);
425 output.Write (buf, 0, c);
430 #if !SYSTEM_WEB_EXTENSIONS
431 void System.Web.IHttpHandler.ProcessRequest (HttpContext context)
433 EmbeddedResource res;
436 SendEmbeddedResource (context, out res, out assembly);
439 sealed class PerformSubstitutionHelper
441 readonly Assembly _assembly;
442 static readonly Regex _regex = new Regex (@"\<%=[ ]*WebResource[ ]*\([ ]*""([^""]+)""[ ]*\)[ ]*%\>");
444 public PerformSubstitutionHelper (Assembly assembly) {
445 _assembly = assembly;
448 public void PerformSubstitution (TextReader reader, TextWriter writer) {
449 string line = reader.ReadLine ();
450 while (line != null) {
451 if (line.Length > 0 && _regex.IsMatch (line))
452 line = _regex.Replace (line, new MatchEvaluator (PerformSubstitutionReplace));
453 writer.WriteLine (line);
454 line = reader.ReadLine ();
458 string PerformSubstitutionReplace (Match m) {
459 string resourceName = m.Groups [1].Value;
460 #if SYSTEM_WEB_EXTENSIONS
461 return ScriptResourceHandler.GetResourceUrl (_assembly, resourceName, false);
463 return AssemblyResourceLoader.GetResourceUrl (_assembly, resourceName, false);
468 #if !SYSTEM_WEB_EXTENSIONS
469 bool System.Web.IHttpHandler.IsReusable { get { return true; } }
471 sealed class EmbeddedResource
475 public WebResourceAttribute Attribute;
478 sealed class AssemblyEmbeddedResources
480 public string AssemblyName = String.Empty;
481 public Dictionary <string, EmbeddedResource> Resources = new Dictionary <string, EmbeddedResource> (StringComparer.Ordinal);