Exemplo n.º 1
0
        private void getFileHandler(IRequest request, IResponse response)
        {
            if (EnableCrossDomain)
            {
                enableCrossDomain(response);
            }

            if (request.QueryString == null)
            {
                response.Status = System.Net.HttpStatusCode.BadRequest;
                return;
            }

            var type = request.QueryString.Get("type");
            var path = request.QueryString.Get("path");

            if (type == null || path == null)
            {
                response.Status = System.Net.HttpStatusCode.BadRequest;
                return;
            }

            var dirType = 0;
            var pathStr = UnescapeDataString(path.Value);

            if (!int.TryParse(type.Value, out dirType))
            {
                response.Status = System.Net.HttpStatusCode.BadRequest;
                return;
            }

            var dir      = getDir((EDirType)dirType);
            var fullname = dir + pathStr;

            if (!File.Exists(fullname))
            {
                response.Status = System.Net.HttpStatusCode.NotFound;
                return;
            }

            FileInfo finfo = new FileInfo(fullname);

            response.Add(new StringHeader("Content-Disposition", "attachment; filename=" + finfo.Name));
            response.Add(new StringHeader("Content-Length", finfo.Length.ToString()));
            response.ContentType = new ContentTypeHeader(ContentTypeHelper.GetType(finfo.Extension.ToLower()));
            var data = File.ReadAllBytes(fullname);

            response.Body.Write(data, 0, data.Length);
        }
Exemplo n.º 2
0
        public ProcessingResult Process(RequestContext context)
        {
            // URL format : ~/camera/{id}/thumbnail
            Regex r = new Regex(@"^/camera/(\w+)/thumbnail$", RegexOptions.IgnoreCase);
            Match m = r.Match(context.Request.Uri.AbsolutePath.ToLowerInvariant());

            if (!m.Success)
            {
                return(ProcessingResult.Continue);
            }

            string cameraId = m.Groups[1].ToString().ToLowerInvariant();

            byte[] thumbnail = Locator.Get <ICameraManager>().GetCameraThumbnail(cameraId);

            IRequest  request  = context.Request;
            IResponse response = context.Response;

            response.ContentType         = new ContentTypeHeader("image/bmp");
            response.ContentLength.Value = thumbnail.Length;
            response.Add(new DateHeader("Last-Modified", DateTime.Now.ToUniversalTime()));

            var generator = HttpFactory.Current.Get <ResponseWriter>();

            generator.SendHeaders(context.HttpContext, response);
            generator.SendBody(context.HttpContext, new MemoryStream(thumbnail));

            return(ProcessingResult.Abort);
        }
Exemplo n.º 3
0
        public ProcessingResult Process(RequestContext context)
        {
            // URL format : ~/cameras
            Regex r = new Regex(@"^/cameras$", RegexOptions.IgnoreCase);
            Match m = r.Match(context.Request.Uri.AbsolutePath.ToLowerInvariant());

            if (!m.Success)
            {
                return(ProcessingResult.Continue);
            }

            List <Camera> cameras = Locator.Get <ICameraManager>().GetCameras().ToList();
            string        json    = JsonConvert.SerializeObject(cameras);

            IRequest  request  = context.Request;
            IResponse response = context.Response;

            response.ContentType         = new ContentTypeHeader("application/json");
            response.ContentLength.Value = json.Length;
            response.Add(new DateHeader("Last-Modified", DateTime.Now.ToUniversalTime()));

            var generator = HttpFactory.Current.Get <ResponseWriter>();

            generator.SendHeaders(context.HttpContext, response);
            generator.SendBody(context.HttpContext, new MemoryStream(Encoding.Default.GetBytes(json)));

            return(ProcessingResult.Abort);
        }
