| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752 |
- //
- // System.Web.HttpContext.cs
- //
- // Author:
- // Miguel de Icaza ([email protected])
- // Gonzalo Paniagua Javier ([email protected])
- // Marek Habersack <[email protected]>
- //
- //
- // Copyright (C) 2005-2009 Novell, Inc (http://www.novell.com)
- //
- // Permission is hereby granted, free of charge, to any person obtaining
- // a copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to
- // permit persons to whom the Software is furnished to do so, subject to
- // the following conditions:
- //
- // The above copyright notice and this permission notice shall be
- // included in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- //
- using System.Collections;
- using System.Configuration;
- using System.Globalization;
- using System.Runtime.Remoting.Messaging;
- using System.Security.Permissions;
- using System.Security.Principal;
- using System.Threading;
- using System.Web.Caching;
- using System.Web.Configuration;
- using System.Web.SessionState;
- using System.Web.UI;
- using System.Web.Util;
- using System.Reflection;
- using System.Collections.Generic;
- using System.IO;
- using System.Resources;
- using System.Web.Compilation;
- using System.Web.Profile;
- using CustomErrorMode = System.Web.Configuration.CustomErrorsMode;
- namespace System.Web
- {
- // CAS - no InheritanceDemand here as the class is sealed
- [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
- public sealed partial class HttpContext : IServiceProvider
- {
- internal HttpWorkerRequest WorkerRequest;
- HttpApplication app_instance;
- HttpRequest request;
- HttpResponse response;
- HttpSessionState session_state;
- HttpServerUtility server;
- TraceContext trace_context;
- IHttpHandler handler;
- string error_page;
- bool skip_authorization = false;
- IPrincipal user;
- object errors;
- Hashtable items;
- object config_timeout;
- int timeout_possible;
- DateTime time_stamp = DateTime.UtcNow;
- Timer timer;
- Thread thread;
- bool _isProcessingInclude;
-
- [ThreadStatic]
- static ResourceProviderFactory provider_factory;
- [ThreadStatic]
- static DefaultResourceProviderFactory default_provider_factory;
-
- [ThreadStatic]
- static Dictionary <string, IResourceProvider> resource_providers;
-
- #if TARGET_JVM
- const string app_global_res_key = "HttpContext.app_global_res_key";
- internal static Assembly AppGlobalResourcesAssembly {
- get { return (Assembly) AppDomain.CurrentDomain.GetData (app_global_res_key); }
- set { AppDomain.CurrentDomain.SetData (app_global_res_key, value); }
- }
- #else
- internal static Assembly AppGlobalResourcesAssembly;
- #endif
- ProfileBase profile = null;
- LinkedList<IHttpHandler> handlers;
- static DefaultResourceProviderFactory DefaultProviderFactory {
- get {
- if (default_provider_factory == null)
- default_provider_factory = new DefaultResourceProviderFactory ();
- return default_provider_factory;
- }
- }
-
- public HttpContext (HttpWorkerRequest wr)
- {
- WorkerRequest = wr;
- request = new HttpRequest (WorkerRequest, this);
- response = new HttpResponse (WorkerRequest, this);
- SessionStateBehavior = SessionStateBehavior.Default;
- }
- public HttpContext (HttpRequest request, HttpResponse response)
- {
- this.request = request;
- this.response = response;
- SessionStateBehavior = SessionStateBehavior.Default;
- }
- internal bool IsProcessingInclude {
- get { return _isProcessingInclude; }
- set { _isProcessingInclude = value; }
- }
- public Exception [] AllErrors {
- get {
- if (errors == null)
- return null;
- if (errors is Exception){
- Exception [] all = new Exception [1];
- all [0] = (Exception) errors;
- return all;
- }
- return (Exception []) (((ArrayList) errors).ToArray (typeof (Exception)));
- }
- }
- public HttpApplicationState Application {
- get {
- return HttpApplicationFactory.ApplicationState;
- }
- }
- public HttpApplication ApplicationInstance {
- get {
- return app_instance;
- }
- set {
- app_instance = value;
- }
-
- }
- public Cache Cache {
- get {
- return HttpRuntime.Cache;
- }
- }
- internal Cache InternalCache {
- get {
- return HttpRuntime.InternalCache;
- }
- }
-
- //
- // The "Current" property is set just after we have constructed it with
- // the 'HttpContext (HttpWorkerRequest)' constructor.
- //
- #if !TARGET_JVM // No remoting CallContext support in Grasshopper
- public static HttpContext Current {
- get {
- return (HttpContext) CallContext.GetData ("c");
- }
- set {
- CallContext.SetData ("c", value);
- }
- }
- #endif
- public Exception Error {
- get {
- if (errors == null || (errors is Exception))
- return (Exception) errors;
- return (Exception) (((ArrayList) errors) [0]);
- }
- }
- public IHttpHandler Handler {
- get {
- return handler;
- }
- set {
- handler = value;
- }
- }
- public bool IsCustomErrorEnabled {
- get {
- try {
- return IsCustomErrorEnabledUnsafe;
- }
- catch {
- return false;
- }
- }
- }
- internal bool IsCustomErrorEnabledUnsafe {
- get {
- CustomErrorsSection cfg = (CustomErrorsSection) WebConfigurationManager.GetSection ("system.web/customErrors");
- if (cfg.Mode == CustomErrorMode.On)
- return true;
- return (cfg.Mode == CustomErrorMode.RemoteOnly) && !Request.IsLocal;
- }
- }
- #if !TARGET_JVM
- public bool IsDebuggingEnabled {
- get { return HttpRuntime.IsDebuggingEnabled; }
- }
- #endif
- public IDictionary Items {
- get {
- if (items == null)
- items = new Hashtable ();
- return items;
- }
- }
- public HttpRequest Request {
- get {
- return request;
- }
- }
- public HttpResponse Response {
- get {
- return response;
- }
- }
- public HttpServerUtility Server {
- get {
- if (server == null)
- server = new HttpServerUtility (this);
- return server;
- }
- }
- public HttpSessionState Session {
- get {
- return session_state;
- }
- }
- public bool SkipAuthorization {
- get {
- return skip_authorization;
- }
- [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
- set {
- skip_authorization = value;
- }
- }
- public DateTime Timestamp {
- get {
- return time_stamp.ToLocalTime ();
- }
- }
-
- public TraceContext Trace {
- get {
- if (trace_context == null)
- trace_context = new TraceContext (this);
- return trace_context;
- }
- }
- public IPrincipal User {
- get {
- return user;
- }
- [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
- set {
- user = value;
- }
- }
- internal bool MapRequestHandlerDone {
- get;
- set;
- }
-
- // The two properties below are defined only when the IIS7 integrated mode is used.
- // They are useless under Mono
- public RequestNotification CurrentNotification {
- get { throw new PlatformNotSupportedException ("This property is not supported on Mono."); }
- }
- public bool IsPostNotification {
- get { throw new PlatformNotSupportedException ("This property is not supported on Mono."); }
- }
-
- internal void PushHandler (IHttpHandler handler)
- {
- if (handler == null)
- return;
- if (handlers == null)
- handlers = new LinkedList <IHttpHandler> ();
- handlers.AddLast (handler);
- }
- internal void PopHandler ()
- {
- if (handlers == null || handlers.Count == 0)
- return;
- handlers.RemoveLast ();
- }
-
- IHttpHandler GetCurrentHandler ()
- {
- if (handlers == null || handlers.Count == 0)
- return null;
-
- return handlers.Last.Value;
- }
- IHttpHandler GetPreviousHandler ()
- {
- if (handlers == null || handlers.Count <= 1)
- return null;
- LinkedListNode <IHttpHandler> previous = handlers.Last.Previous;
- if (previous != null)
- return previous.Value;
- return null;
- }
-
- public IHttpHandler CurrentHandler {
- get { return GetCurrentHandler (); }
- }
- public IHttpHandler PreviousHandler {
- get { return GetPreviousHandler (); }
- }
- internal bool ProfileInitialized {
- get { return profile != null; }
- }
- public ProfileBase Profile {
- get {
- if (profile == null) {
- if (Request.IsAuthenticated)
- profile = ProfileBase.Create (User.Identity.Name);
- else
- profile = ProfileBase.Create (Request.AnonymousID, false);
- }
- return profile;
- }
- internal set {
- profile = value;
- }
- }
- public void AddError (Exception errorInfo)
- {
- if (errors == null){
- errors = errorInfo;
- return;
- }
- ArrayList l;
- if (errors is Exception){
- l = new ArrayList ();
- l.Add (errors);
- errors = l;
- } else
- l = (ArrayList) errors;
- l.Add (errorInfo);
- }
- internal void ClearError (Exception e)
- {
- if (errors == e)
- errors = null;
- }
- internal bool HasError (Exception e)
- {
- if (errors == e)
- return true;
- return (errors is ArrayList) ?
- ((ArrayList) errors).Contains (e) : false;
- }
- public void ClearError ()
- {
- errors = null;
- }
- [Obsolete ("use WebConfigurationManager.GetWebApplicationSection")]
- public static object GetAppConfig (string name)
- {
- object o = ConfigurationSettings.GetConfig (name);
- return o;
- }
- [Obsolete ("see GetSection")]
- public object GetConfig (string name)
- {
- return GetSection (name);
- }
- public static object GetGlobalResourceObject (string classKey, string resourceKey)
- {
- return GetGlobalResourceObject (classKey, resourceKey, Thread.CurrentThread.CurrentUICulture);
- }
- static bool EnsureProviderFactory ()
- {
- if (resource_providers == null)
- resource_providers = new Dictionary <string, IResourceProvider> ();
- if (provider_factory != null)
- return true;
-
- GlobalizationSection gs = WebConfigurationManager.GetSection ("system.web/globalization") as GlobalizationSection;
- if (gs == null)
- return false;
- String rsfTypeName = gs.ResourceProviderFactoryType;
- bool usingDefault = false;
- if (String.IsNullOrEmpty (rsfTypeName)) {
- usingDefault = true;
- rsfTypeName = typeof (DefaultResourceProviderFactory).AssemblyQualifiedName;
- }
-
- Type rsfType = HttpApplication.LoadType (rsfTypeName, true);
- ResourceProviderFactory rpf = Activator.CreateInstance (rsfType) as ResourceProviderFactory;
-
- if (rpf == null && usingDefault)
- return false;
- provider_factory = rpf;
- if (usingDefault)
- default_provider_factory = rpf as DefaultResourceProviderFactory;
-
- return true;
- }
-
- internal static IResourceProvider GetResourceProvider (string virtualPath, bool isLocal)
- {
- if (!EnsureProviderFactory ())
- return null;
- // TODO: check if it makes sense to cache the providers and, if yes, maybe
- // we should expire the entries (or just store them in InternalCache?)
- IResourceProvider rp = null;
- if (!resource_providers.TryGetValue (virtualPath, out rp)) {
- if (isLocal) {
- HttpContext ctx = HttpContext.Current;
- HttpRequest req = ctx != null ? ctx.Request : null;
- rp = provider_factory.CreateLocalResourceProvider (virtualPath);
- } else
- rp = provider_factory.CreateGlobalResourceProvider (virtualPath);
-
- if (rp == null) {
- if (isLocal) {
- HttpContext ctx = HttpContext.Current;
- HttpRequest req = ctx != null ? ctx.Request : null;
- rp = DefaultProviderFactory.CreateLocalResourceProvider (virtualPath);
- } else
- rp = DefaultProviderFactory.CreateGlobalResourceProvider (virtualPath);
- if (rp == null)
- return null;
- }
-
- resource_providers.Add (virtualPath, rp);
- }
- return rp;
- }
- static object GetGlobalObjectFromFactory (string classKey, string resourceKey, CultureInfo culture)
- {
- // FIXME: Retention of data
- IResourceProvider rp = GetResourceProvider (classKey, false);
- if (rp == null)
- return null;
-
- return rp.GetObject (resourceKey, culture);
- }
-
- public static object GetGlobalResourceObject (string classKey, string resourceKey, CultureInfo culture)
- {
- return GetGlobalObjectFromFactory ("Resources." + classKey, resourceKey, culture);
- }
- public static object GetLocalResourceObject (string virtualPath, string resourceKey)
- {
- return GetLocalResourceObject (virtualPath, resourceKey, Thread.CurrentThread.CurrentUICulture);
- }
- static object GetLocalObjectFromFactory (string virtualPath, string resourceKey, CultureInfo culture)
- {
- IResourceProvider rp = GetResourceProvider (virtualPath, true);
- if (rp == null)
- return null;
-
- return rp.GetObject (resourceKey, culture);
- }
-
- public static object GetLocalResourceObject (string virtualPath, string resourceKey, CultureInfo culture)
- {
- if (!VirtualPathUtility.IsAbsolute (virtualPath))
- throw new ArgumentException ("The specified virtualPath was not rooted.");
- return GetLocalObjectFromFactory (virtualPath, resourceKey, culture);
- }
- public object GetSection (string name)
- {
- return WebConfigurationManager.GetSection (name);
- }
- object IServiceProvider.GetService (Type service)
- {
- if (service == typeof (HttpWorkerRequest))
- return WorkerRequest;
- //
- // We return everything out of properties in case
- // they are dynamically computed in some form in the future.
- //
- if (service == typeof (HttpApplication))
- return ApplicationInstance;
- if (service == typeof (HttpRequest))
- return Request;
- if (service == typeof (HttpResponse))
- return Response;
- if (service == typeof (HttpSessionState))
- return Session;
- if (service == typeof (HttpApplicationState))
- return Application;
- if (service == typeof (IPrincipal))
- return User;
- if (service == typeof (Cache))
- return Cache;
- if (service == typeof (HttpContext))
- return Current;
- if (service == typeof (IHttpHandler))
- return Handler;
- if (service == typeof (HttpServerUtility))
- return Server;
-
- if (service == typeof (TraceContext))
- return Trace;
-
- return null;
- }
- public void RemapHandler (IHttpHandler handler)
- {
- if (MapRequestHandlerDone)
- throw new InvalidOperationException ("The RemapHandler method was called after the MapRequestHandler event occurred.");
- Handler = handler;
- }
-
- public void RewritePath (string path)
- {
- RewritePath (path, true);
- }
- public void RewritePath (string filePath, string pathInfo, string queryString)
- {
- RewritePath (filePath, pathInfo, queryString, false);
- }
- public void RewritePath (string path, bool rebaseClientPath)
- {
- int qmark = path.IndexOf ('?');
- if (qmark != -1)
- RewritePath (path.Substring (0, qmark), String.Empty, path.Substring (qmark + 1), rebaseClientPath);
- else
- RewritePath (path, null, null, rebaseClientPath);
- }
- public void RewritePath (string filePath, string pathInfo, string queryString, bool setClientFilePath)
- {
- if (filePath == null)
- throw new ArgumentNullException ("filePath");
- if (!VirtualPathUtility.IsValidVirtualPath (filePath))
- throw new HttpException ("'" + HttpUtility.HtmlEncode (filePath) + "' is not a valid virtual path.");
- bool pathRelative = VirtualPathUtility.IsAppRelative (filePath);
- bool pathAbsolute = pathRelative ? false : VirtualPathUtility.IsAbsolute (filePath);
- HttpRequest req = Request;
- if (req == null)
- return;
-
- if (pathRelative || pathAbsolute) {
- if (pathRelative)
- filePath = VirtualPathUtility.ToAbsolute (filePath);
- else
- filePath = filePath;
- } else
- filePath = VirtualPathUtility.AppendTrailingSlash (req.BaseVirtualDir) + filePath;
-
- if (!StrUtils.StartsWith (filePath, HttpRuntime.AppDomainAppVirtualPath))
- throw new HttpException (404, "The virtual path '" + HttpUtility.HtmlEncode (filePath) + "' maps to another application.", filePath);
- req.SetCurrentExePath (filePath);
- req.SetFilePath (filePath);
- if (setClientFilePath)
- req.ClientFilePath = filePath;
-
- // A null pathInfo or queryString is ignored and previous values remain untouched
- if (pathInfo != null)
- req.SetPathInfo (pathInfo);
- if (queryString != null)
- req.QueryStringRaw = queryString;
- }
- #if NET_4_0
- public void SetSessionStateBehavior (SessionStateBehavior sessionStateBehavior)
- {
- SessionStateBehavior = sessionStateBehavior;
- }
- #endif
-
- #region internals
- internal void SetSession (HttpSessionState state)
- {
- session_state = state;
- }
- // URL of a page used for error redirection.
- internal string ErrorPage {
- get {
- return error_page;
- }
- set {
- error_page = value;
- }
- }
- internal TimeSpan ConfigTimeout {
- get {
- if (config_timeout == null) {
- HttpRuntimeSection section = (HttpRuntimeSection)WebConfigurationManager.GetSection ("system.web/httpRuntime");
- config_timeout = section.ExecutionTimeout;
- }
- return (TimeSpan) config_timeout;
- }
- set {
- config_timeout = value;
- #if !TARGET_J2EE
- if (timer != null) {
- TimeSpan remaining = value - (DateTime.UtcNow - time_stamp);
- long remaining_ms = Math.Max ((long)remaining.TotalMilliseconds, 0);
- // See http://msdn2.microsoft.com/en-us/library/7hs7492w.aspx
- if (remaining_ms > 4294967294)
- remaining_ms = 4294967294;
-
- timer.Change (remaining_ms, (long)Timeout.Infinite);
- }
- #endif
- }
- }
- #if NET_4_0
- internal SessionStateBehavior SessionStateBehavior {
- get;
- private set;
- }
- #endif
-
- #if !TARGET_J2EE
- void TimeoutReached(object state) {
- HttpRuntime.QueuePendingRequest (false);
- if (Interlocked.CompareExchange (ref timeout_possible, 0, 0) == 0) {
- timer.Change(2000, 0);
- return;
- }
- StopTimeoutTimer();
-
- thread.Abort (new StepTimeout ());
- }
-
- internal void StartTimeoutTimer() {
- thread = Thread.CurrentThread;
- timer = new Timer (TimeoutReached, null, (int)ConfigTimeout.TotalMilliseconds, Timeout.Infinite);
- }
-
- internal void StopTimeoutTimer() {
- if(timer != null) {
- timer.Dispose ();
- timer = null;
- }
- }
- internal bool TimeoutPossible {
- get { return (Interlocked.CompareExchange (ref timeout_possible, 1, 1) == 1); }
- }
- internal void BeginTimeoutPossible ()
- {
- timeout_possible = 1;
- }
- internal void EndTimeoutPossible ()
- {
- Interlocked.CompareExchange (ref timeout_possible, 0, 1);
- }
- #endif
- #endregion
- }
-
- class StepTimeout
- {
- }
- }
|