Beispiel #1
0
        public void ProcessRequest(Request request)
        {
            string workDir = Directory.GetCurrentDirectory();//aktuelles verzeichnis bestimmen
            byte[] responseBody;

            if (request.Url.Path == "/")
                workDir = Path.Combine(workDir, "index.html");
            else
                workDir = workDir + request.Url.Path;//vollen Pfad zur angeforderten Datei zusammensetzen. Annahme, dass
            //Datei im selben Verzeichnis wie die Exec liegt.
            Response resp = new Response(request, request._socket);
            if (File.Exists(workDir)) //prüfen ob datei existiert bzw. im angegebenen pfad ist
            {
                using (var fs = File.OpenRead(workDir))
                {
                    long count = fs.Length;

                    responseBody = new byte[count];

                    fs.Read(responseBody, 0, (int)count);

                    resp.sendResponse(request.HttpVersion, getMIMEType(request.Url.Extension), (int)count, " 200 OK", responseBody);

                }
            }
            else //wenn nicht, error message an den browser senden
            {
                string errorMessage = "<h2> Error: File not found! </h2>";
                resp.sendResponse(request.HttpVersion, "", errorMessage.Length, " 404 NOT FOUND", Encoding.ASCII.GetBytes(errorMessage));

            }
        }
Beispiel #2
0
        public void Handle(object threadContext)
        {
            Init();

            while (Connected)
            {
                // read request
                string line, requestText = "";
                while ((line = Reader.ReadLine()) != "")
                    requestText += line + "\n";

                Request req = new Request();
                req.Parse(requestText);

                Response res = Router.Handle(req);

                // keep connection alive if requested
                if (req.Header.ContainsKey("Connection") && req.Header["Connection"] == "keep-alive")
                {
                    res.Header.Connection = "keep-alive";
                    Connected = true;
                }
                else
                {
                    res.Header.Connection = "close";
                    Connected = false;
                }

                // put the stuff in the stream
                Writer.Write(res.GetText());
                Writer.Flush();
            }
        }
Beispiel #3
0
 public bool CanHandle(Request request)
 {
     if (request.Url.Extension != "")
         return true;
     else
         return false;
 }
Beispiel #4
0
        /// <summary>
        /// Handles the given request and routes it to the fitting handler.
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public Response Handle(Request req)
        {
            Response res = new Response();
            // Checks if the method is implemented (routed)
            if (!HandledRoutes.ContainsKey(req.Method))
            {
                res.Header.StatusCode = "501 Not Implemented";
                res.Header.ContentType = "text/plain; encoding=utf-8";
                res.Write("501 Not Implemented\n");
                return res;
            }

            List<KeyValuePair<string, Route>> possibleRoutes = HandledRoutes[req.Method];
            foreach (KeyValuePair<string, Route> r in possibleRoutes)
            {
                if (Matches(r.Key, req.Path))
                {
                    try
                    {
                        if (r.Value(req, res))
                            return res;
                    }
                    catch (Exception e)
                    {
                        res.Header.StatusCode = "500 Internal Server Error";
                        res.Header.ContentType = "text/plain; encoding=utf-8";
                        res.ClearContent();
                        res.Write("500 Internal Server Error\n");
                        res.Write($"Route {r.Key} threw error: {e.Message}\n");
                        return res;
                    }
                }
            }
            return res;
        }
Beispiel #5
0
 public void ParseRequest_longdata()
 {
     string data = "GET /getTemperature/2013/12/03 HTTP/1.1";
     string expected = "GET";
     Request rq = new Request(data);
     rq.parseRequest(data);
     String[] tokens = data.Split(' ');
     string actual = tokens[0].ToUpper();
     Assert.AreEqual(expected, actual, "Stimmt");
 }
Beispiel #6
0
        public void handleGETRequest_Favicon()
        {
            String http_url = "favicon.ico";
            bool expected = false;

            Request newRequest = new Request(http_url);
            newRequest.handleGETRequest();

            bool actual = newRequest.favicon;
            Assert.AreEqual(expected, actual, "Stimmt nicht");
        }
Beispiel #7
0
 public void HandleRequest(Request requ)
 {
     foreach (IPlugin plugin in PluginManager.getInstance().PluginList)
         {
             if (plugin.CanHandle(requ))
             {
                 plugin.ProcessRequest(requ);
                 break;
             }
         }
 }
Beispiel #8
0
        public void handleGETRequest_Favicon()
        {
            String http_url = "GET /favicon.ico HTTP/1.1";
            bool expected = true;

            Request newRequest = new Request(http_url);
            newRequest.handleGETRequest();

            bool actual = newRequest.favicon;
            Assert.AreEqual(expected, actual, "Stimmt");
        }