Exemplo n.º 4
0
        public ProcessingResult Process(RequestContext context)
        {
            // Init our vars.
            IRequest     request  = context.Request;
            IResponse    response = context.Response;
            StreamWriter sw       = new StreamWriter(response.Body);

            sw.AutoFlush = true;
            // Get the page.
            Page   page;
            string uri = request.Uri.AbsolutePath.Remove(0, 1);

            // Check if it exists.
            if (!_pages.ContainsKey(uri))
            {
                return(ProcessingResult.Continue);
            }
            // Handle content.
            page = _pages[uri];
            if ((request.Method == Method.Post ||
                 (request.Method == Method.Get && request.QueryString.Count > 0)) &&
                page is IPostHandler)
            {
                sw.WriteLine(((IPostHandler)page).Post(request.Parameters));
            }
            else
            {
                sw.Write(page.RenderPage(context));
            }
            response.Add(new StringHeader("X-Content-Class", "Dynamic"));
            return(ProcessingResult.SendResponse);
        }
 /// <summary>
 /// Create a challenge header (WWW-authenticate)
 /// </summary>
 /// <param name="response">Response that the authentication header should be added to</param>
 /// <param name="realm">Realm that the user should authenticate in</param>
 /// <returns>WWW-Authenticate header.</returns>
 /// <remarks>
 /// <para>
 /// Scheme can currently be <c>basic</c> or <c>digest</c>. Basic is not very safe, but easier to use.
 /// Digest is quite safe.
 /// </para><para>
 /// </para>
 /// </remarks>
 /// <exception cref="NotSupportedException">Requested scheme is not supported.</exception>
 public void CreateChallenge(IResponse response, string realm)
 {
     foreach (var authenticator in _authenticators.Values)
     {
         var header= authenticator.CreateChallenge(realm);
         response.Add(header.Name, header);
     }
 }
Exemplo n.º 6
0
 /// <summary>
 /// Create a challenge header (WWW-authenticate)
 /// </summary>
 /// <param name="response">Response that the authentication header should be added to</param>
 /// <param name="realm">Realm that the user should authenticate in</param>
 /// <returns>WWW-Authenticate header.</returns>
 /// <remarks>
 /// <para>
 /// Scheme can currently be <c>basic</c> or <c>digest</c>. Basic is not very safe, but easier to use.
 /// Digest is quite safe.
 /// </para><para>
 /// </para>
 /// </remarks>
 /// <exception cref="NotSupportedException">Requested scheme is not supported.</exception>
 public void CreateChallenge(IResponse response, string realm)
 {
     foreach (var authenticator in _authenticators.Values)
     {
         var header = authenticator.CreateChallenge(realm);
         response.Add(header.Name, header);
     }
 }
Exemplo n.º 7
0
        /// <summary>
        /// Process a request.
        /// </summary>
        /// <param name="context">Request information</param>
        /// <returns>What to do next.</returns>
        /// <exception cref="InternalServerException">Failed to find file extension</exception>
        /// <exception cref="ForbiddenException">Forbidden file type.</exception>
        public ProcessingResult Process(RequestContext context)
        {
            Resource resource = _resourceManager.Get(context.Request.Uri.LocalPath);

            if (resource == null)
            {
                return(ProcessingResult.Continue);
            }

            IRequest  request  = context.Request;
            IResponse response = context.Response;

            try
            {
                string fileExtension = Path.GetExtension(request.Uri.AbsolutePath).TrimStart('.');

                ContentTypeHeader header;
                if (!ContentTypes.TryGetValue(fileExtension, out header))
                {
                    return(ProcessingResult.Continue);
                }

                response.ContentType = header;
                //说明: 在某些系统上,总是会出现页面刷不出来的情况,不知道和这个有没有关系?
                //暂时先注释了。
                // Only send file if it has not been modified.
                //var browserCacheDate = request.Headers["If-Modified-Since"] as DateHeader;
                //if (browserCacheDate != null)
                //{
                //    DateTime since = browserCacheDate.Value.ToUniversalTime();
                //    DateTime modified = resource.ModifiedAt;

                //    // Allow for file systems with subsecond time stamps
                //    modified = new DateTime(modified.Year, modified.Month, modified.Day, modified.Hour, modified.Minute, modified.Second, modified.Kind);
                //    if (since >= modified)
                //    {
                //        response.Status = HttpStatusCode.NotModified;
                //        return ProcessingResult.SendResponse;
                //    }
                //}

                using (resource.Stream)
                {
                    response.Add(new DateHeader("Last-Modified", resource.ModifiedAt));

                    // Send response and tell server to do nothing more with the request.
                    SendFile(context.HttpContext, response, resource.Stream);
                    return(ProcessingResult.Abort);
                }
            }
            catch (FileNotFoundException err)
            {
                throw new InternalServerException("Failed to process file '" + request.Uri + "'.", err);
            }
        }
