书籍" Unix网络编程"

时间:2017-09-23 03:53:09

标签: sockets readline ddos

我正在阅读" Unix网络编程" 3ed版本。

我在6.8节" TCP Echo Server(Revisited)"中遇到一个问题,现在的代码如下:

#include    "unp.h"

int
main(int argc, char **argv)
{
    int                 i, maxi, maxfd, listenfd, connfd, sockfd;
    int                 nready, client[FD_SETSIZE];
    ssize_t             n;
    fd_set              rset, allset;
    char                buf[MAXLINE];
    socklen_t           clilen;
    struct sockaddr_in  cliaddr, servaddr;

    listenfd = Socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family      = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port        = htons(SERV_PORT);

    Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

    Listen(listenfd, LISTENQ);

    maxfd = listenfd;           /* initialize */
    maxi = -1;                  /* index into client[] array */
    for (i = 0; i < FD_SETSIZE; i++)
        client[i] = -1;         /* -1 indicates available entry */
    FD_ZERO(&allset);
    FD_SET(listenfd, &allset);

    for ( ; ; ) {
        rset = allset;      /* structure assignment */
        nready = Select(maxfd+1, &rset, NULL, NULL, NULL);

        if (FD_ISSET(listenfd, &rset)) {    /* new client connection */
            clilen = sizeof(cliaddr);
            connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);

            for (i = 0; i < FD_SETSIZE; i++)
                if (client[i] < 0) {
                    client[i] = connfd; /* save descriptor */
                    break;
                }
            if (i == FD_SETSIZE)
                err_quit("too many clients");

            FD_SET(connfd, &allset);    /* add new descriptor to set */
            if (connfd > maxfd)
                maxfd = connfd;         /* for select */
            if (i > maxi)
                maxi = i;               /* max index in client[] array */

            if (--nready <= 0)
                continue;               /* no more readable descriptors */
        }

        for (i = 0; i <= maxi; i++) {   /* check all clients for data */
            if ( (sockfd = client[i]) < 0)
                continue;
            **if (FD_ISSET(sockfd, &rset)) {
                if ( (n = Read(sockfd, buf, MAXLINE)) == 0) {
                        /*4connection closed by client */
                    Close(sockfd);
                    FD_CLR(sockfd, &allset);
                    client[i] = -1;
                } else
                    Writen(sockfd, buf, n);**

                if (--nready <= 0)
                    break;              /* no more readable descriptors */
            }
        }
    }
}

关于这个程序,作者说服务器将遭受DDOS攻击,如下所示: enter image description here

关键是一旦客户端请求到来,服务器读取整行然后回显它。但是这个代码,我们看到服务器使用Read函数从客户端读取数据,而不是ReadLine或Readn,后者不会返回直到遇到&#39; \ n&#39;或者获取指定大小的数据,但在这种情况下,Read函数会立即返回。 读取功能只是系统调用的包装&#34;读取&#34;如下:

ssize_t Read(int fd, void *ptr, size_t nbytes)
{
    ssize_t     n;

    if ( (n = read(fd, ptr, nbytes)) == -1)
        err_sys("read error");
    return(n);
}

所以我很困惑为什么这台服务器会遭受ddos攻击?

任何人都可以澄清一下吗?非常感谢你!

2 个答案:

答案 0 :(得分:1)

我认为这种混淆是由于本书第二版和第三版之间可能存在差异。

我有第2版,其中包括&#34;阅读&#34;实际上是&#34; Readline&#34;。然后解释是有道理的,因为Readline坚持阅读直到换行。

我没有第3版的副本可供比较。

至于Drunken Code Monkey的解释,是的,读取是阻塞的,但是它受到选择的保护,这将保证只有在套接字上有活动时才会调用读取(断开连接,或者至少1字节读取)。因此可以保证读取不会阻塞。但请参阅我关于Read是否被Readline替换的解释(如第2版)

另请参阅Stack Overflow上的上一篇文章Unix Network Programming Clarification

答案 1 :(得分:0)

根据Stephane的回复,这里有一个例子来说明线程TCP服务器中正确的连接处理。请注意,我不熟悉linux开发来轻松编写它,所以这是C#,但程序流程应该是相同的。如果必须,将其视为伪代码。

    // We use a wait handle here to synchronize the client threads with the main thread.
    private static AutoResetEvent _waitHandle = new AutoResetEvent(false);

    static void Main(string[] args)
    {
        // Start the server on port 1337
        StartServer(1337);
    }

    private static void StartServer(int port)
    {
        // Create a connection listener
        var listener = new TcpListener(IPAddress.Any, port);

        try
        {
            // Start the listener
            listener.Start();
            while (true)
            {
                // Wait for a connection, and defer connection handling asynchronously.
                listener.BeginAcceptTcpClient(new AsyncCallback(HandleAsyncConnection), listener);
                _waitHandle.WaitOne();
                _waitHandle.Reset();
            }
        }
        catch (SocketException ex)
        {
            // Handle socket errors or any other exception you deem necessary here
        }
        finally
        {
            // Stop the server.
            listener.Stop();
        }
    }

    private static void HandleAsyncConnection(IAsyncResult state)
    {
        // Get the listener and the client references
        var listener = (TcpListener)state.AsyncState;
        using (var tcpClient = listener.EndAcceptTcpClient(state))
        {
            // Signal the main thread that we have started handling this request.
            // At this point the server is ready to handle another connection, and no amount
            // of tomfoolery on the client's side will prevent this.
            _waitHandle.Set();

            // Declare buffers
            var inBuff = new byte[tcpClient.ReceiveBufferSize];
            var outBuff = new byte[tcpClient.SendBufferSize];

            // Get the connection stream
            using (var stream = tcpClient.GetStream())
            {
                try
                {
                    // Read some data into inBuff
                    stream.Read(inBuff, 0, tcpClient.ReceiveBufferSize);

                    // Do something with the data here, put response in outBuff...

                    // Send response to client
                    stream.Write(outBuff, 0, outBuff.Length);
                }
                catch (SocketException ex)
                {
                    // Handle socket errors or any other exception you deem necessary here
                }
            }
        }
    }