Beispiel #9
0
        public void PluginName_true()
        {
            string http_url = "/StaticFile";
            string expected = "StaticFile";

            Request rq = new Request(http_url);
            rq.handleGETRequest();

            string[] split = Regex.Split(http_url, "/");
            string actual = split[1];
            Assert.AreEqual(expected, actual, "Pluginname richtig");
        }
Beispiel #10
0
        string _timeFmt = "ddd M dd hh:mm:ss yyyy"; //(SSI用)日付書式文字列

        #endregion Fields

        #region Constructors

        public Ssi(Kernel kernel, Logger logger, Conf conf, SockTcp tcpObj, Request request, Header recvHeader)
        {
            _kernel = kernel;
            _logger = logger;
            //_oneOption = oneOption;
            _conf = conf;

            //子プロセスでCGIを実行する場合に使用する
            _sockTcp = tcpObj;
            _request = request;
            _recvHeader = recvHeader;
        }
Beispiel #11
0
        public void processHttp()
        {
            var request = new Request(s);

            if (request.Parse())
            {

                HandleRequest(request);

            }

            s.Close();
        }
Beispiel #12
0
        public bool CreateFromIndex(Request request,string path)
        {
            //Ver5.0.0-a20 �G���R�[�h�̓I�v�V�����ݒ�ɏ]��
            Encoding encoding;
            string charset;
            if (!GetEncodeOption(out encoding,out charset)) {
                return false;
            }

            //���X�|���X�p�̐��`�擾
            var lines = Inet.GetLines((string)_conf.Get("indexDocument"));
            if (lines.Count == 0) {
                _logger.Set(LogKind.Error,null, 26, "");
                return false;
            }

            //�o�b�t�@�̏�����
            var sb = new StringBuilder();

            //������uri��o�͗p�ɃT�C�^�C�Y����i�N���X�T�C�g�X�N���v�e�B���O�Ή��j
            var uri = Inet.Sanitize(request.Uri);

            //���`��P�s�“ǂݍ���ŃL�[���[�h�ϊ������̂��o�͗p�o�b�t�@�ɒ~�ς���
            foreach(string line in lines){
                var str = line;
                if (str.IndexOf("<!--$LOOP-->") == 0) {
                    str = str.Substring(12);//�P�s�̐��^

                    //�ꗗ���̎擾(�P�s����LineData)
                    var lineDataList = new List<LineData>();
                    var dir = request.Uri;
                    if (1 < dir.Length) {
                        if (dir[dir.Length - 1] != '/')
                            dir = dir + '/';
                    }
                    //string dirStr = dir.Substring(0,dir.LastIndexOf('/'));
                    if (dir != "/") {
                        //string parentDirStr = dirStr.Substring(0,dirStr.LastIndexOf('/') + 1);
                        //lineDataList.Add(new LineData(parentDirStr,"Parent Directory","&lt;DIR&gt;","-"));
                        lineDataList.Add(new LineData("../","Parent Directory","&lt;DIR&gt;","-"));
                    }

                    var di = new DirectoryInfo(path);
                    foreach (var info in di.GetDirectories("*.*")) {
                        var href = Uri.EscapeDataString(info.Name) + '/';
                        lineDataList.Add(new LineData(href, info.Name, "&lt;DIR&gt;", "-"));
                    }
                    foreach (var info in di.GetFiles("*.*")) {
                        string href = Uri.EscapeDataString(info.Name);
                        lineDataList.Add(new LineData(href, info.Name, info.LastWriteTime.ToString(), info.Length.ToString()));
                    }

                    //�ʒu���𐗌`�Ő��`����StringBuilder�ɒlj�����
                    foreach (var lineData in lineDataList)
                        sb.Append(lineData.Get(str) + "\r\n");

                } else {//�ꗗ�s�ȊO�̏���
                    str = Util.SwapStr("$URI",uri,str);
                    str = Util.SwapStr("$SERVER",Define.ApplicationName(),str);
                    str = Util.SwapStr("$VER", request.Ver, str);
                    sb.Append(str + "\r\n");
                }
            }
            _body.Set(encoding.GetBytes(sb.ToString()));
            _sendHeader.Replace("Content-Length",_body.Length.ToString());
            _sendHeader.Replace("Content-Type",string.Format("text/html;charset={0}",charset));
            return true;
        }