Exemplo n.º 8
0
        public ProcessingResult Process(RequestContext context)
        {
            // Init our vars.
            IRequest  request  = context.Request;
            IResponse response = context.Response;

            // Get the page.
            byte[] resource;
            string uri = request.Uri.AbsolutePath.Remove(0, 1);

            // Check if it exists.
            if (!File.Exists("Data/static/" + uri))
            {
                return(ProcessingResult.Continue);
            }
            resource = File.ReadAllBytes("Data/static/" + uri);
            response.Add(new StringHeader("Cache-Control", "max-age=28800"));
            response.Add(new StringHeader("X-Content-Class", "Static"));
            response.Body.Write(resource, 0, resource.Length);
            response.ContentType = new ContentTypeHeader(MIMEAssistant.GetMIMEType("Data/static/" + uri));
            return(ProcessingResult.SendResponse);
        }
Exemplo n.º 9
0
        private void WriteResponseHeaders(IResponse originalResponse, HttpWebResponse response)
        {
            foreach (string headerName in response.Headers.AllKeys)
            {
                if (IsNotSettableHeader(headerName))
                {
                    continue;
                }

                /*IHeader header = originalResponse.Headers[headerName];
                 * if(header != null)
                 *  header.HeaderValue = ProcessResponseValue(response.Headers[headerName]);
                 * else*/
                originalResponse.Add(new StringHeader(headerName, ProcessResponseValue(response.Headers[headerName])));
            }
        }
Exemplo n.º 10
0
        public ProcessingResult Process(RequestContext context)
        {
            IRequest  request  = context.Request;
            IResponse response = context.Response;
            string    path     = request.Uri.AbsolutePath;

            path = Uri.UnescapeDataString(path);
            Debug.WriteLine("Request for: " + path);
            try
            {
                response.Status      = System.Net.HttpStatusCode.BadRequest;
                response.ContentType = new HttpServer.Headers.ContentTypeHeader("text/plain");

                var item = path.Remove(0, 1);

                Trace.WriteLine("HTTP item: " + item);
                if (Program.LocalFileStorage.ContainsKey(item))
                {
                    try
                    {
                        var file = Program.LocalFileStorage[item];
                        Trace.WriteLine("HTTP request for file " + file);
                        response.Add(new StringHeader("Content-Disposition", "attachment; filename=\"" + Path.GetFileName(file) + "\""));
                        response.Status      = System.Net.HttpStatusCode.OK;
                        response.ContentType = new HttpServer.Headers.ContentTypeHeader(Mime.MimeFromRegistry(Path.GetExtension(file)));
                        using (var fo = File.OpenRead(file))
                        {
                            SendFile(context.HttpContext, response, fo);
                        }
                    }
                    catch (Exception ex)
                    {
                        response.Status = System.Net.HttpStatusCode.NotFound;
                        Trace.WriteLine(ex);
                        // SendFile(context.HttpContext, response, "File Not Found: " + ex.Message);
                    }
                    return(ProcessingResult.Abort); // don't give invalid request, the user has "authenticated"
                }
            }
            catch (Exception ex)
            {
                SendFile(context.HttpContext, response, ex.Message);
            }
            SendFile(context.HttpContext, response, "Bad Request");

            return(ProcessingResult.Abort);
        }
Exemplo n.º 11
0
 private void ProcessHeaders(IResponse response, Dictionary <string, string> headers)
 {
     foreach (var item in headers)
     {
         if (item.Key.Equals("status", StringComparison.OrdinalIgnoreCase))
         {
             SetStatusCode(response, item.Key, item.Value);
         }
         else if (item.Key.Equals("content-type", StringComparison.OrdinalIgnoreCase))
         {
             response.ContentType = new ContentTypeHeader(item.Value);
         }
         else
         {
             response.Add(new StringHeader(item.Key, item.Value));
         }
     }
 }
