public object Render(IHttpRequest req, HttpResponseHeader res, XmlDocument doc, string xsl_path)
        {
            XslCache cache;

            _cacheLock.AcquireReaderLock(Timeout.Infinite);
            try {
                if (!_cache.TryGetValue(xsl_path, out cache))
                {
                    cache = new XslCache(xsl_path);
                    LockCookie cookie = _cacheLock.UpgradeToWriterLock(Timeout.Infinite);
                    try {
                        _cache[xsl_path] = cache;
                    } finally {
                        _cacheLock.DowngradeFromWriterLock(ref cookie);
                    }
                }
            } finally {
                _cacheLock.ReleaseReaderLock();
            }

            bool enable_xhtml = (req.Headers.ContainsKey(HttpHeaderNames.Accept) && req.Headers[HttpHeaderNames.Accept].Contains(MIME_XHTML));

            if (enable_xhtml)
            {
                res[HttpHeaderNames.ContentType] = MIME_XHTML + "; charset=utf-8";
            }
            else
            {
                res[HttpHeaderNames.ContentType] = MIME_HTML + "; charset=utf-8";
            }
            return(cache.Transform(doc, !enable_xhtml));
        }
Exemple #2
0
 public string this[HttpResponseHeader header]
 {
     get
     {
         if (!AllowHttpResponseHeader)
         {
             throw new InvalidOperationException(SR.net_headers_rsp);
         }
         return(this[header.GetName()]);
     }
     set
     {
         if (!AllowHttpResponseHeader)
         {
             throw new InvalidOperationException(SR.net_headers_rsp);
         }
         if (_type == WebHeaderCollectionType.HttpListenerResponse)
         {
             if (value != null && value.Length > ushort.MaxValue)
             {
                 throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.net_headers_toolong, ushort.MaxValue));
             }
         }
         this[header.GetName()] = value;
     }
 }