Beispiel #13
0
        public bool CreateFromErrorCode(Request request,int responseCode)
        {
            //Ver5.0.0-a20 �G���R�[�h�̓I�v�V�����ݒ�ɏ]��
            Encoding encoding;
            string charset;
            if (!GetEncodeOption(out encoding,out charset)) {
                return false;
            }

            //���X�|���X�p�̐��`�擾
            var lines = Inet.GetLines((string)_conf.Get("errorDocument"));
            if (lines.Count == 0) {
                _logger.Set(LogKind.Error,null,25,"");
                return false;
            }

            //�o�b�t�@�̏�����
            var sb = new StringBuilder();

            //������uri��o�͗p�ɃT�C�^�C�Y����i�N���X�T�C�g�X�N���v�e�B���O�Ή��j
            var uri = Inet.Sanitize(request.Uri);

            //���`��P�s�“ǂݍ���ŃL�[���[�h�ϊ������̂��o�͗p�o�b�t�@�ɒ~�ς���
            foreach(string line in lines){
                string str = line;
                str = Util.SwapStr("$MSG", request.StatusMessage(responseCode), str);
                str = Util.SwapStr("$CODE", responseCode.ToString(), str);
                str = Util.SwapStr("$SERVER", Define.ApplicationName(), str);
                str = Util.SwapStr("$VER", request.Ver, str);
                str = Util.SwapStr("$URI", uri, str);
                sb.Append(str + "\r\n");
            }
            _body.Set(encoding.GetBytes(sb.ToString()));
            _sendHeader.Replace("Content-Length",_body.Length.ToString());
            _sendHeader.Replace("Content-Type",string.Format("text/html;charset={0}",charset));
            return true;
        }
        /// <summary>
        /// Delegate to process web requests
        /// </summary>
        /// <param name="request">Request item received from Listener</param>
        /// <remarks>Very much WIP</remarks>
        private static void WebCommandReceived(Request _request)
        {
            try
            {
                string requestString = _request.BaseUri.Substring(1);	// skip leading slash

                // check ResponseHandlerList for matching response
                WebResponseEventHandler handler = (WebResponseEventHandler)m_eventHandlerList[requestString];
                if (handler != null)
                {
                    // Call the matched handler with the Request object.
                    // <WIP>
                    /*handler(new DictionaryEntry(_request.Querystring["relay"].ToString(),
                        _request.Querystring["status"].ToString()));*/
                    // </WIP>
                }
                else
                {
                    throw new NullReferenceException("No matching Response Handler found");
                }
                /*
                string content = HtmlGeneral.HtmlStart + "<h1>Success</h1>" + HtmlGeneral.HtmlEnd;
                string header = HttpGeneral.GetHttpHeader(content.Length, "text/html", 10);
                result = header + content;
                Debug.Print("\t\trequest.URI="+request.Uri);
                 * */
            }
            catch (Exception ex)
            {
                Debug.Print(ex.StackTrace);
                /*
                string content = HtmlGeneral.HtmlStart + "<h1>500 server error.</h1>" + "<h3>Uri: " + request.Uri + "</h3>";
                content += "<p>Error: " + ex.StackTrace + "</p>" + HtmlGeneral.HtmlEnd;
                string header = HttpGeneral.Get500Header(content.Length);
                result = header + content;
                 * */
            }
        }