Exemplo n.º 12
0
        /// <summary>
        /// 消息解析器解析出一个请求消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnRequest(object sender, FactoryRequestEventArgs e)
        {
            _context = this;

            // 根据请求消息内容生成响应消息
            Response = HttpFactory.Current.Get <IResponse>(this, e.Request);
            Logger.Debug("Received '" + e.Request.Method + " " + e.Request.Uri.PathAndQuery + "' from " + Socket.RemoteEndPoint);

            // 如果请求连接中设置了保活
            if (e.Request.Connection != null && e.Request.Connection.Type == ConnectionType.KeepAlive)
            {
                Response.Add(new StringHeader("Keep-Alive", "timeout=5, max=100"));

                // 刷新计时器
                if (_keepAlive != null)
                {
                    _keepAlive.Change(_keepAliveTimeout, _keepAliveTimeout);
                }
            }

            // 记录请求消息
            Request = e.Request;

            // 通知处理请求
            CurrentRequestReceived(this, new RequestEventArgs(this, e.Request, Response));
            RequestReceived(this, new RequestEventArgs(this, e.Request, Response));

            // 如果请求连接中设置了保活,记录请求处理的超时时间
            if (Response.Connection.Type == ConnectionType.KeepAlive)
            {
                if (_keepAlive == null)
                {
                    _keepAlive = new Timer(OnKeepAliveTimeout, null, _keepAliveTimeout, _keepAliveTimeout);
                }
            }

            // 通知请求处理完毕
            RequestCompleted(this, new RequestEventArgs(this, e.Request, Response));
            CurrentRequestCompleted(this, new RequestEventArgs(this, e.Request, Response));
        }
Exemplo n.º 13
0
        public ProcessingResult Process(RequestContext context)
        {
            // URL format : ~/login
            Regex r = new Regex(@"^/login$", RegexOptions.IgnoreCase);
            Match m = r.Match(context.Request.Uri.AbsolutePath.ToLowerInvariant());

            if (!m.Success)
            {
                return(ProcessingResult.Continue);
            }

            IRequest  request  = context.Request;
            IResponse response = context.Response;

            var assembly     = Assembly.GetExecutingAssembly();
            var resourceName = Assembly.GetExecutingAssembly().GetName().Name + @".html.cameras.html";

            string html;

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
                using (StreamReader reader = new StreamReader(stream))
                {
                    html = reader.ReadToEnd();
                }

            response.ContentType         = new ContentTypeHeader("txt/html");
            response.ContentLength.Value = html.Length;
            response.Add(new DateHeader("Last-Modified", DateTime.Now.ToUniversalTime()));

            var generator = HttpFactory.Current.Get <ResponseWriter>();

            generator.SendHeaders(context.HttpContext, response);
            generator.SendBody(context.HttpContext, new MemoryStream(Encoding.Default.GetBytes(html)));

            return(ProcessingResult.Abort);
        }
Exemplo n.º 14
0
    /// <summary>
    /// 消息解析器解析出一个请求消息
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void OnRequest(object sender, FactoryRequestEventArgs e)
    {
      _context = this;

      // 根据请求消息内容生成响应消息
      Response = HttpFactory.Current.Get<IResponse>(this, e.Request);
      Logger.Debug("Received '" + e.Request.Method + " " + e.Request.Uri.PathAndQuery + "' from " + Socket.RemoteEndPoint);

      // 如果请求连接中设置了保活
      if (e.Request.Connection != null && e.Request.Connection.Type == ConnectionType.KeepAlive)
      {
        Response.Add(new StringHeader("Keep-Alive", "timeout=5, max=100"));

        // 刷新计时器
        if (_keepAlive != null)
          _keepAlive.Change(_keepAliveTimeout, _keepAliveTimeout);
      }

      // 记录请求消息
      Request = e.Request;

      // 通知处理请求
      CurrentRequestReceived(this, new RequestEventArgs(this, e.Request, Response));
      RequestReceived(this, new RequestEventArgs(this, e.Request, Response));

      // 如果请求连接中设置了保活,记录请求处理的超时时间
      if (Response.Connection.Type == ConnectionType.KeepAlive)
      {
        if (_keepAlive == null)
          _keepAlive = new Timer(OnKeepAliveTimeout, null, _keepAliveTimeout, _keepAliveTimeout);
      }

      // 通知请求处理完毕
      RequestCompleted(this, new RequestEventArgs(this, e.Request, Response));
      CurrentRequestCompleted(this, new RequestEventArgs(this, e.Request, Response));
    }