Exemple #3
0
        public void ProcessRequest(HandlerContext context)
        {
            _outputStream = new MemoryStream();
            TextWriter writer = new StreamWriter(_outputStream, Encoding.UTF8);

            writer.WriteLine("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"><title>DomsHttpd test</title></head>");
            writer.WriteLine("<body><h1>Hello world, DomsHttpd!</h1>");
            writer.WriteLine("<br/>request URL is: {0}", context.RequestHeader.Url);
            writer.WriteLine("<br/>user agent: {0}", context.RequestHeader.UserAgent);
            writer.WriteLine("<br/>try <a href=\"/index?id=" + this.GetHashCode().ToString() + "\">change page</a>");
            writer.WriteLine("<br/><form id=\"form1\" method=\"post\" action=\"activepage\">");
            writer.WriteLine("<br/>input some words: <input type=\"text\" name=\"field1\" />");
            writer.WriteLine("<br/><input type=\"submit\" value=\"提交\" />");
            writer.WriteLine("</form>");
            writer.WriteLine("</body></html>");
            writer.Flush();

            _outputStream.Seek(0, SeekOrigin.Begin);

            HttpResponseHeader response = context.ResponseHeader;

            response.Status        = System.Net.HttpStatusCode.OK;
            response.ContentType   = "text/html";
            response.ContentLength = _outputStream.Length;
        }
Exemple #4
0
        public void AllRequestBodyReceived()
        {
            _inputStream.Seek(0, SeekOrigin.Begin);
            TextReader reader  = new StreamReader(_inputStream, Encoding.UTF8);
            string     content = System.Web.HttpUtility.UrlDecode(reader.ReadToEnd());

            reader.Close();

            _outputStream = new MemoryStream();
            TextWriter writer = new StreamWriter(_outputStream, Encoding.UTF8);

            writer.WriteLine("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"><title>DomsHttpd test</title></head>");
            writer.WriteLine("<body><h1>DomsHttpd POST</h1>");
            writer.WriteLine("<br/>referer URL is: {0}", _context.RequestHeader.Referer);
            writer.WriteLine("<br/>the form content length: {0} bytes", _context.RequestHeader.ContentLength);
            writer.WriteLine("<br/>the form content is: <h3>{0}</h3>", System.Web.HttpUtility.HtmlEncode(content));
            writer.WriteLine("</body></html>");
            writer.Flush();

            _outputStream.Seek(0, SeekOrigin.Begin);

            HttpResponseHeader response = _context.ResponseHeader;

            response.Status        = System.Net.HttpStatusCode.OK;
            response.ContentType   = "text/html";
            response.ContentLength = _outputStream.Length;
        }
Exemple #5
0
        public void GenerateCorrectStartLineFromStatusCode(int statusCode, string expectedStartLine)
        {
            var header = new HttpResponseHeader();

            header.StatusCode = statusCode;
            Assert.Equal(expectedStartLine, header.AsPlainText.Split("\r\n")[0]);
        }
Exemple #6
0
 public static void AddHeader(HttpResponseHeader header, string value)
 {
     if (IsRestEnabled)
     {
         WebOperationContext.Current.OutgoingResponse.Headers.Add(header, value);
     }
 }
Exemple #7
0
        static void MockUp(
            out Mock <IHttpRequest> request,
            out Mock <IStaticFileServer> mockStaticFileServer,
            out Mock <IHttpResponse> mockResponse,
            out MemoryStream mockResponseBody,
            out HttpResponseHeader mockResponseHeader)
        {
            var content = Encoding.ASCII.GetBytes("0123456789");

            request = new Mock <IHttpRequest>();
            request
            .Setup(x => x.Header)
            .Returns(new HttpRequestHeader("GET / HTTP/1.1"));

            mockStaticFileServer = new Mock <IStaticFileServer>();
            mockStaticFileServer
            .Setup(x => x.OpenRead("foo.txt"))
            .Returns(new MemoryStream(content));

            mockStaticFileServer
            .Setup(x => x.GetContentTypeHeader("foo.txt"))
            .Returns("text/plain");

            mockResponse       = new Mock <IHttpResponse>();
            mockResponseBody   = new MemoryStream();
            mockResponseHeader = new HttpResponseHeader();
            mockResponse.Setup(x => x.Body).Returns(mockResponseBody);
            mockResponse.Setup(x => x.Header).Returns(mockResponseHeader);
        }
Exemple #8
0
        async Task WontBufferInMemoryIfContentLengthHeaderIsSet()
        {
            var header = new HttpResponseHeader();

            header["content-length"] = "100";

            var mockResponse = new Mock <IHttpResponse>();

            mockResponse.Setup(inst => inst.Header).Returns(header);

            var mockStream = new MemoryStream();
            var body       = new HttpResponseBody(
                mockStream,
                TcpSettings.Default,
                HttpSettings.Default,
                mockResponse.Object
                );

            // Write 99 at the end
            await body.WriteAsync(new byte[] { 0x99 }, 1024);

            // Now verify that the response stream got 99 at the end,
            // as we set the content-length, data must go directly to the response stream
            // and won't buffered in memory.
            Assert.True(mockStream.ToArray().Last() == 0x99);
        }
        public object Render(IHttpRequest req, HttpResponseHeader res, XmlDocument doc, string xsl_path)
        {
            XslCache cache;
            _cacheLock.AcquireReaderLock (Timeout.Infinite);
            try {
                if (!_cache.TryGetValue (xsl_path, out cache)) {
                    cache = new XslCache (xsl_path);
                    LockCookie cookie = _cacheLock.UpgradeToWriterLock (Timeout.Infinite);
                    try {
                        _cache[xsl_path] = cache;
                    } finally {
                        _cacheLock.DowngradeFromWriterLock (ref cookie);
                    }
                }
            } finally {
                _cacheLock.ReleaseReaderLock ();
            }

            bool enable_xhtml = (req.Headers.ContainsKey (HttpHeaderNames.Accept) && req.Headers[HttpHeaderNames.Accept].Contains (MIME_XHTML));
            if (enable_xhtml) {
                res[HttpHeaderNames.ContentType] = MIME_XHTML + "; charset=utf-8";
            } else {
                res[HttpHeaderNames.ContentType] = MIME_HTML + "; charset=utf-8";
            }
            return cache.Transform (doc, !enable_xhtml);
        }
Exemple #10
0
        /// <summary>
        /// Creates the MAFF object method.
        /// </summary>
        /// <param name="oResponseHeader">The message response header.</param>
        /// <param name="oRequestMsg">The request message.</param>
        /// <returns></returns>
        public static BaseObject CreateDataObject(HttpResponseHeader oResponseHeader, HTTPMsg oRequestMsg)
        {
            var oRequestHeader = ((HttpRequestHeader)oRequestMsg.HTTPHeader);
            var sOriginalUrl   = oRequestHeader.RequestURI;

            var sContentType    = ObjectParser.ParseContentType(oResponseHeader);
            var sCharSet        = ObjectParser.ParseCharSet(oResponseHeader);
            var sPathToFileName = ObjectParser.ParsePathToFileName(sOriginalUrl);
            var sFileName       = ObjectParser.ParseFileName(sPathToFileName);
            var listCookiees    = ObjectParser.ParseCookieInformation(oResponseHeader);

            var bGeneratedObject = false;
            var sFileExtension   = string.Empty;

            if (sFileName.Length != 0)
            {
                sFileExtension = ObjectParser.ParseFileExtension(sFileName);

                //If it's Text object without extension, fill with GET uri request
                if (ObjectParser.CheckIfTextObject(sContentType) && sFileExtension == string.Empty)
                {
                    sPathToFileName = sOriginalUrl;
                }
            }

            //Parse GetUrlRequest for Javasrcipt If isnt Root html object
            else if (!sOriginalUrl.Equals("/"))
            {
                _generatedObjectIndex++;
                bGeneratedObject = true;
            }

            if (sContentType.Contains("text/html") && !bGeneratedObject)
            {
                if (ObjectParser.CheckIsValidParentObject(oRequestMsg.PairMessages[0].HTTPContent.Content))
                {
                    return(new ParentObject(sOriginalUrl, sPathToFileName, "index.html", "html", sContentType, oRequestMsg, listCookiees, sCharSet));
                }
                return(new TextObject(sOriginalUrl, sPathToFileName, sFileName, sFileExtension, sContentType, oRequestMsg, listCookiees));
            }

            if (bGeneratedObject)
            {
                //TODO IMPOSSIBLE TO PARSE??? FOR NOW -> Discard packet
                return(ObjectParser.CheckIfScriptObject(sContentType) ?
                       new GeneratedObject(sOriginalUrl, sPathToFileName, sFileName, sFileExtension, sContentType, oRequestMsg, listCookiees, _generatedObjectIndex) : null);
            }

            if (ObjectParser.CheckIfScriptObject(sContentType))
            {
                return(new ScriptObject(sOriginalUrl, sPathToFileName, sFileName, sFileExtension, sContentType, oRequestMsg, listCookiees));
            }

            if (ObjectParser.CheckIfTextObject(sContentType))
            {
                return(new TextObject(sOriginalUrl, sPathToFileName, sFileName, sFileExtension, sContentType, oRequestMsg, listCookiees));
            }

            return(new BaseObject(sOriginalUrl, sPathToFileName, sFileName, sFileExtension, sContentType, oRequestMsg, listCookiees));
        }
 public void ProcessRequest(HandlerContext context)
 {
     //return 'NotImplemented' http status, without response body
     _responseHeader               = context.ResponseHeader;
     _responseHeader.Status        = System.Net.HttpStatusCode.NotImplemented;
     _responseHeader.ContentLength = 0;
 }
Exemple #12
0
 /// <summary>
 /// URLからファイルのキーを取り出す。
 /// 形式としては、/wiki/FileKey/ や /bbs/FileKey/ のほかに、汎用の /FileKey/ に対応し、
 /// FileKeyの後ろにスラッシュが無くURLが終わっている場合は、最後にスラッシュを付与するようにリダイレクトさせる
 /// </summary>
 Key ParseRequestKey(IHttpRequest req, HttpResponseHeader res, out string tailurl)
 {
     tailurl = null;
     string str_key = req.Url.AbsolutePath.Substring (1);
     int pos = str_key.IndexOf ('/');
     if (pos > 0 && pos < 10) {
         // /wiki や /bbs を除去
         str_key = str_key.Substring (pos + 1);
         pos = str_key.IndexOf ('/');
     }
     if (pos < 0) {
         // キーの末尾の / が無いのでリダイレクト
         res[HttpHeaderNames.Location] = req.Url.AbsolutePath + "/";
         throw new HttpException (req.HttpVersion == HttpVersion.Http10 ? HttpStatusCode.Found : HttpStatusCode.SeeOther);
     } else {
         tailurl = str_key.Substring (pos + 1);
         str_key = str_key.Substring (0, pos);
     }
     try {
         if (str_key.Length == (DefaultAlgorithm.ECDomainBytes + 1) * 2)
             return Key.Parse (str_key);
         else if (str_key.Length == (DefaultAlgorithm.ECDomainBytes + 1) * 4 / 3)
             return Key.FromUriSafeBase64String (str_key);
         throw new HttpException (HttpStatusCode.NotFound);
     } catch {
         throw new HttpException (HttpStatusCode.NotFound);
     }
 }
Exemple #13
0
        private static OutputCacheEntry Convert(CachedRawResponse cachedRawResponse, string depKey, string[] fileDependencies)
        {
            List <HeaderElement> headerElements = null;
            ArrayList            headers        = cachedRawResponse._rawResponse.Headers;
            int count = (headers != null) ? headers.Count : 0;

            for (int i = 0; i < count; i++)
            {
                if (headerElements == null)
                {
                    headerElements = new List <HeaderElement>(count);
                }
                HttpResponseHeader h = (HttpResponseHeader)(headers[i]);
                headerElements.Add(new HeaderElement(h.Name, h.Value));
            }

            List <ResponseElement> responseElements = null;
            ArrayList buffers = cachedRawResponse._rawResponse.Buffers;

            count = (buffers != null) ? buffers.Count : 0;
            for (int i = 0; i < count; i++)
            {
                if (responseElements == null)
                {
                    responseElements = new List <ResponseElement>(count);
                }
                IHttpResponseElement elem = buffers[i] as IHttpResponseElement;
                if (elem is HttpFileResponseElement)
                {
                    HttpFileResponseElement fileElement = elem as HttpFileResponseElement;
                    responseElements.Add(new FileResponseElement(fileElement.FileName, fileElement.Offset, elem.GetSize()));
                }
                else if (elem is HttpSubstBlockResponseElement)
                {
                    HttpSubstBlockResponseElement substElement = elem as HttpSubstBlockResponseElement;
                    responseElements.Add(new SubstitutionResponseElement(substElement.Callback));
                }
                else
                {
                    byte[] b      = elem.GetBytes();
                    long   length = (b != null) ? b.Length : 0;
                    responseElements.Add(new MemoryResponseElement(b, length));
                }
            }

            OutputCacheEntry oce = new OutputCacheEntry(
                cachedRawResponse._cachedVaryId,
                cachedRawResponse._settings,
                cachedRawResponse._kernelCacheUrl,
                depKey,
                fileDependencies,
                cachedRawResponse._rawResponse.StatusCode,
                cachedRawResponse._rawResponse.StatusDescription,
                headerElements,
                responseElements
                );

            return(oce);
        }
 public void Remove(HttpResponseHeader header)
 {
     if (!AllowHttpResponseHeader)
     {
         throw new InvalidOperationException(SR.net_headers_rsp);
     }
     this.Remove(header.GetName());
 }
Exemple #15
0
 public int GetInt32(HttpResponseHeader header)
 {
     if (int.TryParse(GetString(header), out int result))
     {
         return(result);
     }
     return(-1);
 }
Exemple #16
0
 public long GetInt64(HttpResponseHeader header)
 {
     if (long.TryParse(GetString(header), out long result))
     {
         return(result);
     }
     return(-1);
 }
Exemple #17
0
 /// <summary>
 /// Parses the cookie information.
 /// </summary>
 /// <param name="oResponseHeader">The response header.</param>
 /// <returns>Return list of Cookies</returns>
 private static List <string> ParseCookieInformation(HttpResponseHeader oResponseHeader)
 {
     if (oResponseHeader.Fields.ContainsKey("Set-Cookie") && oResponseHeader.Fields["Set-Cookie"].Count > 0)
     {
         return(oResponseHeader.Fields["Set-Cookie"]);
     }
     return(new List <string>());
 }
Exemple #18
0
 public void Set(HttpResponseHeader header, string?value)
 {
     if (!AllowHttpResponseHeader)
     {
         throw new InvalidOperationException(SR.net_headers_rsp);
     }
     this.Set(header.GetName(), value);
 }
Exemple #19
0
 // Token: 0x060011AD RID: 4525 RVA: 0x0004A7D8 File Offset: 0x000489D8
 private static string GetHeaderValueFromWebException(WebException e, HttpResponseHeader header)
 {
     if (e == null || e.Response == null)
     {
         return(null);
     }
     return(e.Response.Headers[header]);
 }
 public HttpResponseBase()
 {
     this.Cookies         = new CookieCollection();
     this.ContentType     = "html";
     this.content         = "";
     this.Header          = new HttpResponseHeader();
     this.ContentEncoding = Encoding.UTF8;
 }
Exemple #21
0
        public object Process(IHttpServer server, IHttpRequest req, HttpResponseHeader header)
        {
            header[HttpHeaderNames.ContentType] = "text/plain; charset=UTF-8";
            header[HttpHeaderNames.Date]        = DateTime.UtcNow.ToString("R");

            byte[] raw = Encoding.UTF8.GetBytes("Hello World");
            header[HttpHeaderNames.ContentLength] = raw.Length.ToString();
            return(raw);
        }
        public string this [HttpResponseHeader header] {
            get {
                return(Get(ResponseHeaderToString(header)));
            }

            set {
                Set(header, value);
            }
        }
Exemple #23
0
        public object Process(IHttpServer server, IHttpRequest req, HttpResponseHeader header)
        {
            header[HttpHeaderNames.ContentType] = "text/plain; charset=UTF-8";
            header[HttpHeaderNames.Date] = DateTime.UtcNow.ToString ("R");

            byte[] raw = Encoding.UTF8.GetBytes ("Hello World");
            header[HttpHeaderNames.ContentLength] = raw.Length.ToString ();
            return raw;
        }
Exemple #24
0
 /// <summary>
 /// Parses the type of the HTTP content.
 /// </summary>
 /// <param name="oResponseHeader">The message response header.</param>
 /// <returns>Return type of object</returns>
 private static string ParseContentType(HttpResponseHeader oResponseHeader)
 {
     if (oResponseHeader.Fields.ContainsKey("Content-Type") && oResponseHeader.Fields["Content-Type"].Count > 0)
     {
         var iReplacingIndex = oResponseHeader.Fields["Content-Type"][0].IndexOf(";", StringComparison.Ordinal);
         return(iReplacingIndex > 0 ? oResponseHeader.Fields["Content-Type"][0].Substring(0, iReplacingIndex) : oResponseHeader.Fields["Content-Type"][0]);
     }
     return(string.Empty);
 }
Exemple #25
0
 /// <summary>
 ///     向 HTTP 请求加入 Header。
 /// </summary>
 /// <param name="header">Header 类型。</param>
 /// <param name="value">Header 值。</param>
 public HttpRequest AddHeader(HttpResponseHeader header, String value)
 {
     if (State != HttpRequestState.NothingSpecial)
     {
         throw new InvalidOperationException("不能对传输中的请求进行修改,如果请求已经结束,请使用 HttpRequest.RebuildRequest 方法重构请求。");
     }
     Request.Headers[header] = value;
     return(this);
 }
Exemple #26
0
        private void processRequest(ReceiveHeaderCompleteEventArgs e)
        {
            logger.Debug("{0} process request", _connectionToken.Substring(0, 6));

            if (_lastProcessor != null)
            {
                _lastProcessor.Close();
            }

            HttpRequestHeader requestHeader = (HttpRequestHeader)e.LastReceiveHeader;

            logger.Debug("{0} receive new request: {1}, url: {2}",
                         _connectionToken.Substring(0, 6),
                         requestHeader.Method,
                         requestHeader.Url);

            //check if keep connection alive
            _clientKeepAlive = (requestHeader.Connection == null ||
                                String.Compare(requestHeader.Connection, "keep-alive", true) == 0);

            _lastResponseHeader        = new HttpResponseHeader();
            _lastResponseHeader.Date   = DateTime.Now.ToUniversalTime();
            _lastResponseHeader.Server = HttpServiceControler.SERVER_NAME;

            HandlerContext context = new HandlerContext(
                requestHeader, _lastResponseHeader, _bindEndPoint, _bindEndPointName, _clientIp, _connectionToken);

            _lastProcessor = _processorFactory.CreateProcessor(context);
            _lastProcessor.ProcessRequest(context);

            //request contains body
            if (requestHeader.ContentLength > 0)
            {
                if (_lastProcessor.RequestBodyAcceptable)
                {
                    //continue to receive reqeust body
                    _workStatus = SessionWorkStatus.ReceivingRequestBody;
                    e.TotalPlanReceivingLength = requestHeader.ContentLength;
                }
                else
                {
                    //NOTE::
                    //can not accept request body, because
                    //some http method (GET,HEAD,DELETE) should not contain request body
                    //or POST,PUT access deny.
                    logger.Warn("{0} processor {1} can not accept request body",
                                _connectionToken.Substring(0, 6),
                                _lastProcessor.GetType().Name);
                    Close();
                }
            }
            else
            {
                sendResponse();
            }
        }
Exemple #27
0
 public CometInfo(WaitHandle waitHandle, IHttpRequest req, HttpResponseHeader res, object ctx, DateTime timeout, CometHandler handler)
 {
     _waitHandle = waitHandle;
     _connection = null;
     _req = req;
     _res = res;
     _ctx = ctx;
     _timeout = timeout;
     _handler = handler;
 }
Exemple #28
0
 // Exceptions:
 //   System.ArgumentOutOfRangeException:
 //     The length of value is greater than 65535.
 //
 //   System.InvalidOperationException:
 //     This System.Net.WebHeaderCollection instance does not allow instances of
 //     System.Net.HttpResponseHeader.
 /// <summary>
 /// Gets or sets the specified response header.
 /// </summary>
 /// <param name="header">The response header value.</param>
 /// <returns>A System.String instance containing the specified header.</returns>
 public string this[HttpResponseHeader header] {
     get
     {
         return(_headers[CSharpHeaderToHtmlHeaderConverter.Convert(header)]);
     }
     set
     {
         _headers[CSharpHeaderToHtmlHeaderConverter.Convert(header)] = value;
     }
 }
 public string this [HttpResponseHeader header]
 {
     get
     {
         return(default(string));
     }
     set
     {
     }
 }
Exemple #30
0
        private static CachedRawResponse Convert(OutputCacheEntry oce)
        {
            ArrayList headers = null;

            if ((oce.HeaderElements != null) && (oce.HeaderElements.Count > 0))
            {
                headers = new ArrayList(oce.HeaderElements.Count);
                for (int i = 0; i < oce.HeaderElements.Count; i++)
                {
                    HttpResponseHeader header = new HttpResponseHeader(oce.HeaderElements[i].Name, oce.HeaderElements[i].Value);
                    headers.Add(header);
                }
            }
            ArrayList buffers = null;

            if ((oce.ResponseElements != null) && (oce.ResponseElements.Count > 0))
            {
                buffers = new ArrayList(oce.ResponseElements.Count);
                for (int j = 0; j < oce.ResponseElements.Count; j++)
                {
                    ResponseElement      element  = oce.ResponseElements[j];
                    IHttpResponseElement element2 = null;
                    if (element is FileResponseElement)
                    {
                        HttpContext       current     = HttpContext.Current;
                        HttpWorkerRequest request     = (current != null) ? current.WorkerRequest : null;
                        bool supportsLongTransmitFile = (request != null) && request.SupportsLongTransmitFile;
                        bool isImpersonating          = ((current != null) && current.IsClientImpersonationConfigured) || HttpRuntime.IsOnUNCShareInternal;
                        FileResponseElement element3  = (FileResponseElement)element;
                        element2 = new HttpFileResponseElement(element3.Path, element3.Offset, element3.Length, isImpersonating, supportsLongTransmitFile);
                    }
                    else if (element is MemoryResponseElement)
                    {
                        MemoryResponseElement element4 = (MemoryResponseElement)element;
                        int size = System.Convert.ToInt32(element4.Length);
                        element2 = new HttpResponseBufferElement(element4.Buffer, size);
                    }
                    else
                    {
                        if (!(element is SubstitutionResponseElement))
                        {
                            throw new NotSupportedException();
                        }
                        SubstitutionResponseElement element5 = (SubstitutionResponseElement)element;
                        element2 = new HttpSubstBlockResponseElement(element5.Callback);
                    }
                    buffers.Add(element2);
                }
            }
            else
            {
                buffers = new ArrayList();
            }
            return(new CachedRawResponse(new HttpRawResponse(oce.StatusCode, oce.StatusDescription, headers, buffers, false), oce.Settings, oce.KernelCacheUrl, oce.CachedVaryId));
        }
Exemple #31
0
 public string this[HttpResponseHeader header]
 {
     get
     {
         return(this.Get(WebHeaderCollection.Convert(header)));
     }
     set
     {
         this.Add(header, value);
     }
 }
Exemple #32
0
        public void AsPlainTextPropertyChangesAfterUpdatingStatusCode()
        {
            var header = new HttpResponseHeader();

            // Default header
            Assert.Equal("HTTP/1.1 200 OK", header.AsPlainText.Split("\r\n")[0]);

            // Now change the StatusCode
            header.StatusCode = 400;
            Assert.Equal("HTTP/1.1 400 Bad Request", header.AsPlainText.Split("\r\n")[0]);
        }
 /// <summary>Gets or sets the specified response header.</summary>
 /// <returns>A <see cref="T:System.String" /> instance containing the specified header.</returns>
 /// <param name="header">The response header value.</param>
 /// <exception cref="T:System.ArgumentOutOfRangeException">The length of <paramref name="value" /> is greater than 65535. </exception>
 /// <exception cref="T:System.InvalidOperationException">This <see cref="T:System.Net.WebHeaderCollection" /> instance does not allow instances of <see cref="T:System.Net.HttpResponseHeader" />. </exception>
 /// <PermissionSet>
 ///   <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence" />
 /// </PermissionSet>
 public string this[HttpResponseHeader hrh]
 {
     get
     {
         return(this.Get(this.ResponseHeaderToString(hrh)));
     }
     set
     {
         this.Add(this.ResponseHeaderToString(hrh), value);
     }
 }
Exemple #34
0
 public object Process(IHttpServer server, IHttpRequest req, HttpResponseHeader header)
 {
     object o = _app.Process (server, req, header);
     if (o is string) {
         string[] lines = ((string)o).Split (new string[] {"\r\n"}, StringSplitOptions.None);
         for (int i = 0; i < lines.Length; i ++)
             lines[i] = "*" + lines[i];
         return string.Join ("\r\n", lines);
     } else
         return "";
 }
 public string this[HttpResponseHeader header]
 {
     get
     {
         return(Get(Convert(header)));
     }
     set
     {
         Add(header, value);
     }
 }
Exemple #36
0
 object ProcessNetExitPage(IHttpRequest req, HttpResponseHeader res)
 {
     XmlDocument doc = XmlHelper.CreateEmptyDocument ();
     if (req.HttpMethod == HttpMethod.POST) {
         doc.DocumentElement.SetAttribute ("exit", "exit");
         ThreadPool.QueueUserWorkItem (delegate (object o) {
             Thread.Sleep (500);
             _exitWaitHandle.Set ();
         });
     }
     return _xslTemplate.Render (req, res, doc, Path.Combine (DefaultTemplatePath, "net_exit.xsl"));
 }
Exemple #37
0
 public object Process(IHttpServer server, IHttpRequest req, HttpResponseHeader res)
 {
     switch (req.Url.AbsolutePath) {
     case "/alm_create":
         return ProcessCreateGroup(server, req, res);
     case "/alm_join":
         return ProcessJoinGroup(server, req, res);
     case "/alm_cand":
         return ProcessCandidatePeer(server, req, res);
     }
     return ProcessStaticFile (server, req, res);
 }
Exemple #38
0
        object ProcessManageFile(IHttpRequest req, HttpResponseHeader res)
        {
            string str_key = req.Url.AbsolutePath.Substring (8);
            Key key;
            try {
                if (str_key.Length == (DefaultAlgorithm.ECDomainBytes + 1) * 2)
                    key = Key.Parse (str_key);
                else if (str_key.Length == (DefaultAlgorithm.ECDomainBytes + 1) * 4 / 3)
                    key = Key.FromUriSafeBase64String (str_key);
                else
                    throw new HttpException (HttpStatusCode.NotFound);
            } catch {
                throw new HttpException (HttpStatusCode.NotFound);
            }

            MergeableFileHeader header;
            IMergeableFileWebUIHelper header_helper = null;
            if (req.HttpMethod == HttpMethod.POST && req.HasContentBody ()) {
                header = _node.MMLC.GetMergeableFileHeader (key);
                if (header == null)
                    throw new HttpException (HttpStatusCode.NotFound);
                header_helper = (header.Content as IMergeableFile).WebUIHelper;
                NameValueCollection c = HttpUtility.ParseUrlEncodedStringToNameValueCollection (Encoding.ASCII.GetString (req.GetContentBody (MaxRequestBodySize)), Encoding.UTF8);
                AuthServerInfo[] auth_servers = AuthServerInfo.ParseArray (c["auth"]);
                List<Key> list = new List<Key> ();
                string[] keep_array = c.GetValues ("record");
                if (keep_array != null) {
                    for (int i = 0; i < keep_array.Length; i++) {
                        list.Add (Key.FromUriSafeBase64String (keep_array[i]));
                    }
                }
                IHashComputable new_header_content = header_helper.CreateHeaderContent (c);
                string title = c["title"];
                if (title == null || title.Length == 0 || title.Length > 64)
                    throw new HttpException (HttpStatusCode.InternalServerError);
                MergeableFileHeader new_header = new MergeableFileHeader (key, title, header.Flags, header.CreatedTime, new_header_content, auth_servers);
                _node.MMLC.Manage (new_header, list.ToArray (), null);

                res[HttpHeaderNames.Location] = header_helper.ViewUrl + key.ToUriSafeBase64String ();
                throw new HttpException (req.HttpVersion == HttpVersion.Http10 ? HttpStatusCode.Found : HttpStatusCode.SeeOther);
            }

            List<MergeableFileRecord> records = _node.MMLC.GetRecords (key, out header);
            if (header == null || records == null)
                throw new HttpException (HttpStatusCode.NotFound);
            header_helper = (header.Content as IMergeableFile).WebUIHelper;

            XmlDocument doc = XmlHelper.CreateEmptyDocument ();
            doc.DocumentElement.AppendChild (XmlHelper.CreateMergeableFileElement (doc, header, records.ToArray ()));

            return _xslTemplate.Render (req, res, doc, Path.Combine (DefaultTemplatePath, header_helper.ManagePageXslFileName));
        }
Exemple #39
0
        object ProcessFileList(IHttpRequest req, HttpResponseHeader res)
        {
            XmlDocument doc = XmlHelper.CreateEmptyDocument ();
            XmlElement rootNode = doc.DocumentElement;
            MergeableFileHeader[] headers = _node.MMLC.GetHeaderList ();

            bool include_empty = req.QueryData.ContainsKey ("empty");
            foreach (MergeableFileHeader header in headers) {
                if (header.RecordsetHash.IsZero () && !include_empty)
                    continue;
                rootNode.AppendChild (XmlHelper.CreateMergeableFileElement (doc, header));
            }
            return _xslTemplate.Render (req, res, doc, Path.Combine (DefaultTemplatePath, "list.xsl"));
        }
        /// <summary>
        /// Retrieves a standard HTTP response header from a REST response, if available.
        /// </summary>
        /// <param name="response">The REST response.</param>
        /// <param name="header">The header to retrieve.</param>
        /// <param name="value">Returns the value for <paramref name="header"/>.</param>
        /// <returns><c>true</c> if the specified header is contained in <paramref name="response"/>, otherwise <c>false</c>.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="response"/> is <c>null</c>.</exception>
        public static bool TryGetHeader(this Response response, HttpResponseHeader header, out string value)
        {
            if (response == null)
                throw new ArgumentNullException("response");

            if (response.Headers == null)
            {
                value = null;
                return false;
            }

            WebHeaderCollection collection = new RestWebHeaderCollection(response.Headers);
            value = collection[header];
            return value != null;
        }
        public object Process(IHttpServer server, IHttpRequest req, HttpResponseHeader header)
        {
            string accept_encodings;
            if (!req.Headers.TryGetValue (HttpHeaderNames.AcceptEncoding, out accept_encodings))
                accept_encodings = "";
            bool enableGzip = accept_encodings.Contains ("gzip");
            bool enableDeflate = accept_encodings.Contains ("deflate");
            if (enableDeflate) enableGzip = false;
            if (enableGzip) enableDeflate = false;

            object result = _app.Process (server, req, header);
            if (header.Status != HttpStatusCode.OK || !(enableGzip || enableDeflate) || header.ContainsKey (HttpHeaderNames.ContentEncoding)) {
                return result;
            } else {
                byte[] ret;
                int original_size = -1;
                using (MemoryStream ms = new MemoryStream ())
                using (Stream strm = (enableGzip ? (Stream)new GZipStream (ms, CompressionMode.Compress) : (Stream)new DeflateStream (ms, CompressionMode.Compress))) {
                    if (result is string) {
                        byte[] raw = header.Encoding.GetBytes ((string)result);
                        original_size = raw.Length;
                        strm.Write (raw, 0, raw.Length);
                    } else if (result is byte[]) {
                        byte[] raw = (byte[])result;
                        original_size = raw.Length;
                        strm.Write (raw, 0, raw.Length);
                    } else {
                        return result;
                    }
                    strm.Flush ();
                    strm.Close ();
                    ms.Close ();
                    ret = ms.ToArray ();
                }

                if (ret.Length >= original_size) {
                    _logger.Trace ("Bypass compress middleware ({0} is larger than {1})", ret.Length, original_size);
                    return result;
                }

                header[HttpHeaderNames.ContentLength] = ret.Length.ToString ();
                header[HttpHeaderNames.ContentEncoding] = enableGzip ? "gzip" : "deflate";
                _logger.Trace ("Enable {0} compression, size is {1} to {2}",
                    header[HttpHeaderNames.ContentEncoding], original_size, ret.Length);

                return ret;
            }
        }
Exemple #42
0
 public string this[HttpResponseHeader header]
 {
     get
     {
         if (!AllowHttpResponseHeader)
         {
             throw new InvalidOperationException(SR.net_headers_rsp);
         }
         return this[header.GetName()];
     }
     set
     {
         if (!AllowHttpResponseHeader)
         {
             throw new InvalidOperationException(SR.net_headers_rsp);
         }
         this[header.GetName()] = value;
     }
 }
 public string this[HttpResponseHeader header]
 {
     get
     {
         if (!AllowHttpResponseHeader)
         {
             throw new InvalidOperationException(SR.net_headers_rsp);
         }
         return this[header.GetName()];
     }
     set
     {
         if (!AllowHttpResponseHeader)
         {
             throw new InvalidOperationException(SR.net_headers_rsp);
         }
         if (_type == WebHeaderCollectionType.HttpListenerResponse)
         {
             if (value != null && value.Length > ushort.MaxValue)
             {
                 throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.net_headers_toolong, ushort.MaxValue));
             }
         }
         this[header.GetName()] = value;
     }
 }