Beispiel #15
0
        //public Env(Kernel kernel, Request request, Header recvHeader, System.Net.IPAddress remoteAddress, string remoteHostName, string fileName) {
        public Env(Kernel kernel,Conf conf, Request request, Header recvHeader,SockTcp tcpObj,string fileName)
        {
            //Ver5.6.2
            var documetnRoot = (string)conf.Get("documentRoot");
            _ar.Add(new OneEnv("DOCUMENT_ROOT",documetnRoot));
            var serverAdmin = (string)conf.Get("serverAdmin");
            _ar.Add(new OneEnv("SERVER_ADMIN", serverAdmin));

            _ar.Add(new OneEnv("SystemRoot", Environment.GetEnvironmentVariable("SystemRoot")));
            _ar.Add(new OneEnv("Path", Environment.GetEnvironmentVariable("Path")));
            //Ver5.6.2追加
            _ar.Add(new OneEnv("COMSPEC", Environment.GetEnvironmentVariable("COMSPEC")));
            _ar.Add(new OneEnv("PATHEXT", Environment.GetEnvironmentVariable("PATHEXT")));
            _ar.Add(new OneEnv("WINDIR", Environment.GetEnvironmentVariable("windir")));

            _ar.Add(new OneEnv("SERVER_SOFTWARE", string.Format("{0}/{1} (Windows)", Define.ApplicationName(), kernel.Ver.Version())));

            _ar.Add(new OneEnv("REQUEST_METHOD", request.Method.ToString().ToUpper()));
            _ar.Add(new OneEnv("REQUEST_URI", request.Uri));
            if (request.Uri == "/") { // ルートディレクトリか?
                _ar.Add(new OneEnv("SCRIPT_NAME", Path.GetFileName(fileName)));  // Welcomeファイルを設定する
            } else { // URIで指定されたCGIを設定する
                _ar.Add(new OneEnv("SCRIPT_NAME", request.Uri));
            }
            _ar.Add(new OneEnv("SERVER_PROTOCOL", request.Ver));
            _ar.Add(new OneEnv("QUERY_STRING", request.Param));

            _ar.Add(new OneEnv("REMOTE_HOST", tcpObj.RemoteHostname));
            //Ver5.6.2
            //ar.Add(new OneEnv("REMOTE_ADDR", tcpObj.RemoteAddr.IPAddress.ToString()));
            var addr = (tcpObj.RemoteAddress != null) ? tcpObj.RemoteAddress.Address.ToString() : "";
            _ar.Add(new OneEnv("REMOTE_ADDR", addr));

            //Ver5.6.2
            int port = (tcpObj.RemoteAddress!=null)?tcpObj.RemoteAddress.Port:0;
            _ar.Add(new OneEnv("REMOTE_PORT", port.ToString()));
            port = (tcpObj.LocalAddress != null) ? tcpObj.LocalAddress.Port : 0;
            _ar.Add(new OneEnv("SERVER_PORT", port.ToString()));
            addr = (tcpObj.LocalAddress != null) ? tcpObj.LocalAddress.Address.ToString() : "";
            _ar.Add(new OneEnv("SERVER_ADDR", addr));

            //Ver5.6.2
            SetEnvValue(recvHeader, _ar, "accept-charset", "HTTP_ACCEPT_CHARSET");
            SetEnvValue(recvHeader, _ar, "accept-encoding", "HTTP_ACCEPT_ENCODING");
            SetEnvValue(recvHeader, _ar, "accept-language", "HTTP_ACCEPT_LANGUAGE");

            SetEnvValue(recvHeader, _ar, "User-Agent", "HTTP_USER_AGENT");
            SetEnvValue(recvHeader, _ar, "Content-Type", "CONTENT_TYPE");
            SetEnvValue(recvHeader, _ar, "host", "SERVER_NAME");

            SetEnvValue(recvHeader, _ar, "Content-Length", "CONTENT_LENGTH");
            SetEnvValue(recvHeader, _ar, "AuthUser", "REMOTE_USER");

            //PathInfo/PathTranslatedの取得と環境変数へのセットについて再考察
            SetEnvValue(recvHeader, _ar, "PathInfo", "PATH_INFO");
            SetEnvValue(recvHeader, _ar, "PathTranslated", "PATH_TRANSLATED");

            _ar.Add(new OneEnv("SCRIPT_FILENAME", fileName));

            //HTTP_で環境変数をセットしないヘッダの(除外)リスト
            var exclusionList = new List<string>{
                "accept-charset",
                "accept-encoding",
                "accept-language",
                "authorization",
                "content-length",
                "content-type",
                "date",
                "expires",
                "from",
                "host",
                "if-modified-since",
                "if-match",
                "if-none-match",
                "if-range",
                "if-unmodified-since",
                "last-modified",
                "pragma",
                "range",
                "remote-user",
                "remote-host-wp",
                "transfer-encoding",
                "upgrade",
                "user-agent"
            };
            //Ver5.6.2
            //exclusionList.Add("connection");

            //DEBUG
            //recvHeader.Append("accept", Encoding.ASCII.GetBytes("ABC"));
            foreach (var line in recvHeader) {
                //取得したタグが除外リストにヒットしない場合
                //HTTP_を付加して環境変数にセットする
                if (exclusionList.IndexOf(line.Key.ToLower()) < 0) {
                    //5.5.4重複による例外を回避
                    //ar.Add("HTTP_" + line.Key.ToUpper(), recvHeader.GetVal(line.Key));
                    var tag = "HTTP_" + line.Key.ToUpper();
                    //if (null == ar[tag]) {
                    //    ar.Add(tag, recvHeader.GetVal(line.Key));
                    //}
                    bool find = _ar.Any(a => a.Key == tag);
                    if(!find){
                        _ar.Add(new OneEnv(tag, recvHeader.GetVal(line.Key)));
                    }

                }
            }
        }
Beispiel #16
0
 public void ParseRequest_shortdata()
 {
     string data = "GET /getTemperature/2013/12/03";
     Request rq = new Request(data);
     rq.parseRequest(data);
 }
Beispiel #17
0
 public void SetUp()
 {
     _request = new Request(null,null);
 }