Exemplo n.º 15
0
 private void enableCrossDomain(IResponse response)
 {
     response.Add(new StringHeader("Access-Control-Allow-Origin", "*"));
 }
Exemplo n.º 16
0
        private void WriteResponseHeaders(IResponse originalResponse, HttpWebResponse response)
        {
            foreach(string headerName in response.Headers.AllKeys)
            {
                if(IsNotSettableHeader(headerName))
                    continue;

                /*IHeader header = originalResponse.Headers[headerName];
                if(header != null)
                    header.HeaderValue = ProcessResponseValue(response.Headers[headerName]);
                else*/
                    originalResponse.Add(new StringHeader(headerName, ProcessResponseValue(response.Headers[headerName])));
            }
        }
        /// <summary>
        /// Process a request.
        /// </summary>
        /// <param name="context">Request information</param>
        /// <returns>What to do next.</returns>
        /// <exception cref="InternalServerException">Failed to find file extension</exception>
        /// <exception cref="ForbiddenException">Forbidden file type.</exception>
        public ProcessingResult Process(RequestContext context)
        {
            IRequest  request  = context.Request;
            IResponse response = context.Response;

            try
            {
                // only handle GET and HEAD
                if (!request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase) &&
                    !request.Method.Equals("HEAD", StringComparison.OrdinalIgnoreCase))
                {
                    return(ProcessingResult.Continue);
                }

                if (_fileService.IsDirectory(request.Uri))
                {
                    return(ProcessingResult.Continue);
                }

                var header = request.Headers["If-Modified-Since"];
                var time   = header != null
                               ? DateTime.ParseExact(header.HeaderValue, "R", CultureInfo.InvariantCulture)
                               : DateTime.MinValue;

                DateTime since       = time.ToUniversalTime();
                var      fileContext = new FileContext(context.Request, since);
                _fileService.GetFile(fileContext);
                if (!fileContext.IsFound)
                {
                    response.Status = HttpStatusCode.NotFound;
                    return(ProcessingResult.SendResponse);
                }

                if (!fileContext.IsModified)
                {
                    response.Status = HttpStatusCode.NotModified;
                    return(ProcessingResult.SendResponse);
                }

                var mimeType = MimeTypeProvider.Instance.Get(fileContext.Filename);
                if (mimeType == null)
                {
                    response.Status = HttpStatusCode.UnsupportedMediaType;
                    return(ProcessingResult.SendResponse);
                }

                if (mimeType.Equals("application/x-httpd-cgi"))
                {
                    // CGI module handles the request
                    return(ProcessingResult.Continue);
                }

                response.Status      = HttpStatusCode.OK;
                response.ContentType = new ContentTypeHeader(mimeType);
                response.Add(new DateHeader("Last-Modified", fileContext.LastModifiedAtUtc));

                IHeader acceptEncodingHeader = request.Headers["Accept-Encoding"];

                if (_enableGzip &&
                    fileContext.FileStream.Length > 5000 &&
                    acceptEncodingHeader != null &&
                    acceptEncodingHeader.HeaderValue.Contains("gzip") &&
                    IsGzipCandidate(fileContext.Filename))
                {
                    // Compress file (if larger than 5kb)
                    var stream = GetGzipStream(fileContext.FileStream);

                    response.Add(new StringHeader("Content-Encoding", "gzip"));

                    SendFile(context.HttpContext, response, stream);
                }
                else
                {
                    SendFile(context.HttpContext, response, fileContext.FileStream);
                }

                // Release file stream
                fileContext.FileStream.Close();

                return(ProcessingResult.Abort);
            }
            catch (FileNotFoundException err)
            {
                throw new InternalServerException("Failed to process file '" + request.Uri + "'.", err);
            }
        }