Exemple #44
0
		public string this [HttpResponseHeader header] {
			get {
				return Get (ResponseHeaderToString (header));
			}

			set {
				Set (header, value);
			}
		}
Exemple #45
0
		string ResponseHeaderToString (HttpResponseHeader value)
		{
			CheckHeaderConsistency (HeaderInfo.Response);

			switch (value) {
			case HttpResponseHeader.CacheControl:
				return "Cache-Control";
			case HttpResponseHeader.Connection:
				return "Connection";
			case HttpResponseHeader.Date:
				return "Date";
			case HttpResponseHeader.KeepAlive:
				return "Keep-Alive";
			case HttpResponseHeader.Pragma:
				return "Pragma";
			case HttpResponseHeader.Trailer:
				return "Trailer";
			case HttpResponseHeader.TransferEncoding:
				return "Transfer-Encoding";
			case HttpResponseHeader.Upgrade:
				return "Upgrade";
			case HttpResponseHeader.Via:
				return "Via";
			case HttpResponseHeader.Warning:
				return "Warning";
			case HttpResponseHeader.Allow:
				return "Allow";
			case HttpResponseHeader.ContentLength:
				return "Content-Length";
			case HttpResponseHeader.ContentType:
				return "Content-Type";
			case HttpResponseHeader.ContentEncoding:
				return "Content-Encoding";
			case HttpResponseHeader.ContentLanguage:
				return "Content-Language";
			case HttpResponseHeader.ContentLocation:
				return "Content-Location";
			case HttpResponseHeader.ContentMd5:
				return "Content-MD5";
			case HttpResponseHeader.ContentRange:
				return "Content-Range";
			case HttpResponseHeader.Expires:
				return "Expires";
			case HttpResponseHeader.LastModified:
				return "Last-Modified";
			case HttpResponseHeader.AcceptRanges:
				return "Accept-Ranges";
			case HttpResponseHeader.Age:
				return "Age";
			case HttpResponseHeader.ETag:
				return "ETag";
			case HttpResponseHeader.Location:
				return "Location";
			case HttpResponseHeader.ProxyAuthenticate:
				return "Proxy-Authenticate";
			case HttpResponseHeader.RetryAfter:
				return "Retry-After";
			case HttpResponseHeader.Server:
				return "Server";
			case HttpResponseHeader.SetCookie:
				return "Set-Cookie";
			case HttpResponseHeader.Vary:
				return "Vary";
			case HttpResponseHeader.WwwAuthenticate:
				return "WWW-Authenticate";
			default:
				throw new InvalidOperationException ();
			}
		}
