private void OnAsyncCompletion(IAsyncResult readAsyncResult) { if (readAsyncResult.CompletedSynchronously) { return; } HttpAsyncResult httpAsyncResult = readAsyncResult.AsyncState as HttpAsyncResult; Exception error = null; try { int bytesRead = _inputStream.EndRead(readAsyncResult); byte[] buffer = _app.EntityBuffer; // loop to prevent recursive calls and potential stack overflow when it completes synchronously while (bytesRead != 0) { readAsyncResult = _inputStream.BeginRead(buffer, 0, buffer.Length, _callback, httpAsyncResult); if (!readAsyncResult.CompletedSynchronously) { return; } bytesRead = _inputStream.EndRead(readAsyncResult); } } catch (Exception e) { error = e; } httpAsyncResult.Complete(false, null, error); }
internal override IAsyncResult BeginExecuteUrl(string url, string method, string childHeaders, bool sendHeaders, bool addUserIndo, IntPtr token, string name, string authType, byte[] entity, AsyncCallback cb, object state) { if (((base._ecb == IntPtr.Zero) || (this._asyncResultOfExecuteUrl != null)) || (sendHeaders && this.HeadersSent())) { throw new InvalidOperationException(System.Web.SR.GetString("Cannot_execute_url_in_this_context")); } if (((entity != null) && (entity.Length > 0)) && (UnsafeNativeMethods.EcbGetExecUrlEntityInfo(entity.Length, entity, out this._entity) != 1)) { throw new HttpException(System.Web.SR.GetString("Failed_to_execute_url")); } HttpAsyncResult result = new HttpAsyncResult(cb, state); this._asyncResultOfExecuteUrl = result; this._executeUrlCompletionCallback = new ISAPIAsyncCompletionCallback(this.OnExecuteUrlCompletion); this._rootedThis = GCHandle.Alloc(this); if (UnsafeNativeMethods.EcbExecuteUrlUnicode(base._ecb, url, method, childHeaders, sendHeaders, addUserIndo, token, name, authType, this._entity, this._executeUrlCompletionCallback) != 1) { if (this._entity != IntPtr.Zero) { UnsafeNativeMethods.EcbFreeExecUrlEntityInfo(this._entity); } this._rootedThis.Free(); this._asyncResultOfExecuteUrl = null; throw new HttpException(System.Web.SR.GetString("Failed_to_execute_url")); } if (sendHeaders) { this._headersSentFromExecuteUrl = true; } return result; }
private IAsyncResult OnEnter(Object sender, EventArgs e, AsyncCallback cb, Object state) { Debug.Assert(_inputStream == null); _app = (HttpApplication)sender; HttpContext context = _app.Context; HttpRequest request = context.Request; HttpWorkerRequest wr = context.WorkerRequest; HttpAsyncResult httpAsyncResult = new HttpAsyncResult(cb, state); AsyncPreloadModeFlags asyncPreloadMode = context.AsyncPreloadMode; int contentLength; bool isForm = false; bool isFormMultiPart = false; if (asyncPreloadMode == AsyncPreloadModeFlags.None || request.ReadEntityBodyMode != ReadEntityBodyMode.None || wr == null || !wr.SupportsAsyncRead || !wr.HasEntityBody() || wr.IsEntireEntityBodyIsPreloaded() || context.Handler == null || context.Handler is TransferRequestHandler || context.Handler is DefaultHttpHandler || (contentLength = request.ContentLength) > RuntimeConfig.GetConfig(context).HttpRuntime.MaxRequestLengthBytes || ((isForm = StringUtil.StringStartsWithIgnoreCase(request.ContentType, "application/x-www-form-urlencoded")) && (asyncPreloadMode & AsyncPreloadModeFlags.Form) != AsyncPreloadModeFlags.Form) || ((isFormMultiPart = StringUtil.StringStartsWithIgnoreCase(request.ContentType, "multipart/form-data")) && (asyncPreloadMode & AsyncPreloadModeFlags.FormMultiPart) != AsyncPreloadModeFlags.FormMultiPart) || !isForm && !isFormMultiPart && (asyncPreloadMode & AsyncPreloadModeFlags.NonForm) != AsyncPreloadModeFlags.NonForm ) { Debug.Trace("AsyncPreload", " *** AsyncPreload skipped *** "); httpAsyncResult.Complete(true, null, null); return httpAsyncResult; } Debug.Trace("AsyncPreload", " *** AsyncPreload started *** "); try { if (_callback == null) { _callback = new AsyncCallback(OnAsyncCompletion); } _inputStream = request.GetBufferedInputStream(); byte[] buffer = _app.EntityBuffer; int bytesRead = 0; // loop to prevent recursive calls and potential stack overflow if/when it completes synchronously do { IAsyncResult readAsyncResult = _inputStream.BeginRead(buffer, 0, buffer.Length, _callback, httpAsyncResult); if (!readAsyncResult.CompletedSynchronously) { return httpAsyncResult; } bytesRead = _inputStream.EndRead(readAsyncResult); } while (bytesRead != 0); } catch { Reset(); throw; } httpAsyncResult.Complete(true, null, null); return httpAsyncResult; }
internal HttpAsyncResult ExecuteTasks(AsyncCallback callback, object extraData) { this._failedToStart = false; this._timeoutEnd = DateTime.UtcNow + this._page.AsyncTimeout; this._timeoutEndReached = false; this._tasksStarted = 0; this._tasksCompleted = 0; this._asyncResult = new HttpAsyncResult(callback, extraData); bool waitUntilDone = callback == null; if (waitUntilDone) { try { } finally { try { Monitor.Exit(this._app); Monitor.Enter(this._app); } catch (SynchronizationLockException) { this._failedToStart = true; throw new InvalidOperationException(System.Web.SR.GetString("Async_tasks_wrong_thread")); } } } this._inProgress = true; try { this.ResumeTasks(waitUntilDone, true); } finally { if (waitUntilDone) { this._inProgress = false; } } return this._asyncResult; }
internal IAsyncResult BeginAspCompatExecution(AsyncCallback cb, object extraData) { if (IsInAspCompatMode) { bool completedSynchronously = true; Exception error = this._app.ExecuteStep(this, ref completedSynchronously); this._ar = new HttpAsyncResult(cb, extraData, true, null, error); this._syncCaller = true; } else { this._ar = new HttpAsyncResult(cb, extraData); this._syncCaller = cb == null; this._rootedThis = GCHandle.Alloc(this); bool sharedActivity = this._sessionId != null; int activityHash = sharedActivity ? this._sessionId.GetHashCode() : 0; if (System.Web.UnsafeNativeMethods.AspCompatProcessRequest(this._execCallback, this, sharedActivity, activityHash) != 1) { this._rootedThis.Free(); this._ar.Complete(true, null, new HttpException(System.Web.SR.GetString("Cannot_access_AspCompat"))); } } return this._ar; }
IAsyncResult IHttpAsyncHandler.BeginProcessRequest (HttpContext context, AsyncCallback cb, object extraData) { _Context = context; _Context.ApplicationInstance = this; _CompleteRequest = false; _asyncWebResult = new HttpAsyncResult (cb, extraData); _state.Start (); return _asyncWebResult; }
internal HttpAsyncResult ExecuteTasks(AsyncCallback callback, Object extraData) { _failedToStart = false; _timeoutEnd = DateTime.UtcNow + _page.AsyncTimeout; _timeoutEndReached = false; _tasksStarted = 0; _tasksCompleted = 0; _asyncResult = new HttpAsyncResult(callback, extraData); bool waitUntilDone = (callback == null); if (waitUntilDone) { // when requested to wait for tasks, before starting tasks // make sure that the lock can be suspended. try {} finally { try { // disassociating allows other pending work to take place, and associating will block until that work is complete _app.Context.SyncContext.DisassociateFromCurrentThread(); _app.Context.SyncContext.AssociateWithCurrentThread(); } catch (SynchronizationLockException) { _failedToStart = true; throw new InvalidOperationException(SR.GetString(SR.Async_tasks_wrong_thread)); } } } _inProgress = true; try { // all work done here: ResumeTasks(waitUntilDone, true /*onCallerThread*/); } finally { if (waitUntilDone) { _inProgress = false; } } return _asyncResult; }
private void OnExecuteUrlCompletion(IntPtr ecb, int byteCount, int error) { if (_entity != IntPtr.Zero) { UnsafeNativeMethods.EcbFreeExecUrlEntityInfo(_entity); } _rootedThis.Free(); Debug.Trace("ExecuteUrl", "ISAPIWorkerRequestInProcForIIS6.OnExecuteUrlCompletion"); // signal async caller to resume work HttpAsyncResult asyncResult = _asyncResultOfExecuteUrl; _asyncResultOfExecuteUrl = null; asyncResult.Complete(false, null, null); }
internal override IAsyncResult BeginExecuteUrl( String url, String method, String childHeaders, bool sendHeaders, bool addUserIndo, IntPtr token, String name, String authType, byte[] entity, AsyncCallback cb, Object state) { if (_ecb == IntPtr.Zero || // after done with session _asyncResultOfExecuteUrl != null || // another ExecuteUrl in progress (sendHeaders && HeadersSent())) // asked to send headers, but already sent them { throw new InvalidOperationException(SR.GetString(SR.Cannot_execute_url_in_this_context)); } if (entity != null && entity.Length > 0) { int ret = UnsafeNativeMethods.EcbGetExecUrlEntityInfo(entity.Length, entity, out _entity); if (ret != 1) { throw new HttpException(SR.GetString(SR.Failed_to_execute_url)); } } Debug.Trace("ExecuteUrl", "ISAPIWorkerRequestInProcForIIS6.BeginExecuteUrl: url=\"" + url + "\"."); HttpAsyncResult ar = new HttpAsyncResult(cb, state); _asyncResultOfExecuteUrl = ar; _executeUrlCompletionCallback = new ISAPIAsyncCompletionCallback(OnExecuteUrlCompletion); _rootedThis = GCHandle.Alloc(this); // root for the duration of ExecuteUrl int rc; try { ar.MarkCallToBeginMethodStarted(); rc = UnsafeNativeMethods.EcbExecuteUrlUnicode(_ecb, url, method, childHeaders, sendHeaders, addUserIndo, token, name, authType, _entity, _executeUrlCompletionCallback); } finally { ar.MarkCallToBeginMethodCompleted(); } if (rc != 1) { if (_entity != IntPtr.Zero) { UnsafeNativeMethods.EcbFreeExecUrlEntityInfo(_entity); } _rootedThis.Free(); _asyncResultOfExecuteUrl = null; Debug.Trace("ExecuteUrl", "ISAPIWorkerRequestInProcForIIS6.BeginExecuteUrl: failed!"); throw new HttpException(SR.GetString(SR.Failed_to_execute_url)); } if (sendHeaders) { // ExecuteUrl will send headers, worker request should not _headersSentFromExecuteUrl = true; } return ar; }
IAsyncResult OnBeginRequestCache (object o, EventArgs args, AsyncCallback cb, object data) { HttpApplication app = (HttpApplication) o; HttpContext context = app.Context; string vary_key = context.Request.FilePath; CachedVaryBy varyby = context.Cache [vary_key] as CachedVaryBy; string key; CachedRawResponse c; if (varyby == null) goto leave; key = varyby.CreateKey (vary_key, context); c = context.Cache [key] as CachedRawResponse; if (c != null) { context.Response.ClearContent (); context.Response.BinaryWrite (c.GetData (), 0, c.ContentLength); context.Response.ClearHeaders (); c.DateHeader.Value = TimeUtil.ToUtcTimeString (DateTime.Now); context.Response.SetCachedHeaders (c.Headers); context.Response.StatusCode = c.StatusCode; context.Response.StatusDescription = c.StatusDescription; app.CompleteRequest (); } leave: HttpAsyncResult result = new HttpAsyncResult (cb,this); result.Complete (true, o, null); return result; }
IAsyncResult OnBeginUpdateCache (object o, EventArgs args, AsyncCallback cb, object data) { HttpApplication app = (HttpApplication) o; HttpContext context = app.Context; HttpAsyncResult result; if (context.Response.IsCached && context.Response.StatusCode == 200 && !context.Trace.IsEnabled) DoCacheInsert (context); result = new HttpAsyncResult (cb, this); result.Complete (true, o, null); return result; }
internal IAsyncResult BeginProcessRequestNotification(HttpContext context, AsyncCallback cb) { if (this._context == null) { this.AssignContext(context); } context.CurrentModuleEventIndex = -1; HttpAsyncResult result = new HttpAsyncResult(cb, context); context.NotificationContext.AsyncResult = result; this.ResumeSteps(null); return result; }
// // IHttpAsyncHandler implementation // /// <internalonly/> IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) { HttpAsyncResult result; // Setup the asynchronous stuff and application variables _context = context; _context.ApplicationInstance = this; _stepManager.InitRequest(); // Make sure the context stays rooted (including all async operations) _context.Root(); // Create the async result result = new HttpAsyncResult(cb, extraData); // Remember the async result for use in async completions AsyncResult = result; if (_context.TraceIsEnabled) HttpRuntime.Profile.StartRequest(_context); // Start the application ResumeSteps(null); // Return the async result return result; }
internal /*public*/ IAsyncResult BeginAspCompatExecution(AsyncCallback cb, object extraData) { SynchronizationContextUtil.ValidateModeForAspCompat(); if (IsInAspCompatMode) { // already in AspCompatMode -- execute synchronously bool sync = true; Exception error = _app.ExecuteStep(this, ref sync); _ar = new HttpAsyncResult(cb, extraData, true, null, error); _syncCaller = true; } else { _ar = new HttpAsyncResult(cb, extraData); _syncCaller = (cb == null); _rootedThis = GCHandle.Alloc(this); // send requests from the same session to the same STA thread bool sharedActivity = (_sessionId != null); int activityHash = sharedActivity ? _sessionId.GetHashCode() : 0; if (UnsafeNativeMethods.AspCompatProcessRequest(_execCallback, this, sharedActivity, activityHash) != 1) { // failed to queue up the execution in ASP compat mode _rootedThis.Free(); _ar.Complete(true, null, new HttpException(SR.GetString(SR.Cannot_access_AspCompat))); } } return _ar; }
private void ResetPerRequestFields() { this._rqSessionState = null; this._rqId = null; this._rqSessionItems = null; this._rqStaticObjects = null; this._rqIsNewSession = false; this._rqSessionStateNotFound = true; this._rqReadonly = false; this._rqItem = null; this._rqContext = null; this._rqAr = null; this._rqLockId = null; this._rqInCallback = 0; this._rqLastPollCompleted = DateTime.MinValue; this._rqExecutionTimeout = TimeSpan.Zero; this._rqAddedCookie = false; this._rqIdNew = false; this._rqActionFlags = SessionStateActions.None; this._rqIctx = null; this._rqChangeImpersonationRefCount = 0; this._rqTimerThreadImpersonationIctx = null; this._rqSupportSessionIdReissue = false; }
private IAsyncResult BeginAcquireState(object source, EventArgs e, AsyncCallback cb, object extraData) { IAsyncResult result; bool sessionStateItem = true; bool flag3 = false; this._acquireCalled = true; this._releaseCalled = false; this.ResetPerRequestFields(); this._rqContext = ((HttpApplication) source).Context; this._rqAr = new HttpAsyncResult(cb, extraData); this.ChangeImpersonation(this._rqContext, false); try { if (EtwTrace.IsTraceEnabled(4, 8)) { EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_BEGIN, this._rqContext.WorkerRequest); } this._store.InitializeRequest(this._rqContext); bool requiresSessionState = this._rqContext.RequiresSessionState; if (this._idManager.InitializeRequest(this._rqContext, false, out this._rqSupportSessionIdReissue)) { this._rqAr.Complete(true, null, null); if (EtwTrace.IsTraceEnabled(4, 8)) { EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, this._rqContext.WorkerRequest); } return this._rqAr; } if ((s_allowInProcOptimization && !s_sessionEverSet) && (!requiresSessionState || !((SessionIDManager) this._idManager).UseCookieless(this._rqContext))) { flag3 = true; } else { this._rqId = this._idManager.GetSessionID(this._rqContext); } if (!requiresSessionState) { if (this._rqId != null) { this._store.ResetItemTimeout(this._rqContext, this._rqId); } this._rqAr.Complete(true, null, null); if (EtwTrace.IsTraceEnabled(4, 8)) { EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, this._rqContext.WorkerRequest); } return this._rqAr; } this._rqExecutionTimeout = this._rqContext.Timeout; if (this._rqExecutionTimeout == DEFAULT_DBG_EXECUTION_TIMEOUT) { this._rqExecutionTimeout = s_configExecutionTimeout; } this._rqReadonly = this._rqContext.ReadOnlySessionState; if (this._rqId != null) { sessionStateItem = this.GetSessionStateItem(); } else if (!flag3) { bool flag4 = this.CreateSessionId(); this._rqIdNew = true; if (flag4) { if (s_configRegenerateExpiredSessionId) { this.CreateUninitializedSessionState(); } this._rqAr.Complete(true, null, null); if (EtwTrace.IsTraceEnabled(4, 8)) { EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, this._rqContext.WorkerRequest); } return this._rqAr; } } if (sessionStateItem) { this.CompleteAcquireState(); this._rqAr.Complete(true, null, null); } result = this._rqAr; } finally { this.RestoreImpersonation(); } return result; }
private IAsyncResult OnEnter(Object sender, EventArgs e, AsyncCallback cb, Object state) { Debug.Assert(_inputStream == null); _app = (HttpApplication)sender; HttpContext context = _app.Context; HttpRequest request = context.Request; HttpWorkerRequest wr = context.WorkerRequest; HttpAsyncResult httpAsyncResult = new HttpAsyncResult(cb, state); AsyncPreloadModeFlags asyncPreloadMode = context.AsyncPreloadMode; int contentLength; bool isForm = false; bool isFormMultiPart = false; if (asyncPreloadMode == AsyncPreloadModeFlags.None || request.ReadEntityBodyMode != ReadEntityBodyMode.None || wr == null || !wr.SupportsAsyncRead || !wr.HasEntityBody() || wr.IsEntireEntityBodyIsPreloaded() || context.Handler == null || context.Handler is TransferRequestHandler || context.Handler is DefaultHttpHandler || (contentLength = request.ContentLength) > RuntimeConfig.GetConfig(context).HttpRuntime.MaxRequestLengthBytes || ((isForm = StringUtil.StringStartsWithIgnoreCase(request.ContentType, "application/x-www-form-urlencoded")) && (asyncPreloadMode & AsyncPreloadModeFlags.Form) != AsyncPreloadModeFlags.Form) || ((isFormMultiPart = StringUtil.StringStartsWithIgnoreCase(request.ContentType, "multipart/form-data")) && (asyncPreloadMode & AsyncPreloadModeFlags.FormMultiPart) != AsyncPreloadModeFlags.FormMultiPart) || !isForm && !isFormMultiPart && (asyncPreloadMode & AsyncPreloadModeFlags.NonForm) != AsyncPreloadModeFlags.NonForm ) { Debug.Trace("AsyncPreload", " *** AsyncPreload skipped *** "); httpAsyncResult.Complete(true, null, null); return(httpAsyncResult); } Debug.Trace("AsyncPreload", " *** AsyncPreload started *** "); try { if (_callback == null) { _callback = new AsyncCallback(OnAsyncCompletion); } _inputStream = request.GetBufferedInputStream(); byte[] buffer = _app.EntityBuffer; int bytesRead = 0; // loop to prevent recursive calls and potential stack overflow if/when it completes synchronously do { IAsyncResult readAsyncResult = _inputStream.BeginRead(buffer, 0, buffer.Length, _callback, httpAsyncResult); if (!readAsyncResult.CompletedSynchronously) { return(httpAsyncResult); } bytesRead = _inputStream.EndRead(readAsyncResult); } while (bytesRead != 0); } catch { Reset(); throw; } httpAsyncResult.Complete(true, null, null); return(httpAsyncResult); }
IAsyncResult OnBeginAcquireState (object o, EventArgs args, AsyncCallback cb, object data) { HttpApplication application = (HttpApplication) o; HttpContext context = application.Context; bool required = (context.Handler is IRequiresSessionState); // This is a hack. Sites that use Session in global.asax event handling code // are not supposed to get a Session object for static files, but seems that // IIS handles those files before getting there and thus they are served without // error. // As a workaround, setting MONO_XSP_STATIC_SESSION variable make this work // on mono, but you lose performance when serving static files. if (sessionForStaticFiles && context.Handler is StaticFileHandler) required = true; // hack end bool read_only = (context.Handler is IReadOnlySessionState); bool isNew = false; HttpSessionState session = null; if (handler != null) session = handler.UpdateContext (context, this, required, read_only, ref isNew); if (session != null) { if (isNew) session.SetNewSession (true); if (read_only) session = session.Clone (); context.SetSession (session); if (isNew && config.CookieLess) { string id = context.Session.SessionID; context.Request.SetHeader (HeaderName, id); context.Response.Redirect (UrlUtils.InsertSessionId (id, context.Request.FilePath)); } else if (isNew) { string id = context.Session.SessionID; HttpCookie cookie = new HttpCookie (CookieName, id); cookie.Path = UrlUtils.GetDirectory (context.Request.ApplicationPath); context.Response.AppendCookie (cookie); } } // In the future, we might want to move the Async stuff down to // the interface level, if we're going to support other than // InProc, we might actually want to do things async, now we // simply fake it. HttpAsyncResult result=new HttpAsyncResult (cb,this); result.Complete (true, o, null); if (isNew && Start != null) Start (this, args); return result; }
private void OnExecuteUrlCompletion(IntPtr ecb, int byteCount, int error) { if (this._entity != IntPtr.Zero) { UnsafeNativeMethods.EcbFreeExecUrlEntityInfo(this._entity); } this._rootedThis.Free(); HttpAsyncResult result = this._asyncResultOfExecuteUrl; this._asyncResultOfExecuteUrl = null; result.Complete(false, null, null); }
internal IAsyncResult BeginProcessRequestNotification(HttpContext context, AsyncCallback cb) { Debug.Trace("PipelineRuntime", "BeginProcessRequestNotification"); HttpAsyncResult result; if (_context == null) { // AssignContext(context); } // // everytime initialization // context.CurrentModuleEventIndex = -1; // Create the async result result = new HttpAsyncResult(cb, context); context.NotificationContext.AsyncResult = result; // enter notification execution loop ResumeSteps(null); return result; }
IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { this._context = context; this._context.ApplicationInstance = this; this._stepManager.InitRequest(); this._context.Root(); HttpAsyncResult result = new HttpAsyncResult(cb, extraData); this.AsyncResult = result; if (this._context.TraceIsEnabled) { HttpRuntime.Profile.StartRequest(this._context); } this.ResumeSteps(null); return result; }