.NETでStreamReader.ReadLine()によって読み取られる文字数を制限する方法は?

StackOverflow https://stackoverflow.com/questions/400407

質問

C#でWebサーバーアプリケーションを作成し、StreamReaderクラスを使用して、基礎となるNetworkStreamから読み取ります:

 NetworkStream ns = new NetworkStream(clientSocket);
 StreamReader sr = new StreamReader(ns);
 String request = sr.ReadLine();

このコードはDoS攻撃を受けやすい傾向があります。なぜなら、攻撃者が接続を切断しないと、行の読み取りが完了しなくなるからです。 .NETのStreamReader.ReadLine()によって読み取られる文字数を制限する方法はありますか?

役に立ちましたか?

解決

Read(char []、int、int)オーバーロード(長さを制限します)を使用し、独自の行末検出を行う必要があります。トリッキーすぎるべきではありません。

やや怠laなバージョンの場合(単一文字の読み取りバージョンを使用):

static IEnumerable<string> ReadLines(string path, int maxLineLength)
{
    StringBuilder currentLine = new StringBuilder(maxLineLength);
    using (var reader = File.OpenText(path))
    {
        int i;
        while((i = reader.Read()) > 0) {
            char c = (char) i;
            if(c == '\r' || c == '\n') {
                yield return currentLine.ToString();
                currentLine.Length = 0;
                continue;
            }
            currentLine.Append((char)c);
            if (currentLine.Length > maxLineLength)
            {
                throw new InvalidOperationException("Max length exceeded");
            }
        }
        if (currentLine.Length > 0)
        {
            yield return currentLine.ToString();
        }                
    }
}

他のヒント

StreamReader.Read オーバーロードのいずれかが必要になる場合があります:

http://msdn.microsoft.com/en-usから取得/library/9kstw824.aspx

    using (StreamReader sr = new StreamReader(path)) 
    {
        //This is an arbitrary size for this example.
        char[] c = null;

        while (sr.Peek() >= 0) 
        {
            c = new char[5];
            sr.Read(c, 0, c.Length);
            //The output will look odd, because
            //only five characters are read at a time.
            Console.WriteLine(c);
        }
    }

sr.Read(c、0、c.Length)行にフォーカスします。これは、ストリームから5文字のみを読み取り、 c 配列に入れます。 5を希望する値に変更できます。

ここに、Marc Gravellによるソリューションに基づいた独自のソリューションがあります。

using System;
using System.IO;
using System.Text;

namespace MyProject
{
    class StreamReaderExt : StreamReader
    {

        public StreamReaderExt(Stream s, Encoding e) : base(s, e)
        {            
        }

        /// <summary>
        /// Reads a line of characters terminated by CR+LF from the current stream and returns the data as a string
        /// </summary>
        /// <param name="maxLineLength">Maximum allowed line length</param>
        /// <exception cref="System.IO.IOException" />
        /// <exception cref="System.InvalidOperationException">When string read by this method exceeds the maximum allowed line length</exception>
        /// <returns></returns>
        public string ReadLineCRLF(int maxLineLength)
        {
            StringBuilder currentLine = new StringBuilder(maxLineLength);

            int i;
            bool foundCR = false;
            bool readData = false;

            while ((i = Read()) > 0)
            {

                readData = true;

                char c = (char)i;

                if (foundCR)
                {
                    if (c == '\r')
                    {
                        // If CR was found before , and the next character is also CR,
                        // adding previously skipped CR to the result string
                        currentLine.Append('\r');
                        continue;
                    }
                    else if (c == '\n')
                    {
                        // LF found, finished reading the string
                        return currentLine.ToString();
                    }
                    else
                    {
                        // If CR was found before , but the next character is not LF,
                        // adding previously skipped CR to the result string
                        currentLine.Append('\r');
                        foundCR = false;
                    }
                }
                else // CR not found
                {
                    if (c == '\r')
                    {
                        foundCR = true;
                        continue;
                    }
                }

                currentLine.Append((char)c);
                if (currentLine.Length > maxLineLength)
                {
                    throw new InvalidOperationException("Max line length exceeded");
                }
            }

            if (foundCR)
            {
                // If CR was found before, and the end of the stream has been reached, appending the skipped CR character
                currentLine.Append('\r');
            }

            if (readData)
            {
                return currentLine.ToString();
            }

            // End of the stream reached
            return null;

        }
    }
}

このコードは「現状のまま」提供されます。無保証。

常に&quot; .Read(...)&quot;を使用できます。そして、MSDNはあなたのような状況でそうすることを推奨しています。

http://msdn.microsoft.com/en-us/library/system .io.streamreader.readline.aspx

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top