Exemple #46
0
		public void Remove (HttpResponseHeader header)
		{
			Remove (ResponseHeaderToString (header));
		}
Exemple #47
0
		public void Set (HttpResponseHeader header, string value)
		{
			Set (ResponseHeaderToString (header), value);
		}
Exemple #48
0
 public void Remove(HttpResponseHeader header) {
     if (!AllowHttpResponseHeader) {
         throw new InvalidOperationException(SR.GetString(SR.net_headers_rsp));
     }
     this.Remove(UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE_HEADER_ID.ToString((int)header));
 }
Exemple #49
0
		public void Add (HttpResponseHeader header, string value)
		{
			Add (ResponseHeaderToString (header), value);
		}
Exemple #50
0
        public string this[HttpResponseHeader header] {
            get {
                if (!AllowHttpResponseHeader) {
                    throw new InvalidOperationException(SR.GetString(SR.net_headers_rsp));
                }

                // Some of these can be mapped to Common Headers.  Other cases can be added as needed for perf.
                if (m_CommonHeaders != null)
                {
                    switch (header)
                    {
                        case HttpResponseHeader.ProxyAuthenticate:
                            return m_CommonHeaders[c_ProxyAuthenticate];

                        case HttpResponseHeader.WwwAuthenticate:
                            return m_CommonHeaders[c_WwwAuthenticate];
                    }
                }

                return this[UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE_HEADER_ID.ToString((int)header)];
            }
            set {
                if (!AllowHttpResponseHeader) {
                    throw new InvalidOperationException(SR.GetString(SR.net_headers_rsp));
                }
                if (m_Type==WebHeaderCollectionType.HttpListenerResponse) {
                    if (value!=null && value.Length>ushort.MaxValue) {
                        throw new ArgumentOutOfRangeException("value", value, SR.GetString(SR.net_headers_toolong, ushort.MaxValue));
                    }
                }
                this[UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE_HEADER_ID.ToString((int)header)] = value;
            }
        }
