【问题标题】:ASIO UDP client never receiving messagesASIO UDP 客户端从不接收消息
【发布时间】:2020-01-10 14:43:15
【问题描述】:

我正在尝试使用独立的 ASIO/C++ 库编写一个带有用户提供的解析器的 DNS 解析器(只是一个包含多个可用于查询的 IP 地址的文本文件),但每次尝试都失败了接收器工作。所有解析器似乎都没有响应(udp::receive_from)我发送的查询。但是,当我尝试将相同的解析器文件与dnslib 之类的外部库一起使用时,它们的工作原理就像魅力一样,所以问题出在我的代码上。这是我用来向 DNS 服务器发送数据的代码。

struct DNSPktHeader
{
    uint16_t id{};
    uint16_t bitfields{};
    uint16_t qdcount{};
    uint16_t ancount{};
    uint16_t nscount{};
    uint16_t arcount{};
};

// dnsname, for example is -> google.com
// dns_resolver is a list of udp::endpoint of IPv4 address on port 53.
// ip is the final result
// returns 0 on success and negative value on failure

int get_host_by_name( char const *dnsname, std::vector<udp::endpoint> const & dns_resolvers, OUT uint16_t* ip )
{
    uint8_t netbuf[128]{};
    char const *funcname = "get_host_by_name";

    uint16_t const dns_id = rand() % 2345; // warning!!! Simply for testing purpose

    DNSPktHeader dns_qry{};
    dns_qry.id = dns_id;
    dns_qry.qdcount = 1;
    dns_qry.bitfields = 0x8; // set the RD field of the header to 1

    // custom_htons sets the buffer pointed to by the second argument netbuf
    // to the htons of the first argument
    custom_htons( dns_qry.id, netbuf + 0 );
    custom_htons( dns_qry.bitfields, netbuf + 2 );
    custom_htons( dns_qry.qdcount, netbuf + 4 );
    custom_htons( dns_qry.ancount, netbuf + 6 );
    custom_htons( dns_qry.nscount, netbuf + 8 );
    custom_htons( dns_qry.arcount, netbuf + 10 );

    unsigned char* question_start = netbuf + sizeof( DNSPktHeader ) + 1;
    // creates the DNS question segment into netbuf's specified starting index
    int len = create_question_section( dnsname, (char**) &question_start, thisdns::dns_record_type::DNS_REC_A, 
        thisdns::dns_class::DNS_CLS_IN );
    if( len < 0 ){
        fmt::print( stderr, "{}: {} ({})\n", funcname, dnslib_errno_strings[DNSLIB_ERRNO_BADNAME - 1], dnsname );
        return -EFAULT;
    }
    len += sizeof( DNSPktHeader );
    fmt::print( stdout, "{}: Submitting DNS A-record query for domain name ({})\n", funcname, dnsname );
    asio::error_code resolver_ec{};

    udp::socket udp_socket{ DNSResolver::GetIOService() };
    udp_socket.open( udp::v4() );
    // set 5 seconds timeout on receive and reuse the address
    udp_socket.set_option( asio::ip::udp::socket::reuse_address( true ) );
    udp_socket.set_option( asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO>{ 5'000 } );
    udp_socket.bind( udp::endpoint{ asio::ip::make_address( "127.0.0.1" ), 53 } );
    std::size_t bytes_read = 0, retries = 1;
    int const max_retries = 10;
    asio::error_code receiver_err{};
    uint8_t receive_buf[0x200]{};
    udp::endpoint default_receiver{};

    do{
        udp::endpoint const & resolver_endpoint{ dns_resolvers[retries] };
        int bytes_sent = udp_socket.send_to( asio::buffer( netbuf, len ), resolver_endpoint, 0, resolver_ec );
        if( bytes_sent < len || resolver_ec ){
            fmt::print( stderr, "{}: (found {}, expected {})\n", funcname, i, sizeof( DNSPktHeader ) );
            return -EFAULT;
        }
        // ======== the problem ==============
        bytes_read = udp_socket.receive_from( asio::buffer( receive_buf, sizeof( receive_buf ) ), default_receiver, 0,
            receiver_err );
        // bytes_read always return 0
        if( receiver_err ){
            fmt::print( stderr, "{}\n\n", receiver_err.message() );
        }
    } while( bytes_read == 0 && retries++ < max_retries );

    //...
}

我已经尽力了,但显然还不够。你能看看这个并帮助找出问题所在吗?这是我第一次在实际项目中使用 ASIO。

不知道这是否相关,但这里是create_question_section

int create_question_section( const char *dnsname, char** buf, thisdns::dns_record_type type, thisdns::dns_class class_ )
{
    char const *funcname = "create_question_section";
    if( dnsname[0] == '\0' ){  // Blank DNS name?
        fmt::print( stderr, "{}: Blank DNS name?\n", funcname );
        return -EBADF;
    }

    uint8_t len{};
    int index{};
    int j{};
    bool found = false;
    do{
        if( dnsname[index] != '.' ){
            j = 1;
            found = false;
            do{
                if( dnsname[index + j] == '.' || dnsname[index + j] == '\0' ){
                    len = j;
                    strncpy( *buf, (char*) &len, 1 );
                    ++( *buf );
                    strncpy( *buf, (char*) dnsname + index, j );
                    ( *buf ) += j;
                    found = true;
                    if( dnsname[index + j] != '\0' )
                        index += j + 1;
                    else
                        index += j;
                } else{
                    j++;
                }
            } while( !found && j < 64 );
        } else{
            fmt::print( stderr, "{}: DNS addresses can't start with a dot!\n", funcname );
            return -EBADF;  // DNS addresses can't start with a dot!
        }
    } while( dnsname[index] );
    uint8_t metadata_buf[5]{};

    custom_htons( (uint16_t)type, metadata_buf + 1 );
    custom_htons( (uint16_t)class_, metadata_buf + 3 );
    strncpy( *buf, (char*) metadata_buf, sizeof(metadata_buf) );

    return sizeof( metadata_buf ) + index + 1;
}

【问题讨论】:

  • 除了学习之外,我建议不要从头开始重写 DNS 服务器,而是使用任何现有的。我不知道你的代码有什么问题,首先阅读多次 RFC 1034 和 1035 以真正完全了解数据包是如何构建和解析的。还要记住,DNS 是通过 UDP 和 TCP 进行的,而不仅仅是通过 UDP,经常会出错......
  • Patrick Mevzek,感谢您的评论。我实际上在写的是一个 DNS 解析器客户端,而不是另一个服务器。我会看看使用 TCP 是否可以工作,如果两者都没有,我会使用 Wireshack 进行跟踪。
  • 我的评论同样适用:除了学习,不要从头开始编写 DNS 客户端或服务器。至少使用现有的库。查看 getdnsapi 以获得更新版本的 DNS 库。
  • @iamOgunyinka 还有其他问题还是解决了?
  • 已解决。我最终使用了另一个开源库并完全放弃了它。 TBH 你的回答很有帮助,它消除了问题创建中的错误。因此,我将其标记为已解决此问题。

标签: c++ dns udp asio


【解决方案1】:

至少有两个问题导致它不适合您。它们都归结为您发送的 DNS 数据包格式错误。

这一行

unsigned char* question_start = netbuf + sizeof( DNSPktHeader ) + 1;

将指针设置到比你想要的更远的缓冲区的位置。它不是从位置 12(从 0 开始索引)开始编码的 FQDN,而是从位置 13 开始。这意味着 DNS 服务器看到一个零长度的域名和一些垃圾记录类型和类,而忽略其余部分。因此它决定根本不响应您的查询。只需摆脱+1

另一个可能的问题是使用custom_htons() 对所有记录进行编码。我不知道它是如何实现的,因此无法告诉您它是否正常工作。

此外,虽然不直接对您观察到的行为负责,但以下对 bind() 的调用将产生零效果,除非您以 root 身份运行二进制文件(或在 linux 上使用适当的功能),因为您正在尝试绑定到特权端口

udp_socket.bind( udp::endpoint{ asio::ip::make_address( "127.0.0.1" ), 53 } );

另外,这个dns_qry.bitfields = 0x8; 不会做你想做的事。应该是dns_qry.bitfields = 0x80;

查看thisthis RFC 以获取有关如何形成有效DNS 请求的参考。

重要提示:我强烈建议您不要将 C++ 与 C 混合使用。选择一个,但既然您标记了 C++ 并使用 Boost 和 libfmt,请坚持使用 C++。用适当的 C++ 版本(static_castreinterpret_cast 等)替换所有 C 风格的转换。不要使用 C 样式的数组,使用 std::array,不要使用 strncpy 等。

【讨论】: