public ProgressWorkerRequest(HttpWorkerRequest wr, HttpRequest request)
 {
     this._originalWorkerRequest = wr;
     this._request = request;
     this._boundary = this.GetBoundary(this._request);
     this._requestStateStore = new Areas.Lib.UploadProgress.Upload.RequestStateStore(this._request.ContentEncoding);
 }
Ejemplo n.º 2
0
		public HttpWorkerRequest GetNextRequest (HttpWorkerRequest req)
		{
			if (!CanExecuteRequest (req)) {
				if (req != null) {
					lock (queue) {
						Queue (req);
					}
				}

				return null;
			}

			HttpWorkerRequest result;
			lock (queue) {
				result = Dequeue ();
				if (result != null) {
					if (req != null)
						Queue (req);
				} else {
					result = req;
				}
			}

			return result;
		}
Ejemplo n.º 3
0
 protected DecoratedWorkerRequest(HttpWorkerRequest origWorker)
 {
     if (log.IsDebugEnabled) log.Debug("origWorker=" + origWorker);
     OrigWorker = origWorker;
     // Remember the original HttpContext so that it can be used by UploadHttpModule.AppendToLog().
     OrigContext = HttpContext.Current;
 }
Ejemplo n.º 4
0
        public TestWebContext(string virtualPath, string page)
        {
            _out = new StringWriter();
            HttpWorkerRequest wr;
            AppDomain domain = Thread.GetDomain();

            // are we running within a valid AspNet AppDomain?
            string appPath = (string) domain.GetData(".appPath");
            if (appPath != null)
            {
                wr = new SimpleWorkerRequest(page, string.Empty, _out);
            }
            else
            {
                appPath = domain.BaseDirectory + "\\";
                wr = new SimpleWorkerRequest(virtualPath, appPath, page, string.Empty, _out);
            }
            HttpContext ctx = new HttpContext(wr);
            HttpContext.Current = ctx;
            HttpBrowserCapabilities browser = new HttpBrowserCapabilities();
            browser.Capabilities = new CaseInsensitiveHashtable(); //CollectionsUtil.CreateCaseInsensitiveHashtable();
            browser.Capabilities[string.Empty] = "Test User Agent"; // string.Empty is the key for "user agent"

            // avoids NullReferenceException when accessing HttpRequest.FilePath
            object virtualPathObject = ExpressionEvaluator.GetValue(null, "T(System.Web.VirtualPath).Create('/')");
            object cachedPathData = ExpressionEvaluator.GetValue(null, "T(System.Web.CachedPathData).GetRootWebPathData()");
            ExpressionEvaluator.SetValue(cachedPathData, "_virtualPath", virtualPathObject);
            ExpressionEvaluator.SetValue(cachedPathData, "_physicalPath", appPath);

            ctx.Request.Browser = browser;
            string filePath = ctx.Request.FilePath;
            _wr = wr;
        }
        // This constructor creates the header collection for response headers.
        // Try to preallocate the base collection with a size that should be sufficient
        // to store the headers for most requests.
        internal HttpHeaderCollection(HttpWorkerRequest wr, HttpResponse response, int capacity) : base(capacity) {

            // if this is an IIS7WorkerRequest, then the collection will be writeable and we will
            // call into IIS7 to update the header blocks when changes are made.
            _iis7WorkerRequest = wr as IIS7WorkerRequest;

            _response = response;
        }
Ejemplo n.º 6
0
 void IHttpResponseElement.Send(HttpWorkerRequest wr)
 {
     if (this._size > 0)
     {
         bool isBufferFromUnmanagedPool = false;
         wr.SendResponseFromMemory(new IntPtr(this._data.ToInt64() + this._offset), this._size, isBufferFromUnmanagedPool);
     }
 }
 public static KeyValuePair<HttpContext, HttpApplication> GetContext(HttpWorkerRequest wr, params IHttpModule[] modules) {
     var ctx = new HttpContext(wr);
     var app = new MyApp(modules);
     SetHttpApplicationFactoryCustomApplication(app);
     InitInternal(app, ctx);
     AssignContext(app, ctx);
     return new KeyValuePair<HttpContext, HttpApplication>(ctx, app);
 }
        public static RequestBufferlessStream CreateStream(HttpWorkerRequest workerRequest)
        {
            if (workerRequest == null)
                throw new ArgumentNullException("workerRequest");

            long totalBytes = (long)workerRequest.GetTotalEntityBodyLength();
            return new RequestBufferlessStream(workerRequest, totalBytes);
        }
 void IHttpResponseElement.Send(HttpWorkerRequest wr)
 {
     if (this._size > 0)
     {
         bool isBufferFromUnmanagedPool = false;
         wr.SendResponseFromMemory(new IntPtr(this._data.ToInt64() + this._offset), this._size, isBufferFromUnmanagedPool);
     }
 }
 private bool CheckClientConnected(HttpWorkerRequest wr)
 {
     if ((DateTime.UtcNow - wr.GetStartTime()) > this._clientConnectedTime)
     {
         return wr.IsClientConnected();
     }
     return true;
 }
 private bool CheckClientConnected(HttpWorkerRequest wr)
 {
     if ((DateTime.UtcNow - wr.GetStartTime()) > this._clientConnectedTime)
     {
         return(wr.IsClientConnected());
     }
     return(true);
 }
        // This constructor creates the header collection for response headers.
        // Try to preallocate the base collection with a size that should be sufficient
        // to store the headers for most requests.
        internal HttpHeaderCollection(HttpWorkerRequest wr, HttpResponse response, int capacity) : base(capacity) {

            // if this is an IIS7WorkerRequest, then the collection will be writeable and we will
            // call into IIS7 to update the header blocks when changes are made.
            _iis7WorkerRequest = wr as IIS7WorkerRequest;

            _response = response;
        }
 void IHttpResponseElement.Send(HttpWorkerRequest wr)
 {
     int length = base._size - base._free;
     if (length > 0)
     {
         wr.SendResponseFromMemory(this._data, length);
     }
 }
Ejemplo n.º 14
0
        // Caller may invoke this repeatedly until EndRead returns zero, at which point the entire entity has been read.
        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
        {
            HttpWorkerRequest wr = _context.WorkerRequest;

            // Only perform an async read if the worker request supports it and we're not in a cancellable period.
            // If we were to allow async read in a cancellable period, the timeout manager could raise a ThreadAbortEx and
            // corrupt the state of the request.
            if (wr != null && wr.SupportsAsyncRead && !_context.IsInCancellablePeriod)
            {
                if (!_preloadedContentRead)
                {
                    if (buffer == null)
                    {
                        throw new ArgumentNullException("buffer");
                    }
                    if (offset < 0)
                    {
                        throw new ArgumentOutOfRangeException("offset");
                    }
                    if (count < 0)
                    {
                        throw new ArgumentOutOfRangeException("count");
                    }
                    if (buffer.Length - offset < count)
                    {
                        throw new ArgumentException(SR.GetString(SR.InvalidOffsetOrCount, "offset", "count"));
                    }
                    _preloadedBytesRead = GetPreloadedContent(buffer, ref offset, ref count);
                }
                if (_remainingBytes == 0)
                {
                    // set count to zero and invoke BeginRead to return an async result
                    count = 0;
                }
                if (_persistEntityBody)
                {
                    // hold a reference so we can add bytes to _rawContent when EndRead is called
                    _buffer = buffer;
                    _offset = offset;
                    _count  = count;
                }
                try {
                    return(wr.BeginRead(buffer, offset, count, callback, state));
                }
                catch (HttpException) {
                    if (_persistEntityBody)
                    {
                        SetRawContentOnce();
                    }
                    throw;
                }
            }
            else
            {
                // perform a sync read
                return(base.BeginRead(buffer, offset, count, callback, state));
            }
        }
        // method called from HttpRuntime for incoming requests
        internal HttpWorkerRequest GetRequestToExecute(HttpWorkerRequest wr)
        {
            int workerThreads, ioThreads;

            ThreadPool.GetAvailableThreads(out workerThreads, out ioThreads);

            int freeThreads;

            if (_iis6)
            {
                freeThreads = workerThreads; // ignore IO threads to avoid starvation from Indigo TCP requests
            }
            else
            {
                freeThreads = (ioThreads > workerThreads) ? workerThreads : ioThreads;
            }

            // fast path when there are threads available and nothing queued
            if (freeThreads >= _minExternFreeThreads && _count == 0)
            {
                return(wr);
            }

            bool isLocal = IsLocal(wr);

            // fast path when there are threads for local requests available and nothing queued
            if (isLocal && freeThreads >= _minLocalFreeThreads && _count == 0)
            {
                return(wr);
            }

            // reject if queue limit exceeded
            if (_count >= _queueLimit)
            {
                HttpRuntime.RejectRequestNow(wr, false);
                return(null);
            }

            // can't execute the current request on the current thread -- need to queue
            QueueRequest(wr, isLocal);

            // maybe can execute a request previously queued
            if (freeThreads >= _minExternFreeThreads)
            {
                wr = DequeueRequest(false); // enough threads to process even external requests
            }
            else if (freeThreads >= _minLocalFreeThreads)
            {
                wr = DequeueRequest(true);  // enough threads to process only local requests
            }
            else
            {
                wr = null;                  // not enough threads -> do nothing on this thread
                ScheduleMoreWorkIfNeeded(); // try to schedule to worker thread
            }

            return(wr);
        }
Ejemplo n.º 16
0
        public HttpContext(HttpWorkerRequest wr)
        {
            WorkerRequest = wr;
            request       = new HttpRequest(WorkerRequest, this);
            response      = new HttpResponse(WorkerRequest, this);
#if NET_4_0
            SessionStateBehavior = SessionStateBehavior.Default;
#endif
        }
Ejemplo n.º 17
0
        /*
         * Write HttpWorkerRequest
         */
        /*public*/ void IHttpResponseElement.Send(HttpWorkerRequest wr)
        {
            int n = _size - _free;

            if (n > 0)
            {
                wr.SendResponseFromMemory(_data, n);
            }
        }
Ejemplo n.º 18
0
            public override void Send(HttpWorkerRequest wr)
            {
                if (length == 0)
                {
                    return;
                }

                blocks.Send(wr, start, length);
            }
Ejemplo n.º 19
0
            public void Send(HttpWorkerRequest wr, int start, int end)
            {
                if (end - start <= 0)
                {
                    return;
                }

                wr.SendResponseFromMemory((IntPtr)(data + start), end - start);
            }
        // We preallocate the base collection with a size that should be sufficient
        // to store all server variables w/o having to expand
        internal HttpServerVarsCollection(HttpWorkerRequest wr, HttpRequest request) : base(59) {
            // if this is an IIS7WorkerRequest, then the collection will be writeable and we will
            // call into IIS7 to update the server var block when changes are made.
            _iis7workerRequest = wr as IIS7WorkerRequest;
            _request = request;
            _populated = false;

            Debug.Assert( _request != null );
        }
        void IHttpResponseElement.Send(HttpWorkerRequest wr)
        {
            int length = base._size - base._free;

            if (length > 0)
            {
                wr.SendResponseFromMemory(this._data, length, true);
            }
        }
Ejemplo n.º 22
0
            public override void Send(HttpWorkerRequest wr)
            {
                if (_position == 0)
                {
                    return;
                }

                wr.SendResponseFromMemory(buffer, 0, _position, _encoding);
            }
Ejemplo n.º 23
0
 internal void SetWorkerRequest(HttpWorkerRequest wr)
 {
     worker_request   = wr;
     current_exe_path = null;
     file_path        = null;
     base_virtual_dir = null;
     form             = null;
     all_params       = null;
 }
Ejemplo n.º 24
0
		bool CanExecuteRequest (HttpWorkerRequest req)
		{
			if (disposing)
				return false;
				
			int threads, cports;
			ThreadPool.GetAvailableThreads (out threads, out cports);
			bool local = (req != null && req.GetLocalAddress () == "127.0.0.1");
			return (threads > minFree) || (local && threads > minLocalFree);
		}
Ejemplo n.º 25
0
		public HttpContext (HttpWorkerRequest WorkerRequest)
		{
			Context = this;

			_oTimestamp = DateTime.Now;
			_oRequest = new HttpRequest (WorkerRequest, this);
			_oResponse = new HttpResponse (WorkerRequest, this);
			_oWorkerRequest = WorkerRequest;
			_oTrace = new TraceContext (this);
		}
        // We preallocate the base collection with a size that should be sufficient
        // to store all server variables w/o having to expand
        internal HttpServerVarsCollection(HttpWorkerRequest wr, HttpRequest request) : base(59)
        {
            // if this is an IIS7WorkerRequest, then the collection will be writeable and we will
            // call into IIS7 to update the server var block when changes are made.
            _iis7workerRequest = wr as IIS7WorkerRequest;
            _request           = request;
            _populated         = false;

            Debug.Assert(_request != null);
        }
Ejemplo n.º 27
0
        void UnsafeWrite(HttpWorkerRequest wr, byte [] buffer, int offset, int count)
        {
            if (count <= 0)
            {
                return;
            }

            byte [] copy = new byte [count];
            Array.Copy(buffer, offset, copy, 0, count);
            wr.SendResponseFromMemory(copy, count);
        }
Ejemplo n.º 28
0
 internal void Send(HttpWorkerRequest wr)
 {
     if (_knownHeaderIndex >= 0)
     {
         wr.SendKnownResponseHeader(_knownHeaderIndex, _value);
     }
     else
     {
         wr.SendUnknownResponseHeader(_unknownHeader, _value);
     }
 }
Ejemplo n.º 29
0
        static void RealProcessRequest(object o)
        {
            HttpWorkerRequest req   = (HttpWorkerRequest)o;
            bool started_internally = req.StartedInternally;

            do
            {
                Process(req);
                req = QueuePendingRequest(started_internally);
            } while (started_internally && req != null);
        }
Ejemplo n.º 30
0
        HttpWorkerRequest Dequeue()
        {
            if (queue.Count > 0)
            {
                HttpWorkerRequest request = (HttpWorkerRequest)queue.Dequeue();
                requestsQueuedCounter.Decrement();
                return(request);
            }

            return(null);
        }
 internal void Send(HttpWorkerRequest wr)
 {
     if (this._knownHeaderIndex >= 0)
     {
         wr.SendKnownResponseHeader(this._knownHeaderIndex, this._value);
     }
     else
     {
         wr.SendUnknownResponseHeader(this._unknownHeader, this._value);
     }
 }
Ejemplo n.º 32
0
        void Queue(HttpWorkerRequest wr)
        {
            if (queue.Count < queueLimit)
            {
                queue.Enqueue(wr);
                requestsQueuedCounter.Increment();
                return;
            }

            HttpRuntime.FinishUnavailable(wr);
        }
Ejemplo n.º 33
0
        // When this returns zero, the entire entity has been read.
        public override int EndRead(IAsyncResult asyncResult)
        {
            HttpWorkerRequest wr = _context.WorkerRequest;

            if (wr != null && wr.SupportsAsyncRead && !_context.IsInCancellablePeriod)
            {
                int totalBytesRead = _preloadedBytesRead;
                if (_preloadedBytesRead > 0)
                {
                    _preloadedBytesRead = 0;
                }
                int bytesRead = 0;
                try {
                    bytesRead = wr.EndRead(asyncResult);
                }
                catch (HttpException) {
                    if (_persistEntityBody)
                    {
                        SetRawContentOnce();
                    }
                    throw;
                }
                totalBytesRead += bytesRead;
                if (bytesRead > 0)
                {
                    if (_persistEntityBody)
                    {
                        if (_rawContent != null)
                        {
                            _rawContent.AddBytes(_buffer, _offset, bytesRead);
                        }
                        _buffer = null;
                        _offset = 0;
                        _count  = 0;
                    }
                    int dummy1 = 0, dummy2 = 0, dummy3 = 0;
                    UpdateCounters(bytesRead, ref dummy1, ref dummy2, ref dummy3);
                }
                if (_persistEntityBody
                    // we might attempt a read with count == 0, in which case bytesRead will
                    // be zero but we may not be done reading the entity body. Don't set raw
                    // content until bytesRead is 0 and count is not 0 or _remainingBytes is 0
                    && ((bytesRead == 0 && _count != 0) || _remainingBytes == 0))
                {
                    SetRawContentOnce();
                }
                return(totalBytesRead);
            }
            else
            {
                return(base.EndRead(asyncResult));
            }
        }
Ejemplo n.º 34
0
        // ctor used in HttpRuntime
        internal HttpContext(HttpWorkerRequest wr, bool initResponseWriter)
        {
            _wr = wr;
            Init(new HttpRequest(wr, this), new HttpResponse(wr, this));

            if (initResponseWriter)
            {
                _response.InitResponseWriter();
            }

            PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_EXECUTING);
        }
Ejemplo n.º 35
0
        internal HttpResponse(HttpWorkerRequest worker_request, HttpContext context) : this()
        {
            WorkerRequest = worker_request;
            this.context  = context;

#if !TARGET_J2EE
            if (worker_request != null)
            {
                use_chunked = (worker_request.GetHttpVersion() == "HTTP/1.1");
            }
#endif
        }
Ejemplo n.º 36
0
        //
        // This is called from the QueueManager if a request
        // can not be processed (load, no resources, or
        // appdomain unload).
        //
        static internal void FinishUnavailable(HttpWorkerRequest wr)
        {
            wr.SendStatus(503, "Service unavailable");
            wr.SendUnknownResponseHeader("Connection", "close");
            Encoding enc = Encoding.ASCII;

            wr.SendUnknownResponseHeader("Content-Type", "text/html; charset=" + enc.WebName);
            byte [] contentBytes = enc.GetBytes(content503);
            wr.SendUnknownResponseHeader("Content-Length", contentBytes.Length.ToString());
            wr.SendResponseFromMemory(contentBytes, contentBytes.Length);
            wr.FlushResponse(true);
            wr.CloseConnection();
            HttpApplication.requests_total_counter.Increment();
        }
 void IHttpResponseElement.Send(HttpWorkerRequest wr)
 {
     if (this._size > 0L)
     {
         if (this._useTransmitFile)
         {
             wr.TransmitFile(this._filename, this._offset, this._size, this._isImpersonating);
         }
         else
         {
             wr.SendResponseFromFile(this._filename, this._offset, this._size);
         }
     }
 }
Ejemplo n.º 38
0
        bool CanExecuteRequest(HttpWorkerRequest req)
        {
            if (disposing)
            {
                return(false);
            }

            int threads, cports;

            ThreadPool.GetAvailableThreads(out threads, out cports);
            bool local = (req != null && req.GetLocalAddress() == "127.0.0.1");

            return((threads > minFree) || (local && threads > minLocalFree));
        }
Ejemplo n.º 39
0
 internal HttpResponseHeader(string unknownHeader, string value, bool enableHeaderChecking)
 {
     if (enableHeaderChecking)
     {
         HttpEncoder.Current.HeaderNameValueEncode(unknownHeader, value, out _unknownHeader, out _value);
         _knownHeaderIndex = HttpWorkerRequest.GetKnownResponseHeaderIndex(_unknownHeader);
     }
     else
     {
         _unknownHeader    = unknownHeader;
         _knownHeaderIndex = HttpWorkerRequest.GetKnownResponseHeaderIndex(_unknownHeader);
         _value            = value;
     }
 }
Ejemplo n.º 40
0
        public AsyncUpload(HttpWorkerRequest wRquest)
        {
            if (wRquest == null) throw new ArgumentNullException("wRquest");
            this.uploadProcess = new UploadProcess(delegate(float f) { });
            workerRequest = wRquest;

            //当前读到的流长度
            this.preLen = workerRequest.GetPreloadedEntityBodyLength();
            //请求流的总长度
            this.totLen = workerRequest.GetTotalEntityBodyLength();
            //内容分隔符 如: -----------------------------152733254716788
            if (preLen == 0 && workerRequest.IsClientConnected() && workerRequest.HasEntityBody())
            {
                byte[] buffer = new byte[8192];
                preLen = workerRequest.ReadEntityBody(buffer, buffer.Length);
                byte[] buf = new byte[preLen];
                for (int i = 0; i < buf.Length; i++) buf[i] = buffer[i];
                this.perBodyBytes = buf;
            }
            else
                this.perBodyBytes = workerRequest.GetPreloadedEntityBody();

            this.headerBytes = this.GetBoundaryBytes(Encoding.UTF8.GetBytes(workerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentType)));
            //请求流尾部分隔符 如: -----------------------------152733254716788--
            this.contentEnd = new byte[this.headerBytes.Length + 2];
            this.headerBytes.CopyTo(this.contentEnd, 0);
            this.contentEnd[this.headerBytes.Length] = 45;
            this.contentEnd[this.headerBytes.Length + 1] = 45;

            //当前流中第一个文件分隔符的位置
            int fHeaderPosition = perBodyBytes.Indexof(fileNameHeader);
            //尝试在已读取到的流中找文件尾位置
            this.fEndPosition = perBodyBytes.Indexof(contentEnd);
            if (fHeaderPosition > -1)
            {
                //先找到文件名
                IList<byte> bufList = new List<byte>();
                int i = fHeaderPosition + fileNameHeader.Length;
                while (i < perBodyBytes.Length)
                {
                    if (perBodyBytes[i] == 34) break;
                    bufList.Add(perBodyBytes[i]);
                    i++;
                }

                this.FileName = Encoding.UTF8.GetString(bufList.ToArray());//file name
                this.fPosition = perBodyBytes.Indexof(wrapBytes, i) + 4;//当前流中此文件的开始位置
                this.FileLength = this.totLen - this.fPosition;
            }
        }
Ejemplo n.º 41
0
 /*
  * Write HttpWorkerRequest
  */
 /*public*/ void IHttpResponseElement.Send(HttpWorkerRequest wr)
 {
     if (_size > 0)
     {
         if (_filename != null)
         {
             wr.SendResponseFromFile(_filename, _offset, _size);
         }
         else
         {
             wr.SendResponseFromFile(_fileHandle, _offset, _size);
         }
     }
 }
Ejemplo n.º 42
0
		public RequestStream(HttpWorkerRequest request)
		{
			this.request = request;

			tempBuff = request.GetPreloadedEntityBody();

            _contentLength = long.Parse(request.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength));
            
            // Handle the case where GetPreloadedEntityBody is null -- e.g. Mono
			if (tempBuff == null || tempBuff.Length == 0)
			{
				isInPreloaded = false;
			}
    	}
        private HttpWorkerRequest DequeueRequest(bool localOnly)
        {
            HttpWorkerRequest wr = null;

            while (_count > 0)
            {
                lock (this) {
                    if (_localQueue.Count > 0)
                    {
                        wr = (HttpWorkerRequest)_localQueue.Dequeue();
                        _count--;
                    }
                    else if (!localOnly && _externQueue.Count > 0)
                    {
                        wr = (HttpWorkerRequest)_externQueue.Dequeue();
                        _count--;
                    }
                }

                if (wr == null)
                {
                    break;
                }
                else
                {
                    PerfCounters.DecrementGlobalCounter(GlobalPerfCounter.REQUESTS_QUEUED);
                    PerfCounters.DecrementCounter(AppPerfCounter.REQUESTS_IN_APPLICATION_QUEUE);
                    if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.Infrastructure))
                    {
                        EtwTrace.Trace(EtwTraceType.ETW_TYPE_REQ_DEQUEUED, wr);
                    }

                    if (!CheckClientConnected(wr))
                    {
                        HttpRuntime.RejectRequestNow(wr, true);
                        wr = null;

                        PerfCounters.IncrementGlobalCounter(GlobalPerfCounter.REQUESTS_DISCONNECTED);
                        PerfCounters.IncrementCounter(AppPerfCounter.APP_REQUEST_DISCONNECTED);
                    }
                    else
                    {
                        break;
                    }
                }
            }

            return(wr);
        }
        protected override string InternalGet(string name)
        {
            int    headerIndex = HttpWorkerRequest.GetKnownRequestHeaderIndex(name);
            string headerValue = null;

            if (headerIndex >= 0)
            {
                headerValue = _request.WorkerRequest.GetKnownRequestHeader(headerIndex);
            }
            if (headerValue == null)
            {
                headerValue = _request.WorkerRequest.GetUnknownRequestHeader(name);
            }
            return(headerValue);
        }
Ejemplo n.º 45
0
		internal HttpClientCertificate (HttpWorkerRequest hwr)
		{
			// we don't check hwr for null so we end up throwing a 
			// NullReferenceException just like MS implementation
			// if the public ctor for HttpRequest is used
			this.hwr = hwr;
			flags = GetIntNoPresense ("CERT_FLAGS");
			if (IsPresent) {
				from = hwr.GetClientCertificateValidFrom ();
				until = hwr.GetClientCertificateValidUntil ();
			} else {
				from = DateTime.Now;
				until = from;
			}
		}
Ejemplo n.º 46
0
 void IHttpResponseElement.Send(HttpWorkerRequest wr)
 {
     if (this._isIIS7WorkerRequest)
     {
         IIS7WorkerRequest request = wr as IIS7WorkerRequest;
         if (request != null)
         {
             request.SendResponseFromIISAllocatedRequestMemory(this._firstSubstData, this._firstSubstDataSize);
         }
     }
     else
     {
         this._firstSubstitution.Send(wr);
     }
 }
Ejemplo n.º 47
0
        internal void Flush(HttpWorkerRequest wr, bool final_flush)
        {
            if (!dirty && !final_flush)
            {
                return;
            }

            for (Bucket b = first_bucket; b != null; b = b.Next)
            {
                b.Send(wr);
            }

            wr.FlushResponse(final_flush);
            Clear();
        }
Ejemplo n.º 48
0
		static void Redirect (HttpWorkerRequest wr, string location)
		{
			string host = wr.GetKnownRequestHeader (HttpWorkerRequest.HeaderHost);
			wr.SendStatus (301, "Moved Permanently");
			wr.SendUnknownResponseHeader ("Connection", "close");
			wr.SendUnknownResponseHeader ("Date", DateTime.Now.ToUniversalTime ().ToString ("r"));
			wr.SendUnknownResponseHeader ("Location", String.Format ("{0}://{1}{2}", wr.GetProtocol(), host, location));
			Encoding enc = Encoding.ASCII;
			wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
			string content = String.Format (CONTENT301, host, location);
			byte [] contentBytes = enc.GetBytes (content);
			wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
			wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
			wr.FlushResponse (true);
			wr.CloseConnection ();
		}
Ejemplo n.º 49
0
        private void QueueRequest(HttpWorkerRequest wr, bool isLocal) {
            lock (this) {
                if (isLocal) {
                    _localQueue.Enqueue(wr);
                }
                else  {
                    _externQueue.Enqueue(wr);
                }

                _count++;
            }

            PerfCounters.IncrementGlobalCounter(GlobalPerfCounter.REQUESTS_QUEUED);
            PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_IN_APPLICATION_QUEUE);
            if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.Infrastructure)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_REQ_QUEUED, wr);
        }
    /// <summary>
    /// Gets the response.
    /// </summary>
    /// <param name="workerRequest">The worker request.</param>
    /// <returns>The <see cref="Response"/>.</returns>
    protected virtual Response GetResponse(HttpWorkerRequest workerRequest)
    {
      if (workerRequest == null)
      {
        throw new ArgumentNullException("workerRequest");
      }

      WorkerRequest workerRequestCandidate = workerRequest as WorkerRequest;

      if (workerRequestCandidate == null)
      {
        throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "workerRequest is of improper type. It should be based on {0}", typeof(WorkerRequest).AssemblyQualifiedName));
      }

      return workerRequestCandidate.Response;
    }
Ejemplo n.º 51
0
        internal static bool IsUploadStatusRequest(HttpWorkerRequest request, out string id)
        {
            id = string.Empty;

            if (request.GetHttpVerbName() != GetVerbName)
                return false;

            Match m = _getUploadId.Match(request.GetRawUrl());

            if (!m.Success)
                return false;

            id = m.Value;

            return true;
        }
Ejemplo n.º 52
0
        // helpers
        private static bool IsLocal(HttpWorkerRequest wr) {
            String remoteAddress = wr.GetRemoteAddress();

            // check if localhost
            if (remoteAddress == "127.0.0.1" || remoteAddress == "::1")
                return true;

            // if unknown, assume not local
            if (String.IsNullOrEmpty(remoteAddress))
                return false;

            // compare with local address
            if (remoteAddress == wr.GetLocalAddress())
                return true;

            return false;
        }
 private static void ResolveWorkerRequestType(HttpWorkerRequest workerRequest)
 {
     if (workerRequest is IIS7WorkerRequest)
     {
         s_WrType = EtwWorkerRequestType.IIS7Integrated;
     }
     else if (workerRequest is ISAPIWorkerRequestInProc)
     {
         s_WrType = EtwWorkerRequestType.InProc;
     }
     else if (workerRequest is ISAPIWorkerRequestOutOfProc)
     {
         s_WrType = EtwWorkerRequestType.OutOfProc;
     }
     else
     {
         s_WrType = EtwWorkerRequestType.Unknown;
     }
 }
		internal void SendContent (HttpWorkerRequest WorkerRequest)
		{
			// use URL encoding on the value (see bug #75392)
			// but only for CR and LF. Other characters are left untouched.
			string actual_val = val;
			if (actual_val != null) {
				int crlf = actual_val.IndexOfAny (CRLF);
				if (crlf >= 0) {
					actual_val = actual_val.Replace ("\r", "%0d");
					actual_val = actual_val.Replace ("\n", "%0a");
				}
			}

			if (null != header) {
				WorkerRequest.SendUnknownResponseHeader (header, actual_val);
			} else {
				WorkerRequest.SendKnownResponseHeader (header_id, actual_val);
			}
		}