Exemple #51
0
 internal void SetInternal(HttpResponseHeader header, string value) {
     if (!AllowHttpResponseHeader) {
         throw new InvalidOperationException(SR.GetString(SR.net_headers_rsp));
     }
     if (m_Type==WebHeaderCollectionType.HttpListenerResponse) {
         if (value!=null && value.Length>ushort.MaxValue) {
             throw new ArgumentOutOfRangeException("value", value, SR.GetString(SR.net_headers_toolong, ushort.MaxValue));
         }
     }
     this.SetInternal(UnsafeNclNativeMethods.HttpApi.HTTP_RESPONSE_HEADER_ID.ToString((int)header), value);
 }
Exemple #52
0
		public string this[HttpResponseHeader hrh]
		{
			get
			{
				return Get (ResponseHeaderToString (hrh));
			}

			set
			{
				Add (ResponseHeaderToString (hrh), value);
			}
		}
Exemple #53
0
        object ProcessNetInitPage(IHttpRequest req, HttpResponseHeader res)
        {
            XmlDocument doc = XmlHelper.CreateEmptyDocument ();
            if (req.HttpMethod == HttpMethod.POST && req.HasContentBody ()) {
                Dictionary<string, string> dic = HttpUtility.ParseUrlEncodedStringToDictionary (Encoding.ASCII.GetString (req.GetContentBody (MaxRequestBodySize)), Encoding.UTF8);
                if (dic.ContainsKey ("nodes")) {
                    string[] lines = dic["nodes"].Replace ("\r\n", "\n").Replace ('\r', '\n').Split ('\n');
                    List<EndPoint> list = new List<EndPoint> ();
                    List<string> raw_list = new List<string> ();
                    for (int i = 0; i < lines.Length; i++) {
                        EndPoint ep;
                        lines[i] = lines[i].Trim ();
                        if (lines[i].StartsWith ("%")) {
                            ep = EndPointObfuscator.Decode (lines[i]);
                        } else {
                            ep = Helpers.Parse (lines[i]);
                        }
                        if (ep != null) {
                            list.Add (ep);
                            raw_list.Add (lines[i]);
                        }
                    }
                    if (list.Count > 0) {
                        p2pncs.Threading.ThreadTracer.CreateThread (delegate () {
                            for (int i = 0; i < list.Count; i++) {
                                if (list[i] is IPEndPoint) {
                                    if ((list[i] as IPEndPoint).Address.Equals (_node.GetCurrentPublicIPAddress ()))
                                        continue;
                                    _node.PortOpenChecker.Join (list[i]);
                                }
                            }
                            for (int i = 0; i < list.Count; i++) {
                                if (list[i] is DnsEndPoint) {
                                    IPAddress[] adrs_list = Dns.GetHostAddresses ((list[i] as DnsEndPoint).DNS);
                                    for (int k = 0; k < adrs_list.Length; k++) {
                                        if (adrs_list[k].AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && !adrs_list[k].Equals (_node.GetCurrentPublicIPAddress ())) {
                                            _node.PortOpenChecker.Join (new IPEndPoint (adrs_list[k], (list[i] as DnsEndPoint).Port));
                                        }
                                    }
                                }
                            }
                        }, "WebApp Join Thread").Start ();
                        XmlNode root = doc.DocumentElement.AppendChild (doc.CreateElement ("connected"));
                        for (int i = 0; i < list.Count; i++) {
                            XmlElement element = doc.CreateElement ("endpoint");
                            element.AppendChild (doc.CreateTextNode (raw_list[i].ToString ()));
                            root.AppendChild (element);
                        }
                    }
                } else if (dic.ContainsKey ("ip") && dic.ContainsKey ("port")) {
                    string ip_dns = dic["ip"].Trim ();
                    string port = dic["port"].Trim ();
                    try {
                        if (ip_dns.Length == 0)
                            throw new FormatException ();
                        EndPoint ep = Helpers.Parse (ip_dns + ":" + port);
                        if (ep == null)
                            throw new FormatException ();
                        if (ep is IPEndPoint && (IPAddressUtility.IsPrivate ((ep as IPEndPoint).Address) || (ep as IPEndPoint).Address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork))
                            throw new FormatException ();
                        string encoded = EndPointObfuscator.Encode (ep);
                        doc.DocumentElement.AppendChild (doc.CreateElement ("encoded", null, new XmlNode[] {
                            doc.CreateElement ("source", null, new[] {
                                doc.CreateTextNode (ip_dns + ":" + port)
                            }),
                            doc.CreateTextNode (encoded)
                        }));
                    } catch {
                        doc.DocumentElement.AppendChild (doc.CreateElement ("encoded", null, new[] {
                            doc.CreateElement ("source", null, new[] {
                                doc.CreateTextNode (ip_dns + ":" + port)
                            }),
                            doc.CreateElement ("error")
                        }));
                    }
                }
            }

            string pub_ip = "";
            XmlNode[] encoded_nodes = null;
            if (!IPAddressUtility.IsPrivate (_node.GetCurrentPublicIPAddress ())) {
                pub_ip = _node.GetCurrentPublicIPAddress().ToString ();
                encoded_nodes = new XmlNode[] {
                    doc.CreateTextNode (EndPointObfuscator.Encode (new IPEndPoint (_node.GetCurrentPublicIPAddress (), _node.BindUdpPort)))
                };
            }
            doc.DocumentElement.AppendChild (doc.CreateElement ("ipendpoint", new string[][] {
                    new [] {"ip", pub_ip},
                    new [] {"port", _node.BindUdpPort.ToString ()}
                }, encoded_nodes));

            return _xslTemplate.Render (req, res, doc, Path.Combine (DefaultTemplatePath, "net_init.xsl"));
        }
Exemple #54
0
        object ProcessStaticFile(IHttpRequest req, HttpResponseHeader res)
        {
            string path = req.Url.AbsolutePath;
            if (path.Contains ("/../"))
                throw new HttpException (HttpStatusCode.BadRequest);
            path = path.Replace ('/', Path.DirectorySeparatorChar).Substring (1);
            path = Path.Combine (DefaultStaticFilePath, path);
            if (!File.Exists (path))
                throw new HttpException (HttpStatusCode.NotFound);
            DateTime lastModified = File.GetLastWriteTimeUtc (path);
            string etag = lastModified.Ticks.ToString ("x");
            res[HttpHeaderNames.ETag] = etag;
            res[HttpHeaderNames.LastModified] = lastModified.ToString ("r");
            if (req.Headers.ContainsKey (HttpHeaderNames.IfNoneMatch) && req.Headers[HttpHeaderNames.IfNoneMatch] == etag)
                throw new HttpException (HttpStatusCode.NotModified);

            res[HttpHeaderNames.ContentType] = MIMEDatabase.GetMIMEType (Path.GetExtension (path));
            bool supportGzip = req.Headers.ContainsKey (HttpHeaderNames.AcceptEncoding) && req.Headers[HttpHeaderNames.AcceptEncoding].Contains("gzip");
            string gzip_path = path + ".gz";
            if (supportGzip && File.Exists (gzip_path) && File.GetLastWriteTimeUtc (gzip_path) >= lastModified) {
                path = gzip_path;
                res[HttpHeaderNames.ContentEncoding] = "gzip";
            }
            using (FileStream strm = new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                byte[] raw = new byte[strm.Length];
                strm.Read (raw, 0, raw.Length);
                return raw;
            }
        }
        /// <summary>
        /// Gets or sets the specified response <paramref name="header"/> in the collection.
        /// </summary>
        /// <value>
        /// A <see cref="string"/> that contains the value of the specified response <paramref name="header"/>.
        /// </value>
        /// <param name="header">
        /// A <see cref="HttpResponseHeader"/> that indicates a response header.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// The current <see cref="WebHeaderCollection"/> instance does not allow any of <see cref="HttpResponseHeader"/> values.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///   <para>
        ///   <paramref name="header"/> is a restricted header.
        ///   </para>
        ///   <para>
        ///   -or-
        ///   </para>
        ///   <para>
        ///   <paramref name="value"/> contains invalid characters.
        ///   </para>
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// The length of <paramref name="value"/> is greater than 65535.
        /// </exception>
        public string this[HttpResponseHeader header]
        {
            get {
                return Get (Convert (header));
            }

            set {
                Add (header, value);
            }
        }
 /// <summary>
 /// Sets the specified header to the specified value.
 /// </summary>
 /// <param name="header">
 /// A <see cref="HttpResponseHeader"/> to set.
 /// </param>
 /// <param name="value">
 /// A <see cref="string"/> that contains the value of the header to set.
 /// </param>
 /// <exception cref="InvalidOperationException">
 /// The current <see cref="WebHeaderCollection"/> instance does not allow any of <see cref="HttpResponseHeader"/> values.
 /// </exception>
 /// <exception cref="ArgumentException">
 ///   <para>
 ///   <paramref name="header"/> is a restricted header.
 ///   </para>
 ///   <para>
 ///   -or-
 ///   </para>
 ///   <para>
 ///   <paramref name="value"/> contains invalid characters.
 ///   </para>
 /// </exception>
 /// <exception cref="ArgumentOutOfRangeException">
 /// The length of <paramref name="value"/> is greater than 65535.
 /// </exception>
 public void Set(HttpResponseHeader header, string value)
 {
     DoWithCheckingState (SetWithoutCheckingName, Convert (header), value, true, true);
 }
 /// <summary>
 /// Removes the specified header from the collection.
 /// </summary>
 /// <param name="header">
 /// A <see cref="HttpResponseHeader"/> to remove from the collection.
 /// </param>
 /// <exception cref="InvalidOperationException">
 /// The current <see cref="WebHeaderCollection"/> instance does not allow any of <see cref="HttpResponseHeader"/> values.
 /// </exception>
 /// <exception cref="ArgumentException">
 /// <paramref name="header"/> is a restricted header.
 /// </exception>
 public void Remove(HttpResponseHeader header)
 {
     DoWithCheckingState (RemoveWithoutCheckingName, Convert (header), null, true, false);
 }
Exemple #58
0
        public object Process(IHttpServer server, IHttpRequest req, HttpResponseHeader res)
        {
            string absPath = req.Url.AbsolutePath;
            if (absPath == "/")
                return ProcessMainPage (req, res);
            if (absPath == "/list")
                return ProcessFileList (req, res);
            if (absPath == "/open")
                return ProcessFileOpen (req, res);
            if (absPath == "/net/init")
                return ProcessNetInitPage (req, res);
            if (absPath == "/net/exit")
                return ProcessNetExitPage (req, res);
            if (absPath == "/bbs/new")
                return Process_NewMergeableFilePage (req, res, BBS.BBSWebApp.Instance);
            if (absPath == "/wiki/new")
                return Process_NewMergeableFilePage (req, res, Wiki.WikiWebApp.Instance);
            if (absPath == "/manage" || absPath == "/manage/")
                return ProcessManageTop (req, res);
            if (absPath.StartsWith ("/manage/"))
                return ProcessManageFile (req, res);
            if (absPath == "/statistics")
                return ProcessStatistics (req, res);

            string ext = Path.GetExtension (req.Url.AbsolutePath);
            if (ext.Equals (".css", StringComparison.InvariantCultureIgnoreCase) ||
                ext.Equals (".js", StringComparison.InvariantCultureIgnoreCase) ||
                ext.Equals (".png", StringComparison.InvariantCultureIgnoreCase) ||
                ext.Equals (".jpg", StringComparison.InvariantCultureIgnoreCase)) {
                return ProcessStaticFile (req, res);
            }
            return Process_File (req, res);
        }
 internal static string Convert(HttpResponseHeader header)
 {
     return Convert (header.ToString ());
 }
Exemple #60
0
 object ProcessMainPage(IHttpRequest req, HttpResponseHeader res)
 {
     XmlDocument doc = CreateDocumentWithNetworkState ();
     doc.DocumentElement.SetAttribute ("ver", System.Reflection.Assembly.GetEntryAssembly ().GetName ().Version.ToString ());
     return _xslTemplate.Render (req, res, doc, Path.Combine (DefaultTemplatePath, "main.xsl"));
 }