Ejemplo n.º 55
0
        // Determines whether or not a given HttpWorkerRequest meets the requirements for "same-origin"
        // as called out in these two documents:
        // - http://tools.ietf.org/html/rfc6454 (Web Origin)
        // - http://tools.ietf.org/html/rfc6455 (WebSockets)
        public static bool IsSameOriginRequest(HttpWorkerRequest workerRequest) {
            string hostHeader = workerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderHost);
            if (String.IsNullOrEmpty(hostHeader)) {
                // RFC 6455 (Sec. 4.1) and RFC 2616 (Sec. 14.23) make the "Host" header mandatory
                return false;
            }

            string secWebSocketOriginHeader = workerRequest.GetUnknownRequestHeader("Origin");
            if (String.IsNullOrEmpty(secWebSocketOriginHeader)) {
                // RFC 6455 (Sec. 4.1) makes the "Origin" header mandatory for browser clients.
                // Phone apps, console clients, and similar non-browser clients aren't required to send the header,
                // but this method isn't intended for those use cases anyway, so we can fail them. (Note: it's still
                // possible for a non-browser app to send the appropriate Origin header.)
                return false;
            }

            // create URI instances from both the "Host" and the "Origin" headers
            Uri hostHeaderUri = null;
            Uri originHeaderUri = null;
            bool urisCreatedSuccessfully = Uri.TryCreate(workerRequest.GetProtocol() + "://" + hostHeader.Trim(), UriKind.Absolute, out hostHeaderUri) // RFC 2616 (Sec. 14.23): "Host" header doesn't contain the scheme, so we need to prepend
                && Uri.TryCreate(secWebSocketOriginHeader.Trim(), UriKind.Absolute, out originHeaderUri);

            if (!urisCreatedSuccessfully) {
                // construction of one of the Uri instances failed
                return false;
            }

            // RFC 6454 (Sec. 4), schemes must be normalized to lowercase. (And for WebSockets we only
            // support HTTP / HTTPS anyway.)
            if (originHeaderUri.Scheme != "http" && originHeaderUri.Scheme != "https") {
                return false;
            }

            // RFC 6454 (Sec. 5), comparisons should be ordinal. The Uri class will automatically
            // fill in the Port property using the default value for the scheme if the provided input doesn't
            // explicitly contain a port number.
            return hostHeaderUri.Scheme == originHeaderUri.Scheme
                && hostHeaderUri.Host == originHeaderUri.Host
                && hostHeaderUri.Port == originHeaderUri.Port;
        }
		string Fill (HttpWorkerRequest wr, bool standard)
		{
			StringBuilder sb = new StringBuilder ();
			
			for (int i = 0; i < HttpWorkerRequest.RequestHeaderMaximum; i++){
				string val = wr.GetKnownRequestHeader (i);
				if (val == null || val == "")
					continue;
				string key = HttpWorkerRequest.GetKnownRequestHeaderName (i);
				AppendKeyValue (sb, key, val, standard);
			}
			string [][] other = wr.GetUnknownRequestHeaders ();
			if (other == null)
				return sb.ToString ();

			for (int i = other.Length; i > 0; ){
				i--;
				AppendKeyValue (sb, other [i][0], other [i][1], standard);
			}

			return sb.ToString ();
		}
 private ProgressWorkerRequest GetProgressWorker(HttpWorkerRequest workerRequest)
 {
     if (this.IsAsyncUploadRequest)
     {
         return new AsyncProgressWorkerRequest(workerRequest, this.Context.Request);
     }
     return new ProgressWorkerRequest(workerRequest, this.Context.Request);
 }
Ejemplo n.º 58
0
		internal HttpResponse (HttpWorkerRequest worker_request, HttpContext context) : this ()
		{
			WorkerRequest = worker_request;
			this.context = context;

			if (worker_request != null && worker_request.GetHttpVersion () == "HTTP/1.1") {
				string gi = worker_request.GetServerVariable ("GATEWAY_INTERFACE");
				use_chunked = (String.IsNullOrEmpty (gi) ||
					!gi.StartsWith ("cgi", StringComparison.OrdinalIgnoreCase));
			} else {
				use_chunked = false;
			}
			writer = new HttpWriter (this);
		}
 public HttpUploadWorkerRequest(HttpWorkerRequest request)
 {
     _httpWorkerRequest = request;
     _inspector = new EntityBodyInspector(this);
 }
Ejemplo n.º 60
0
 private static bool IsIIS7WorkerRequest(HttpWorkerRequest workerRequest)
 {
     return workerRequest.GetType().FullName == IIS7WorkerRequestTypeName;
 }