[嵌入式开发模块]DNS(Domain Name System)模块 附报文格式和请求过程浅析

秒速五厘米 2023-08-17 17:46 260阅读 0赞

文章目录

  • 前言
  • DNS速成
    • 域名结构
    • 解析过程
    • 报文格式
      • 头部
      • Queries区域
      • 资源记录(RR)区域
      • Name格式
  • 模块源码
    • DNS.h
    • DNS.c
    • 依赖
  • 模块简介
  • 使用示例
    • 构造报文
    • 解析报文
    • 综合示例
  • 后记
  • 更新历史

前言

现代人在网上冲浪时不停地在和DNS系统打着交道。

你在浏览器的地址栏中输入一个网站名比如www.baidu.com并回车时,浏览器第一个要干的事情就是通过DNS系统把这个文本的域名解析为对应的IP地址,因为IP报文在网络上传递时使用IP地址来确定接收方和发送方,而不是这一长串文本。

这么设计有几个方面考虑:从用户的角度来说,一串有意义的文本总比那4个字节的数字好记得多,相信没人会愿意像背电话号码一样把各个网站的IP地址都直接背下来;从网络通信的角度来说,为了节省流量、降低延迟,要尽可能减少每个报文的额外信息,4个字节的IPv4地址自然比可能多达两百多字节的域名要省的多;从服务器的角度来说,使用域名系统后,可以实现IP地址与服务器地址的解耦,自己的IP地址可以随时变化,反正变化后只要通知下DNS服务器,这样下次用户要连接服务器时就会解析同一个域名到新的IP地址上。另外还可以实现一个域名对应多个IP地址,这样通过一些技巧,不同的用户就可以均匀连接到几个不同的IP去,其实就是负载均衡的一种实现。还有其他用处就不详说了。

这篇博文给出了我写的一个 DNS报文解析/构造 模块。对于大的网络协议栈来说肯定是自带DNS这么基础的功能的,但是谁让我们这是嵌入式呢,各种轮子都要自己造,用个轮子也得各种知其所以然。于是为了大家能够上手使用这个模块,我在这里把DNS的相关知识也直接附上,希望讲的足够清晰,帮助更多的人。

当然要是你连一点基础知识也来不及补的话,也可以直接荡下模块源码,然后就直接翻到使用示例那看怎么用就好了。
更方便地,如果你用的W5500的io库,你可以直接用我封装好的DNSClient模块的接口:
https://blog.csdn.net/lin\_strong/article/details/101936463

DNS速成

这部分内容大量参考https://jocent.me/2017/06/18/dns-protocol-principle.html
相当于是其上的一个精简,如想更深入一步了解DNS系统,可以点进去看。

域名结构

先明确一点,我们平常在浏览器上方看到的那一行比如:
https://baike.baidu.com/item/dns/427444
这个是URL,统一资源定位符,其中包含很多信息。

https 指这个资源要通过https协议访问
baike.baidu.com 才是服务器的域名
而后面那一长串则是需要获取的具体资源。可以想象服务器是一个文件系统,上面这一个URL的意义就是:
用HTTPS协议访问baike.baidu.com这个服务器,访问其上的item文件夹下的dns文件夹下的427444这个文件。

当然,URL不止由这些部分构成,但一般也就知道这些就够了,其他不是这篇文章的重点。

因特网在命名的时候采用了层次结构的命名方法。每一个域名(本文只讨论英文域名)都是一个label,用字母(A-Z,a-z,不分大小写)、数字(0-9)和连接符(-)组成,域名总长度不能超过255个字符,它由点号分割成一个个的label,每个label应该在63个字符之内,每个label都可以看成一个层次的域名。级别最低的域名写在左边,级别最高的域名写在右边。

所以baike.baidu.com被点号分层了3级域名,顶级域名com,二级域名baidu,三级域名baike。

整个DNS系统实际上是由分布全球的无数DNS服务器分层次组成的,上级服务器知道下级服务器的域名以及对应地址。根域名服务器有着固定分配的IP地址,根域名服务器知道各个顶级域名服务器的地址,顶级知道二级,以此类推。在请求baike.baidu.com这个域名的地址时,完整的,会先去根域名服务器要到com这个域名服务器的地址,然后要到baidu的,然后最后从baidu域名服务器上知道baike这个子域名的IP地址完成解析。

解析过程

当客户端想要解析一个域名时,它需要先构造一个DNS请求报文(有些词看不懂没事,看完下一章报文结构后再回来看就看懂了),QR位自然要设为0,ID随便设一个,然后对于最普通的这种域名转IP地址的DNS请求,我们选择标准查询(实际上DNS系统不只能解析域名,它还有很多其他功能,但我们这里只关心解析域名);另外,一般我们会选择递归查询,这样这个DNS服务器就会帮你完成上述那个递归的一级一级查询的整个过程,最后直接把查询结果返回给你,如果是非递归的话,你就得按上述过程自己一个个去问;最后在Queries区域带上要查询的域名,查询类IN,类型A(即IPv4地址),这样就构造好了。

DNS默认是基于UDP通信,所以继续往下看之前起码你要先学会怎么收发UDP报文,这个自己学去。。。

默认的,DNS服务器会监听在UDP 53端口。为了完成解析,我们要把构造好的报文发送给服务器的这个UDP端口,然后如果正常运作的话,DNS服务器应该会答复你一个答复报文。这个答复报文的QR位自然是1,ID与你的请求报文一致;然后在Answers区域应该会有对应答复的IPv4地址。

注意:因为之前说的那些服务器端的考虑,答复中可能有多个地址记录。而且这些地址记录对应的直接名字可能并不是你请求的那一个,不过这种情况下会有CNAME类型的记录告诉你之前那个询问的域名有个别名。所以答复也许是这样的 - baike.baidu.com CNAME aaaaa.com , baike.baidu.com CNAME bbbbb.com, aaaaa.com A XXX.XXX.XXX.XXX,bbbbb.com A XXX.XXX.XXX.XXX。意思就是说这个域名有两个别名,然后它们分别的IP地址。

报文格式

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpbl9zdHJvbmc_size_16_color_FFFFFF_t_70

头部

  • 会话标识(2字节):是DNS报文的ID标识,对于请求报文和其对应的应答报文,这个字段是相同的,通过它可以区分DNS应答报文是哪个请求的响应
  • 标志(2字节):
    20191002153421372.png
    QR(1bit) 查询/响应标志,0为查询,1为响应
    opcode(4bit) 0表示标准查询,1表示反向查询,2表示服务器状态请求
    AA(1bit) 表示授权回答
    TC(1bit) 表示可截断的
    RD(1bit) 表示期望递归
    RA(1bit) 表示可用递归
    rcode(4bit) 表示返回码,0表示没有差错,3表示名字差错,2表示服务器错误(Server Failure)
  • 数量字段(总共8字节):Questions、Answer RRs、Authority RRs、Additional RRs 各自表示后面的四个区域的数目。Questions表示查询问题区域节的数量,Answers表示回答区域的数量,Authoritative namesversers表示授权区域的数量,Additional recoreds表示附加区域的数量

Queries区域

20191002153753294.png

  • 查询名:长度不固定,且不使用填充字节,一般该字段表示的就是需要查询的域名(如果是反向查询,则为IP,反向查询即由IP地址反查域名)
  • 查询类型:列出一些常用的




























































类型 助记符 说明
1 A 由域名获得IPv4地址
2 NS 查询域名服务器
5 CNAME 查询规范名称
12 PTR 域名指针(别名)
15 MX 邮件交换
16 TXT 文本字符串
28 AAAA 由域名获得IPv6地址
33 SRV 服务定位
47 NSEC
255 ANY 对所有记录的请求

· 查询类:通常为1(IN),表明是Internet数据

资源记录(RR)区域

包括回答区域,授权区域和附加区域,格式都是一样的。
watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpbl9zdHJvbmc_size_16_color_FFFFFF_t_70 1

  • 域名:格式和Queries区域的查询名字字段是一样的。
  • 查询类型:表明资源纪录的类型,见上表。
  • 查询类:对于Internet信息,总是IN
  • 生存时间(TTL):以秒为单位,表示的是资源记录的生命周期,一般用于当地址解析程序取出资源记录后决定保存及使用缓存数据的时间,它同时也可以表明该资源记录的稳定程度,极为稳定的信息会被分配一个很大的值(比如86400,这是一天的秒数)。
  • 资源数据:该字段是一个可变长字段,表示按照查询段的要求返回的相关资源记录的数据。可以是Address(表明查询报文想要的回应是一个IP地址)或者CNAME(表明查询报文想要的回应是一个规范主机名)等。

Name格式

报文中Name字段的格式如下。
每个label前面都用一个数字表示这个label的长度,对于最后一个label,其后跟一个0作为结尾,表明Name字段的结束。

因此,对于baike.baidu.com
其在报文中的格式为

| 5 | b | a | i | k | e | 5 | b | a | i | d | u | 3 | c | o | m | 0 |

其中,字母代表这个字节的ASCII对应的字符,数字代表这个字节的值。

另外,因为同一个报文的不同记录间经常会有重复的域名,所以为了对域名进行压缩,DNS报文采用了指针机制。指针由两个字节组成,其特征是最高两个bit为11,其余的14bit构成的无符号整型值代表从DNS报文的开始处开始的偏移量。所以,每当在本该表示label长度的那个字节处读到最高两bit是11时,就代表这是一个指针,接下来就应该跳转到指针指向的那个地址继续读取剩下的域名。

我们看看rfc文档上的例子:

  1. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  2. 20 | 1 | F |
  3. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  4. 22 | 3 | I |
  5. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  6. 24 | S | I |
  7. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  8. 26 | 4 | A |
  9. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  10. 28 | R | P |
  11. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  12. 30 | A | 0 |
  13. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  14. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  15. 40 | 3 | F |
  16. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  17. 42 | O | O |
  18. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  19. 44 | 1 1| 20 |
  20. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  21. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  22. 64 | 1 1| 26 |
  23. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  24. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  25. 92 | 0 | |
  26. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+

假设20处开始Name字段,那这个域名就是 “F.ISI.ARPA”,这个应该很好理解,就不详细解释了。
我们看40字节起的Name字段。先读了一个3字节的label,是FOO,然后读到一个指针,指针指示跳转到地址为20那里去,然后我们接着读出了上一个域名,因此拼起来就是“FOO.F.ISI.ARPA”。
还有可能像64那里那样上来就是指针的,这样这个域名就是“ARPA”。

模块源码

DNS.h

  1. /*
  2. ******************************************************************************************
  3. *
  4. * DOMAIN NAME SYSTEM MODULE
  5. * DNS模块
  6. *
  7. * File : DNS.h
  8. * By : Lin Shijun(http://blog.csdn.net/lin_strong)
  9. * Date: 2019/10/15
  10. * Version: V1.1
  11. * History: 2019/05/07 beta
  12. * 2019/07/22 V1.0 fix that Domain name should be case-insensitive.
  13. * 2019/10/15 V1.1 add print interfaces of DNS-SD.
  14. * remove debug messages in DNSMsg_getDomainNameLen
  15. * Note(s): 1. the module is to provide basic definition and functions for Domain Name System.
  16. * References: https://github.com/mwarning/SimpleDNS
  17. * https://jocent.me/2017/06/18/dns-protocol-principle.html
  18. * rfc1035
  19. * rfc2782
  20. ******************************************************************************************
  21. */
  22. #ifndef _DNS_H
  23. #define _DNS_H
  24. /*
  25. *******************************************************************************************
  26. * INCLUDES
  27. *******************************************************************************************
  28. */
  29. #include <stdint.h>
  30. #include "common.h"
  31. /*
  32. *******************************************************************************************
  33. * CONFIGURATION
  34. *******************************************************************************************
  35. */
  36. // malloc define _DNS_DEBUG to enable debug message(useless in the version)
  37. // #define _DNS_DEBUG
  38. // malloc define _DNS_SCAN_TXT_MALLOC to ask scanRR to allocate new space for hold RDATA
  39. // for TXT type.
  40. // Default is pointer to the buffer, so you can't touch buffer before use up the returned RR.
  41. // #define _DNS_SCAN_TXT_MALLOC
  42. /*
  43. *******************************************************************************************
  44. * CONSTANTS
  45. *******************************************************************************************
  46. */
  47. // <domain-name> is a domain name represented as a series of labels, and terminated by a
  48. // label with zero length.
  49. // <character-string> is a single length octet followed by that number of characters.
  50. // <character-string> is treated as binary information, and can be up to 256 characters in
  51. // length (including the length octet).
  52. // Port of DNS Server
  53. #define DNSS_PORT 53
  54. // max size of <label> in DNS message
  55. #define DNS_MAXSIZE_LABELS 63
  56. // max size of <domain name> in DNS message
  57. #define DNS_MAXSIZE_NAMES 255
  58. #define DNS_MAXSIZE_TTL 2147483647L
  59. #define DNS_MAXSIZE_UDPMSG 512
  60. // ResponseType of DNS Message(rcode)
  61. // No error condition
  62. #define DNSRC_OK 0
  63. // The name server was unable to interpret the query.
  64. #define DNSRC_FormatError 1
  65. // The name server was unable to process this query due to a problem with the name server.
  66. #define DNSRC_ServerFailure 2
  67. // Meaningful only for responses from an authoritative name server, this code signifies
  68. // that the domain name referenced in the query does not exist.
  69. #define DNSRC_NameError 3
  70. // The name server does not support the requested kind of query.
  71. #define DNSRC_NotImplemented 4
  72. // The name server refuses to perform the specified operation for policy reasons.
  73. #define DNSRC_Refused 5
  74. // opcode of DNS Message
  75. #define DNSOC_Query 0 // a standard query
  76. #define DNSOC_IQuery 1 // an inverse query
  77. #define DNSOC_Status 2 // a server status request
  78. #define DNSOC_Notify 4 // request zone transfer
  79. #define DNSOC_Update 5 // change resource records
  80. // Query Type
  81. #define DNSQT_A 1 // a host address i.e. IPv4
  82. #define DNSQT_NS 2 // an authoritative name server
  83. #define DNSQT_MD 3 // a mail destination (Obsolete - use MX)
  84. #define DNSQT_MF 4 // a mail forwarder (Obsolete - use MX)
  85. #define DNSQT_CNAME 5 // the canonical name for an alias 查询规范名称
  86. #define DNSQT_SOA 6 // marks the start of a zone of authority 开始授权
  87. #define DNSQT_MB 7 // a mailbox domain name (EXPERIMENTAL)
  88. #define DNSQT_MG 8 // a mail group member (EXPERIMENTAL)
  89. #define DNSQT_MR 9 // a mail rename domain name (EXPERIMENTAL)
  90. #define DNSQT_NULL 10 // a null RR (EXPERIMENTAL)
  91. #define DNSQT_WKS 11 // a well known service description 熟知服务
  92. #define DNSQT_PTR 12 // a domain name pointer 域名指针
  93. #define DNSQT_HINFO 13 // host information 主机信息
  94. #define DNSQT_MINFO 14 // mailbox or mail list information
  95. #define DNSQT_MX 15 // mail exchange 邮件交换
  96. #define DNSQT_TXT 16 // text strings 文本字符串
  97. #define DNSQT_AAAA 28 // 由域名获得IPv6地址
  98. #define DNSQT_SRV 33 // the location of services
  99. #define DNSQT_NSEC 47
  100. // below are QTYPE, superset of TYPE
  101. #define DNSQT_IXFR 251 // aa
  102. #define DNSQT_AXFR 252 // A request for a transfer of an entire zone
  103. #define DNSQT_MAILB 253 // A request for mailbox-related records (MB, MG or MR)
  104. #define DNSQT_MAILA 254 // A request for mail agent RRs (Obsolete - see MX)
  105. #define DNSQT_ANY 255 // 对所有记录的请求
  106. // Query Class
  107. #define DNSQC_IN 1 // the Internet
  108. #define DNSQC_CS 2 // the CSNET class
  109. #define DNSQC_CH 3 // the CHAOS class
  110. #define DNSQC_Hesiod 4 // Hesiod [Dyer 87]
  111. // QCLASS
  112. #define DNSQC_ANY 255 // any class
  113. /*
  114. *******************************************************************************************
  115. * TYPE DEFINITION
  116. *******************************************************************************************
  117. */
  118. // Header of DNS message
  119. typedef struct DNSHDR_STRUCT{
  120. // A 16 bit identifier assigned by the program that generates any kind of query.
  121. // This identifier is copied the corresponding reply and can be used by the requester
  122. // to match up replies to outstanding queries. 会话ID
  123. uint16_t TransID;
  124. // Flags
  125. // Recursion Desired - this bit may be set in a query and is copied into the response.
  126. // If RD is set, it directs the name server to pursue the query recursively. Recursive
  127. // query support is optional.
  128. // 是否期望递归查询
  129. unsigned int RD : 1;
  130. // TrunCation - specifies that this message was truncated due to length greater than that
  131. // permitted on the transmission channel.
  132. // 帧是否截断
  133. unsigned int TC : 1;
  134. // Authoritative Answer - this bit is valid in responses, and specifies that the responding
  135. // name server is an authority for the domain name in question section. Note that the contents
  136. // of the answer section may have multiple owner names because of aliases. The AA bit corresponds
  137. // to the name which matches the query name, or the first owner name in the answer section.
  138. // 是否是授权的回答
  139. unsigned int AA : 1;
  140. // A four bit field that specifies kind of query in this message. This value is set by the
  141. // originator of a query and copied into the response.(DNSOC_XX)
  142. unsigned int opcode : 4;
  143. // A one bit field that specifies whether this message is a query (0), or a response (1).
  144. // 查询/响应标志位,0为查询,1为响应,1bit
  145. unsigned int QR : 1;
  146. // Response code - this 4 bit field is set as part of responses. (DNSRT_XX)
  147. // 答复码(见DNSRC_XX)
  148. unsigned int rcode : 4;
  149. // Reserved for future use. Must be zero in all queries and responses.
  150. // unsigned int Z: 3;
  151. // Recursion Available - this be is set or cleared in a response, and denotes whether
  152. // recursive query support is available in the name server.
  153. // 在答复中用于表示递归有效
  154. unsigned int RA : 1;
  155. // count fields
  156. // an unsigned 16 bit integer specifying the number of entries in the question section.
  157. // 请求数
  158. uint16_t Questions;
  159. // an unsigned 16 bit integer specifying the number of resource records in the answer section.
  160. // 回答资源记录数
  161. uint16_t AnswerRRs;
  162. // an unsigned 16 bit integer specifying the number of name server resource records in the
  163. // authority records section.
  164. // 授权资源记录数
  165. uint16_t AuthorityRRs;
  166. // an unsigned 16 bit integer specifying the number of resource records in the additional records section.
  167. // 附加资源记录数
  168. uint16_t AdditionalRRs;
  169. } DNSHdr;
  170. // Queries Section
  171. typedef struct DNSQUE_STRUCT {
  172. const char * Name; // Query Name (ASCII format)
  173. uint16_t Type; // Query Type (DNSQT_XX)
  174. uint16_t Class; // Query Class(DNSQC_XX)
  175. } DNSQue;
  176. // Data part of a Resource Record
  177. typedef union DNSRD_STRUCT{
  178. struct {
  179. const char *target;
  180. uint16_t port;
  181. uint16_t priority;
  182. uint16_t weight;
  183. } SRV;
  184. // the module don't resolve the content of the TXT RData, because it highly depends on the usage.
  185. struct {
  186. // data in RData
  187. const uint8_t *data;
  188. // the length of RData.
  189. uint16_t len;
  190. } TXT;
  191. struct {
  192. const uint8_t* addr; // A for Ipv4 address uint8_t[4], AAAA for IPv6 address uint8_t[16]
  193. } A, AAAA;
  194. struct {
  195. const char *dname; // <domain-name>, but in ascii string format here.
  196. } MB, MD, MF, MG, MR, NS, PTR, CNAME;
  197. struct {
  198. // The <domain-name> of the name server that was the original or primary source of data for this zone.
  199. // In ascii string format.
  200. const char * MName;
  201. // A <domain-name> which specifies the mailbox of the person responsible for this zone.In ascii string
  202. // format.
  203. const char* RName;
  204. // The unsigned 32 bit version number of the original copy of the zone. Zone transfers preserve this
  205. // value. This value wraps and should be compared using sequence space arithmetic.
  206. uint32_t serial;
  207. // A 32 bit time interval before the zone should be refreshed.
  208. uint32_t refresh;
  209. // A 32 bit time interval that should elapse before a failed refresh should be retried.
  210. uint32_t retry;
  211. // A 32 bit time value that specifies the upper limit on the time interval that can elapse before the
  212. // zone is no longer authoritative.
  213. uint32_t expire;
  214. // The unsigned 32 bit minimum TTL field that should be exported with any RR from this zone.
  215. uint32_t minimum;
  216. } SOA;
  217. // struct {
  218. // uint16_t preference;
  219. // const char *exchange;
  220. // } MX;
  221. struct {
  222. uint8_t useless;
  223. } Null;
  224. struct {
  225. // the next owner name (in the canonical ordering of the zone) that has authoritative data or
  226. // contains a delegation point NS RRset, <domain-name>, but in ascii string format here.
  227. const char *NextDName;
  228. // the bytes count of TypeBitMaps. Currently, not support > 32.
  229. uint16_t TypeBitMapsLength;
  230. // bitmaps array bit 0 for TYPE 0, bit 1 for TYPE 1(A), and so on. in network order.
  231. uint8_t * TypeBitMaps;
  232. } NSEC;
  233. } DNSRD;
  234. // Resource Record Section
  235. typedef struct DNSRR_STRUCT {
  236. const char *Name;
  237. uint16_t Type; // Query Type (DNSQT_XX)
  238. uint16_t Class; // Query Class(DNSQC_XX)
  239. uint32_t TTL; //
  240. // uint16_t RDLength; according to Query Type and RData
  241. DNSRD RData; // according to Query Type
  242. } DNSRR;
  243. /*
  244. *******************************************************************************************
  245. * INTERFACES
  246. *******************************************************************************************
  247. */
  248. // description: print the header to a DNS message stream.
  249. // parameter : buf the buffer for DNS message.
  250. // maxLen max length of buffer
  251. // header the header message.
  252. // return : pointer to the end of current message stream.
  253. // NULL if any error
  254. // note : neither of buf and header can't be NULL
  255. uint8_t * DNSMsg_printHeader(uint8_t *buf, uint16_t maxLen, const DNSHdr * header);
  256. // description: print a query to a DNS message stream.
  257. // parameter : buf the buffer for DNS message.
  258. // maxLen max length of buffer
  259. // p pointer to the current position of the message stream
  260. // que the query.
  261. // return : pointer to the end of current message stream.
  262. // NULL if any error
  263. // note : p, que and que->Name can't be NULL
  264. // if buf == NULL, it means you don't need overflow check.
  265. // the current version can't correctly process the situation when Name looks like
  266. // "XXX..XXX" or "XXXXXXX.", just make sure it's a normal Domain Name.
  267. uint8_t * DNSMsg_printQuery(uint8_t *buf, uint16_t maxLen, uint8_t *p, const DNSQue * que);
  268. // description: print a resource record to a DNS message stream.
  269. // parameter : buf the buffer for DNS message.
  270. // maxLen max length of buffer
  271. // p pointer to the current position of the message stream
  272. // rr the resource record.
  273. // return : pointer to the end of current message stream.
  274. // NULL if any error
  275. // note : p, que and que->Name can't be NULL
  276. // if Type in rr is unsupported, NULL will be returned.
  277. uint8_t * DNSMsg_printRR(uint8_t *buf, uint16_t maxLen, uint8_t *p, const DNSRR * rr);
  278. uint8_t * DNSMsg_printRRwithAnotherTTL(uint8_t *buf, uint16_t maxLen, uint8_t *p, const DNSRR * rr, uint32_t ttl);
  279. // description: calculate the lenth of a domian name when converted to ascii format.
  280. // parameter : msg point to the start of the DNS message.
  281. // msgLen total length of message.
  282. // p point to the start of the <domain name>.
  283. // return : >=0 the lenth of a domian name when converted to ascii format
  284. // <0 if any error.
  285. // note :
  286. int16_t DNSMsg_getDomainNameLen(const uint8_t *msg, uint16_t msgLen, const uint8_t *p);
  287. // description: get the domian name converted to ascii format.
  288. // parameter : msg point to the start of the DNS message.
  289. // msgLen total length of message.
  290. // p point to the start of the <domain name>.
  291. // return : the domian name converted to ascii format
  292. // NULL if any error.
  293. // note : user are responsible for call free to the return string.
  294. const char *DNSMsg_getDomainName(const uint8_t *msg, uint16_t msgLen, const uint8_t *p);
  295. // description: scan DNS message for resolving DNS Header.
  296. // parameter : msg point to the DNS message(start of the header)
  297. // msgLen total length of message.
  298. // ret return the resolved header message.
  299. // return : pointer to the position after the header.
  300. // NULL if any error
  301. // note :
  302. const uint8_t * DNSMsg_scanHeader(const uint8_t *msg, uint16_t msgLen, DNSHdr * ret);
  303. // description: scan DNS message stream for resolving a DNS Query.
  304. // parameter : msg point to the start of the DNS message.
  305. // msgLen total length of message.
  306. // p point to the current position for resolving query
  307. // ret return the resolved query.
  308. // return : pointer to the position after the Query.
  309. // NULL if any error
  310. // note : if return value is not NULL. don't forget to use DNSMsg_freeQueReturnByScan
  311. // to free DNSQue.
  312. const uint8_t * DNSMsg_scanQuery(const uint8_t *msg, uint16_t msgLen, const uint8_t *p, DNSQue * ret);
  313. // description: scan DNS message stream for resolving a DNS Resource Record.
  314. // parameter : msg point to the start of the DNS message.
  315. // msgLen total length of message.
  316. // p point to the current position for resolving Resource Record
  317. // ret return the resolved Resource Record.
  318. // return : pointer to the position after the Resource Record.
  319. // NULL if any error
  320. // note : if return value is not NULL. don't forget to use DNSMsg_freeRRReturnByScan
  321. // to free DNSRR.
  322. // do check the pointers in the returned RR, may be NULL if memory run out.
  323. const uint8_t * DNSMsg_scanRR(const uint8_t *msg, uint16_t msgLen, const uint8_t *p, DNSRR * ret);
  324. // description: whether support this Type of DNS
  325. // parameter : Type the type to ask
  326. // return : not 0 if support
  327. // 0 if not
  328. // note :
  329. int DNSMsg_supportType(uint16_t Type);
  330. // description: free the allocated memory used by DNSQue returned by DNSMsg_scanQuery
  331. // parameter : que the DNSQue to be free memory.
  332. // return :
  333. // note : the que must the one returned by DNSMsg_scanQuery!!!
  334. // call this function after successfully call DNSMsg_scanQuery
  335. void DNSMsg_freeQueReturnByScan(DNSQue * que);
  336. // description: free the allocated memory used by DNSRR returned by DNSMsg_scanRR
  337. // parameter : rr the DNSRR to be free memory.
  338. // return :
  339. // note : the rr must the one returned by DNSMsg_scanRR!!!
  340. // call this function after successfully call DNSMsg_scanRR
  341. void DNSMsg_freeRRReturnByScan(DNSRR * rr);
  342. // description: print a standard query DNS message for Ipv4 addr(A)
  343. // parameter : buf pointer to the buffer for DNS message.
  344. // maxLen the MAX. size of buffer.
  345. // ID ID used in this query
  346. // name pointer to the domain name.
  347. // return : the length of the DNS message.
  348. // -1 if any error
  349. // note :
  350. int16_t DnsMsg_printStandardQueryIPv4Message(uint8_t * buf, uint16_t maxLen, uint16_t ID, char const * name);
  351. // description: print a standard query DNS message for service(PTR)
  352. // parameter : buf pointer to the buffer for DNS message.
  353. // maxLen the MAX. size of buffer.
  354. // ID ID used in this query
  355. // svcName pointer to the service name("_service._tcp/_udp.local").
  356. // return : the length of the DNS message.
  357. // -1 if any error
  358. // note :
  359. int16_t DnsMsg_printStandardQueryServiceMessage(uint8_t * buf, uint16_t maxLen, uint16_t ID, char const * svcName);
  360. // description: print a standard query DNS message for service instance record(SRV)
  361. // parameter : buf pointer to the buffer for DNS message.
  362. // maxLen the MAX. size of buffer.
  363. // ID ID used in this query
  364. // svcInsName pointer to the service instance name("instance._service._tcp/_udp.local").
  365. // return : the length of the DNS message.
  366. // -1 if any error
  367. // note :
  368. int16_t DnsMsg_printStandardQueryServiceInstanceMessage(uint8_t * buf, uint16_t maxLen, uint16_t ID, char const * svcInsName);
  369. // description: print the content of a DNS message to standard output
  370. // parameter : msg pointer to the DNS message.
  371. // msgLen the of DNS message.
  372. // return :
  373. // note :
  374. void DnsMsg_resolveMessage(const uint8_t * msg, uint16_t msgLen);
  375. // description: judgment whether two DNSQue are equal.
  376. // parameter : rr1 the Question 1 to be compared.
  377. // rr2 the Question 2 to be compared.
  378. // return : TRUE if not equal
  379. // FALSE if not equal
  380. // note : no parameters NULL check.
  381. BOOL DNSQue_isEqual(const DNSQue *que1, const DNSQue *que2);
  382. // description: judgment whether two DNSRR are equal.
  383. // parameter : rr1 the Resource record 1 to be compared.
  384. // rr2 the Resource record 2 to be compared.
  385. // return : TRUE if not equal
  386. // FALSE if not equal
  387. // < 0 if error or unsupport
  388. // note : no parameters NULL check.
  389. int DNSRR_isEqual(const DNSRR *rr1, const DNSRR *rr2);
  390. int DNSRR_isEqualIgnoreTTL(const DNSRR *rr1, const DNSRR *rr2);
  391. BOOL DNSDName_isEqual(const char *dn1, const char *dn2);
  392. #endif

DNS.c

  1. /*
  2. ******************************************************************************************
  3. *
  4. * DOMAIN NAME SYSTEM MODULE
  5. * DNS模块
  6. *
  7. * File : DNS.c
  8. * By : Lin Shijun(http://blog.csdn.net/lin_strong)
  9. * Date: 2019/10/15
  10. * Version: V1.1
  11. * History:
  12. * NOTE(s):
  13. ******************************************************************************************
  14. */
  15. /*
  16. *******************************************************************************************
  17. * INCLUDES
  18. *******************************************************************************************
  19. */
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <stdio.h>
  23. #include <ctype.h>
  24. #include "DNS.h"
  25. #include "NetworkLib.h"
  26. #include "lib_lite.h" // for strcasecmp
  27. #ifdef _DNS_DEBUG
  28. #define _DEBUG
  29. #else
  30. #undef _DEBUG
  31. #endif
  32. #include "DebugMsg.h"
  33. /*
  34. *******************************************************************************************
  35. * CONSTANT
  36. *******************************************************************************************
  37. */
  38. // Mask and offset of flags byte 1
  39. #define MASK_QR 0x80
  40. #define MASK_opcode 0x78
  41. #define MASK_AA 0x04
  42. #define MASK_TC 0x02
  43. #define MASK_RD 0x01
  44. #define OFST_QR 7
  45. #define OFST_opcode 3
  46. #define OFST_AA 2
  47. #define OFST_TC 1
  48. #define OFST_RD 0
  49. // Mask and offset of flags byte 2
  50. #define MASK_RA 0x80
  51. #define MASK_zero 0x70
  52. #define MASK_rcode 0x0F
  53. #define OFST_RA 7
  54. #define OFST_zero 4
  55. #define OFST_rcode 0
  56. /*
  57. *******************************************************************************************
  58. * LOCAL VARIABLE
  59. *******************************************************************************************
  60. */
  61. typedef struct {
  62. uint16_t num;
  63. const char * s;
  64. } NameList;
  65. static const NameList NameList_QueryType[] = {
  66. {
  67. DNSQT_A, "A(IPv4 Address)" },
  68. {
  69. DNSQT_AAAA, "AAAA(IPv6 Address)"},
  70. {
  71. DNSQT_CNAME, "CNAME(alias name)" },
  72. {
  73. DNSQT_NSEC, "NSEC" },
  74. {
  75. DNSQT_MB, "MB" },
  76. {
  77. DNSQT_MD, "MD" },
  78. {
  79. DNSQT_MF, "MF" },
  80. {
  81. DNSQT_MG, "MG" },
  82. {
  83. DNSQT_MR, "MR" },
  84. {
  85. DNSQT_NS, "NS" },
  86. {
  87. DNSQT_PTR, "PTR" },
  88. {
  89. DNSQT_NULL, "NULL" },
  90. {
  91. DNSQT_SOA, "SOA" },
  92. {
  93. DNSQT_SRV, "SRV" },
  94. {
  95. DNSQT_TXT, "TXT" },
  96. {
  97. DNSQT_IXFR, "IXFR" },
  98. {
  99. DNSQT_AXFR, "AXFR" },
  100. {
  101. DNSQT_MAILB, "MAILB"},
  102. {
  103. DNSQT_MAILA, "MAILA"},
  104. {
  105. DNSQT_ANY, "ANY" },
  106. };
  107. static const NameList NameList_QueryClass[] = {
  108. {
  109. DNSQC_IN, "IN(the internet)"},
  110. {
  111. DNSQC_CS, "CS" },
  112. {
  113. DNSQC_CH, "CH" },
  114. {
  115. DNSQC_Hesiod,"Hesiod"},
  116. {
  117. DNSQC_ANY, "ANY" },
  118. };
  119. static const char _emptyStr[] = "";
  120. /*
  121. *******************************************************************************************
  122. * LOCAL FUNCTION DECLARATIONS
  123. *******************************************************************************************
  124. */
  125. // return the name string of query type, NULL if not found.
  126. static const char * _getNameOfQueryType(uint16_t qt);
  127. // return the name string of query type, NULL if not found.
  128. static const char * _getNameOfQueryClass(uint16_t qc);
  129. #define _isDomainNamePtr(labelLenByte) ((labelLenByte) >= 0xC0)
  130. // <domain-name> is a domain name represented as a series of labels, and terminated by a label
  131. // with zero length.
  132. // skip the <domain-name> in DNS message
  133. static const uint8_t * _skipDomainName(const uint8_t *p);
  134. // print a domain name in ascii to <domain-name>
  135. // if s == NULL, will output an empty <domain-name>
  136. static uint8_t * _putDomainName(uint8_t * buf, const char *s);
  137. // print <domain-name> 's', Type field 't' and Class field 'c'
  138. static uint8_t * _printDomainNameTypeClass(uint8_t *buf, const char * s, uint16_t t, uint16_t c);
  139. static void _resolveHeader(const DNSHdr *hdr);
  140. static void _resolveQuery(const DNSQue *que);
  141. static void _resolveRR(const DNSRR *rr);
  142. /*
  143. *******************************************************************************************
  144. * PUBLIC INTERFACES IMPLEMENTATIONS
  145. *******************************************************************************************
  146. */
  147. int16_t DnsMsg_printStandardQueryIPv4Message(uint8_t * buf, uint16_t maxLen, uint16_t ID,char const * name){
  148. uint8_t *p = buf;
  149. DNSQue que;
  150. DNSHdr hdr;
  151. memset(&hdr, 0, sizeof(DNSHdr));
  152. // hdr.opcode = DNSOC_Query;
  153. hdr.TransID = ID;
  154. // Recursion desired
  155. hdr.RD = 1;
  156. hdr.Questions = 1;
  157. p = DNSMsg_printHeader(buf, maxLen, &hdr);
  158. que.Name = name;
  159. que.Type = DNSQT_A;
  160. que.Class = DNSQC_IN;
  161. p = DNSMsg_printQuery(buf, maxLen, p, &que);
  162. if(p)
  163. return p - buf;
  164. else
  165. return -1;
  166. }
  167. int16_t DnsMsg_printStandardQueryServiceMessage(uint8_t * buf, uint16_t maxLen, uint16_t ID, char const * svcName){
  168. uint8_t *p = buf;
  169. DNSQue que;
  170. DNSHdr hdr;
  171. memset(&hdr, 0, sizeof(DNSHdr));
  172. // hdr.opcode = DNSOC_Query;
  173. hdr.TransID = ID;
  174. // Recursion desired
  175. hdr.RD = 1;
  176. hdr.Questions = 1;
  177. p = DNSMsg_printHeader(buf, maxLen, &hdr);
  178. que.Name = svcName;
  179. que.Type = DNSQT_PTR;
  180. que.Class = DNSQC_IN;
  181. p = DNSMsg_printQuery(buf, maxLen, p, &que);
  182. if(p)
  183. return p - buf;
  184. else
  185. return -1;
  186. }
  187. int16_t DnsMsg_printStandardQueryServiceInstanceMessage(uint8_t * buf, uint16_t maxLen, uint16_t ID, char const * svcInsName){
  188. uint8_t *p = buf;
  189. DNSQue que;
  190. DNSHdr hdr;
  191. memset(&hdr, 0, sizeof(DNSHdr));
  192. // hdr.opcode = DNSOC_Query;
  193. hdr.TransID = ID;
  194. // Recursion desired
  195. hdr.RD = 1;
  196. hdr.Questions = 1;
  197. p = DNSMsg_printHeader(buf, maxLen, &hdr);
  198. que.Name = svcInsName;
  199. que.Type = DNSQT_SRV;
  200. que.Class = DNSQC_IN;
  201. p = DNSMsg_printQuery(buf, maxLen, p, &que);
  202. if(p)
  203. return p - buf;
  204. else
  205. return -1;
  206. }
  207. uint8_t * DNSMsg_printHeader(uint8_t *buf, uint16_t maxLen, const DNSHdr * header){
  208. if(buf == NULL || maxLen < 12 || header == NULL)
  209. return NULL;
  210. buf = NetworkStream_putUint16(buf,header->TransID);
  211. *((uint16_t *)buf) = 0; // clear flag field
  212. *buf++ = (header->QR << OFST_QR) | (header->opcode << OFST_opcode) |
  213. (header->AA << OFST_AA) | (header->TC >> OFST_TC) | (header->RD >> OFST_RD);
  214. *buf++ = (header->RA << OFST_RA) | (header->rcode << OFST_rcode);
  215. buf = NetworkStream_putUint16(buf,header->Questions);
  216. buf = NetworkStream_putUint16(buf,header->AnswerRRs);
  217. buf = NetworkStream_putUint16(buf,header->AuthorityRRs);
  218. buf = NetworkStream_putUint16(buf,header->AdditionalRRs);
  219. return buf;
  220. }
  221. uint8_t * DNSMsg_printQuery(uint8_t *buf, uint16_t maxLen, uint8_t *p, const DNSQue * que){
  222. const char * s;
  223. uint16_t len;
  224. if(p == NULL || que == NULL)
  225. return NULL;
  226. s = que->Name;
  227. if(s)
  228. len = strlen(s);
  229. else
  230. len = 0;
  231. if(buf != NULL){
  232. // 溢出检查
  233. if((p + len + 2 + 4 - buf) > maxLen)
  234. return NULL;
  235. }
  236. p = _printDomainNameTypeClass(p, s, que->Type, que->Class);
  237. return p;
  238. }
  239. uint8_t * DNSMsg_printRRwithAnotherTTL(uint8_t *buf, uint16_t maxLen, uint8_t *p, const DNSRR * rr, uint32_t ttl){
  240. const char * s;
  241. uint8_t *pDATALEN;
  242. uint16_t len;
  243. if(p == NULL || rr == NULL)
  244. return NULL;
  245. s = rr->Name;
  246. p = _printDomainNameTypeClass(p, s, rr->Type, rr->Class);
  247. pDATALEN = NetworkStream_putUint32(p, ttl);
  248. p = pDATALEN + 2;
  249. switch (rr->Type){
  250. case DNSQT_A:
  251. len = 4;
  252. *(uint32_t *)p = *(uint32_t *)rr->RData.A.addr;
  253. p += 4;
  254. break;
  255. case DNSQT_AAAA:
  256. len = 16;
  257. (void)memcpy(p, rr->RData.AAAA.addr,16);
  258. p += 16;
  259. break;
  260. case DNSQT_CNAME: case DNSQT_PTR: case DNSQT_MB: case DNSQT_MD:
  261. case DNSQT_MF: case DNSQT_MG: case DNSQT_MR: case DNSQT_NS:
  262. buf = p;
  263. p = _putDomainName(p, rr->RData.CNAME.dname);
  264. len = p - buf;
  265. break;
  266. case DNSQT_NULL:
  267. len = 0;
  268. // append nothing
  269. break;
  270. case DNSQT_SOA:
  271. buf = p;
  272. p = _putDomainName(p, rr->RData.SOA.MName);
  273. p = _putDomainName(p, rr->RData.SOA.RName);
  274. p = NetworkStream_putUint32(p, rr->RData.SOA.serial);
  275. p = NetworkStream_putUint32(p, rr->RData.SOA.refresh);
  276. p = NetworkStream_putUint32(p, rr->RData.SOA.retry);
  277. p = NetworkStream_putUint32(p, rr->RData.SOA.expire);
  278. p = NetworkStream_putUint32(p, rr->RData.SOA.minimum);
  279. len = p - buf;
  280. break;
  281. case DNSQT_NSEC:
  282. buf = p;
  283. p = _putDomainName(p, rr->RData.NSEC.NextDName);
  284. *p++ = 0x00; // currently, only support first window blocks
  285. if(rr->RData.NSEC.TypeBitMapsLength > 32)
  286. return NULL;
  287. *p++ = (uint8_t)rr->RData.NSEC.TypeBitMapsLength;
  288. memcpy(p, rr->RData.NSEC.TypeBitMaps, rr->RData.NSEC.TypeBitMapsLength);
  289. p += rr->RData.NSEC.TypeBitMapsLength;
  290. len = p - buf;
  291. break;
  292. case DNSQT_SRV:
  293. buf = p;
  294. p = NetworkStream_putUint16(p, rr->RData.SRV.priority);
  295. p = NetworkStream_putUint16(p, rr->RData.SRV.weight);
  296. p = NetworkStream_putUint16(p, rr->RData.SRV.port);
  297. p = _putDomainName(p, rr->RData.SRV.target);
  298. len = p - buf;
  299. break;
  300. case DNSQT_TXT:
  301. len = rr->RData.TXT.len;
  302. if(len > 0 && rr->RData.TXT.data == NULL)
  303. return NULL;
  304. (void)memcpy(p, rr->RData.TXT.data, rr->RData.TXT.len);
  305. p += len;
  306. break;
  307. default:
  308. // return NULL if unknown Type
  309. return NULL;
  310. }
  311. (void)NetworkStream_putUint16(pDATALEN, len);
  312. return p;
  313. }
  314. uint8_t * DNSMsg_printRR(uint8_t *buf, uint16_t maxLen, uint8_t *p, const DNSRR * rr){
  315. if(rr == NULL)
  316. return NULL;
  317. return DNSMsg_printRRwithAnotherTTL(buf, maxLen, p, rr, rr->TTL);
  318. }
  319. const uint8_t * DNSMsg_scanHeader(const uint8_t *msg, uint16_t msgLen, DNSHdr * ret){
  320. uint8_t b;
  321. const uint8_t *p = msg;
  322. if(msg == NULL || msgLen < 12 || ret == NULL)
  323. return NULL;
  324. memset(ret, 0, sizeof(DNSHdr));
  325. p = NetworkStream_getUint16(p, &ret->TransID);
  326. b = *p++;
  327. ret->QR = !!(b & MASK_QR);
  328. ret->opcode = b >> OFST_opcode;
  329. ret->AA = !!(b & MASK_AA);
  330. ret->TC = !!(b & MASK_TC);
  331. ret->RD = !!(b & MASK_RD);
  332. b = *p++;
  333. ret->RA = !!(b & MASK_RA);
  334. ret->rcode = ((b & MASK_rcode) >> OFST_rcode);
  335. p = NetworkStream_getUint16(p, &ret->Questions);
  336. p = NetworkStream_getUint16(p, &ret->AnswerRRs);
  337. p = NetworkStream_getUint16(p, &ret->AuthorityRRs);
  338. p = NetworkStream_getUint16(p, &ret->AdditionalRRs);
  339. return p;
  340. }
  341. const uint8_t * DNSMsg_scanQuery(const uint8_t *msg, uint16_t msgLen, const uint8_t *p, DNSQue * ret){
  342. if(p == NULL || ret == NULL)
  343. return NULL;
  344. memset(ret, 0, sizeof(DNSQue));
  345. if((ret->Name = DNSMsg_getDomainName(msg,msgLen,p)) == NULL)
  346. return NULL;
  347. p = _skipDomainName(p);
  348. if(msg && (p - msg + 4 > msgLen)){
  349. free((void *)ret->Name);
  350. ret->Name = NULL;
  351. return NULL;
  352. }
  353. p = NetworkStream_getUint16(p, &ret->Type);
  354. p = NetworkStream_getUint16(p, &ret->Class);
  355. return p;
  356. }
  357. const uint8_t * DNSMsg_scanRR(const uint8_t *msg, uint16_t msgLen, const uint8_t *p, DNSRR * ret){
  358. uint16_t RDataLen, len;
  359. const uint8_t * p2;
  360. memset(ret, 0, sizeof(DNSRR));
  361. if((p = DNSMsg_scanQuery(msg,msgLen,p,(DNSQue *)ret)) == NULL)
  362. return NULL;
  363. p = NetworkStream_getUint32(p, &ret->TTL);
  364. p = NetworkStream_getUint16(p, &RDataLen);
  365. if(RDataLen == 0)
  366. return p;
  367. switch (ret->Type){
  368. case DNSQT_A:case DNSQT_AAAA:
  369. len = (ret->Type == DNSQT_A)? 4: 16;
  370. if((ret->RData.A.addr = (uint8_t *)malloc(len)) == NULL)
  371. break;
  372. (void)memcpy((uint8_t *)ret->RData.A.addr, p, len);
  373. break;
  374. case DNSQT_CNAME: case DNSQT_PTR: case DNSQT_MB: case DNSQT_MD:
  375. case DNSQT_MF: case DNSQT_MG: case DNSQT_MR: case DNSQT_NS:
  376. ret->RData.CNAME.dname = DNSMsg_getDomainName(msg,msgLen,p);
  377. break;
  378. case DNSQT_SOA:
  379. p2 = p;
  380. if((ret->RData.SOA.MName = DNSMsg_getDomainName(msg,msgLen,p2)) == NULL)
  381. break;
  382. p2 = _skipDomainName(p2);
  383. if((ret->RData.SOA.RName = DNSMsg_getDomainName(msg,msgLen,p2)) == NULL)
  384. break;
  385. p2 = _skipDomainName(p2);
  386. p2 = NetworkStream_getUint32(p2, &ret->RData.SOA.serial);
  387. p2 = NetworkStream_getUint32(p2, &ret->RData.SOA.refresh);
  388. p2 = NetworkStream_getUint32(p2, &ret->RData.SOA.retry);
  389. p2 = NetworkStream_getUint32(p2, &ret->RData.SOA.expire);
  390. (void)NetworkStream_getUint32(p2, &ret->RData.SOA.minimum);
  391. break;
  392. case DNSQT_SRV:
  393. p2 = p;
  394. p2 = NetworkStream_getUint16(p2, &ret->RData.SRV.priority);
  395. p2 = NetworkStream_getUint16(p2, &ret->RData.SRV.weight);
  396. p2 = NetworkStream_getUint16(p2, &ret->RData.SRV.port);
  397. ret->RData.SRV.target = DNSMsg_getDomainName(msg,msgLen,p2);
  398. break;
  399. case DNSQT_NSEC:
  400. p2 = p;
  401. if((ret->RData.NSEC.NextDName = DNSMsg_getDomainName(msg,msgLen,p2)) == NULL)
  402. break;
  403. p2 = _skipDomainName(p2);
  404. if(*p2 != 0 || *(p2 + 1) > 32 ){
  405. // check is window block 0
  406. ret->RData.NSEC.TypeBitMapsLength = 0;
  407. break;
  408. }
  409. ++p2;
  410. ret->RData.NSEC.TypeBitMapsLength = *p2++;
  411. if((ret->RData.NSEC.TypeBitMaps = (uint8_t *)malloc(ret->RData.NSEC.TypeBitMapsLength)) == NULL)
  412. break;
  413. (void)memcpy(ret->RData.NSEC.TypeBitMaps, p2, ret->RData.NSEC.TypeBitMapsLength);
  414. break;
  415. case DNSQT_TXT:
  416. ret->RData.TXT.len = RDataLen;
  417. #ifndef _DNS_SCAN_TXT_MALLOC
  418. ret->RData.TXT.data = p;
  419. #else
  420. if(RDataLen == 0)
  421. break;
  422. // one more slot for convenient of printf.
  423. if((ret->RData.TXT.data = (uint8_t *)malloc(RDataLen)) == NULL)
  424. break;
  425. (void)memcpy((void *)ret->RData.TXT.data, p, RDataLen);
  426. #endif
  427. break;
  428. default:
  429. break;
  430. }
  431. p += RDataLen;
  432. return p;
  433. }
  434. void DNSMsg_freeQueReturnByScan(DNSQue * que){
  435. if(que && que->Name){
  436. free((void *)que->Name);
  437. que->Name = NULL;
  438. }
  439. }
  440. void DNSMsg_freeRRReturnByScan(DNSRR * rr){
  441. if(rr == NULL)
  442. return;
  443. if(rr->Name){
  444. free((void *)rr->Name);
  445. rr->Name = NULL;
  446. }
  447. switch (rr->Type){
  448. case DNSQT_A: case DNSQT_AAAA:
  449. if(rr->RData.A.addr){
  450. free((void *)rr->RData.A.addr);
  451. rr->RData.A.addr = NULL;
  452. }
  453. break;
  454. case DNSQT_CNAME: case DNSQT_PTR: case DNSQT_MB: case DNSQT_MD:
  455. case DNSQT_MF: case DNSQT_MG: case DNSQT_MR: case DNSQT_NS:
  456. if(rr->RData.CNAME.dname){
  457. free((void *)rr->RData.CNAME.dname);
  458. rr->RData.CNAME.dname = NULL;
  459. }
  460. break;
  461. case DNSQT_SOA:
  462. if(rr->RData.SOA.MName){
  463. free((void *)rr->RData.SOA.MName);
  464. rr->RData.SOA.MName = NULL;
  465. }
  466. if(rr->RData.SOA.RName){
  467. free((void *)rr->RData.SOA.RName);
  468. rr->RData.SOA.RName = NULL;
  469. }
  470. break;
  471. case DNSQT_SRV:
  472. if(rr->RData.SRV.target){
  473. free((void *)rr->RData.SRV.target);
  474. rr->RData.SRV.target = NULL;
  475. }
  476. break;
  477. #ifdef _DNS_SCAN_TXT_MALLOC
  478. case DNSQT_TXT:
  479. if(rr->RData.TXT.data){
  480. free((void *)rr->RData.TXT.data);
  481. rr->RData.TXT.data = NULL;
  482. rr->RData.TXT.len = 0;
  483. }
  484. break;
  485. #endif
  486. case DNSQT_NSEC:
  487. if(rr->RData.NSEC.NextDName){
  488. free((void *)rr->RData.NSEC.NextDName);
  489. rr->RData.NSEC.NextDName = NULL;
  490. }
  491. if(rr->RData.NSEC.TypeBitMaps){
  492. free((void *)rr->RData.NSEC.TypeBitMaps);
  493. rr->RData.NSEC.TypeBitMaps = NULL;
  494. }
  495. break;
  496. default:
  497. break;
  498. }
  499. }
  500. int16_t DNSMsg_getDomainNameLen(const uint8_t *msg, uint16_t msgLen, const uint8_t *p){
  501. int16_t len = 0;
  502. uint8_t labelLen;
  503. uint16_t offset;
  504. uint16_t ptrJumpCnt = 0;
  505. if(p == NULL)
  506. return -1;
  507. while(labelLen = *p){
  508. if(_isDomainNamePtr(labelLen)){
  509. if(++ptrJumpCnt >= 10){
  510. //_dbg_printf0("ptr infinite loop doubt\n");
  511. return -1;
  512. }
  513. if(msg == NULL){
  514. //_dbg_printf0("ptr when msg == NULL error\n");
  515. return -1;
  516. }
  517. (void)NetworkStream_getUint16(p, &offset);
  518. offset &= 0x3FFF;
  519. //_dbg_printf1("ptr to %u \n", offset);
  520. p = msg + offset;
  521. if(p - msg >= msgLen){
  522. //_dbg_printf0("ptr out of msg.\n");
  523. return -1;
  524. }
  525. continue;
  526. }
  527. if(labelLen > DNS_MAXSIZE_LABELS){
  528. //_dbg_printf0("label length octets error\n");
  529. return -1;
  530. }
  531. //_dbg_printf1("label len: %d ", labelLen);
  532. ++p;
  533. len += labelLen + 1;
  534. if((msg != NULL) && (p + labelLen - msg > msgLen)){
  535. //_dbg_printf0("domain name outof message error\n");
  536. return -1;
  537. }
  538. // check no 0 in the label
  539. while(labelLen > 0){
  540. if(*p == 0){
  541. //_dbg_printf0("find 0 in label, error\n");
  542. return -1;
  543. }
  544. //_dbg_printf1("%c ", *p);
  545. --labelLen;
  546. ++p;
  547. }
  548. //_dbg_printf0("\n");
  549. }
  550. if(len > 0)
  551. --len;
  552. return len;
  553. }
  554. const char *DNSMsg_getDomainName(const uint8_t *msg, uint16_t msgLen, const uint8_t *p){
  555. int iMsg = 0, iName = 0;
  556. uint8_t labelLen;
  557. uint16_t offset;
  558. int16_t nameLen;
  559. char * name;
  560. // format check depends on getDomainNameLen
  561. nameLen = DNSMsg_getDomainNameLen(msg, msgLen, p);
  562. if(nameLen < 0)
  563. return NULL;
  564. name = (char *)malloc(nameLen + 1); // 1 slot for '\0'
  565. if(!name)
  566. return NULL;
  567. while(p[iMsg] != 0){
  568. labelLen = p[iMsg];
  569. if(_isDomainNamePtr(labelLen)){
  570. (void)NetworkStream_getUint16(&p[iMsg], &offset);
  571. p = msg + (offset & 0x3FFF);
  572. iMsg = 0;
  573. continue;
  574. }
  575. if(iName != 0)
  576. name[iName++] = '.';
  577. ++iMsg;
  578. if(iName + labelLen > nameLen){
  579. free(name);
  580. return NULL;
  581. }
  582. memcpy(&name[iName], &p[iMsg], labelLen);
  583. iName += labelLen;
  584. iMsg += labelLen;
  585. }
  586. name[iName] = '\0';
  587. return name;
  588. }
  589. static const uint8_t * _resolveRRSection(const uint8_t * msg, uint16_t msgLen, const uint8_t * p, const char * secName, uint16_t rrCnt){
  590. DNSRR rr;
  591. uint16_t i;
  592. for(i = 0; i < rrCnt; i++){
  593. printf("%s %u\r\n", secName, i + 1);
  594. p = DNSMsg_scanRR(msg, msgLen, p, &rr);
  595. if(p == NULL){
  596. printf("resolve fail.\r\n");
  597. return NULL;
  598. }
  599. _resolveRR(&rr);
  600. DNSMsg_freeRRReturnByScan(&rr);
  601. }
  602. return p;
  603. }
  604. void DnsMsg_resolveMessage(const uint8_t * msg, uint16_t msgLen){
  605. DNSHdr hdr;
  606. DNSQue que;
  607. const uint8_t * p;
  608. uint16_t i;
  609. p = DNSMsg_scanHeader(msg, msgLen, &hdr);
  610. if(p == NULL){
  611. printf("Resolve DNS message header fail.\r\n");
  612. return;
  613. }
  614. printf("Resolving DNS message.\r\n");
  615. _resolveHeader(&hdr);
  616. for(i = 0; i < hdr.Questions; i++){
  617. printf("Questions %2u\r\n", i + 1);
  618. p = DNSMsg_scanQuery(msg, msgLen, p, &que);
  619. if(p == NULL){
  620. printf("resolve fail.\r\n");
  621. return;
  622. }
  623. _resolveQuery(&que);
  624. DNSMsg_freeQueReturnByScan(&que);
  625. }
  626. if((p = _resolveRRSection(msg, msgLen, p, "AnswerRRs", hdr.AnswerRRs)) == NULL)
  627. return;
  628. if((p = _resolveRRSection(msg, msgLen, p, "AuthorityRRs", hdr.AuthorityRRs)) == NULL)
  629. return;
  630. _resolveRRSection(msg, msgLen, p, "AdditionalRRs", hdr.AdditionalRRs);
  631. }
  632. int DNSMsg_supportType(uint16_t Type){
  633. return _getNameOfQueryType(Type) != NULL;
  634. }
  635. /*
  636. *******************************************************************************************
  637. * LOCAL FUNCTIONS IMPLEMENTATIONS
  638. *******************************************************************************************
  639. */
  640. static const uint8_t * _skipDomainName(const uint8_t *p){
  641. uint8_t labelLen;
  642. for(;;){
  643. labelLen = *p++;
  644. if(labelLen == 0)
  645. break;
  646. if(_isDomainNamePtr(labelLen)){
  647. ++p;
  648. break;
  649. }
  650. p += labelLen;
  651. }
  652. return p;
  653. }
  654. static uint8_t * _putDomainName(uint8_t * buf, const char *s){
  655. uint8_t * p = buf;
  656. if(s != NULL)
  657. while(*s != '\0'){
  658. p = buf + 1;
  659. while(*s != '.' && *s != '\0')
  660. *p++ = *s++;
  661. *buf = p - buf - 1;
  662. buf = p;
  663. if(*s == '.')
  664. ++s;
  665. }
  666. *buf++ = '\0';
  667. return buf;
  668. }
  669. static uint8_t * _printDomainNameTypeClass(uint8_t *buf, const char * s, uint16_t t, uint16_t c){
  670. buf = _putDomainName(buf, s);
  671. buf = NetworkStream_putUint16(buf, t);
  672. buf = NetworkStream_putUint16(buf, c);
  673. return buf;
  674. }
  675. static const char * _getNameOfQueryType(uint16_t qt){
  676. int i;
  677. for(i = 0; i < (sizeof(NameList_QueryType)/ sizeof(NameList_QueryType[0])); i++){
  678. if(NameList_QueryType[i].num == qt)
  679. return NameList_QueryType[i].s;
  680. }
  681. return NULL;
  682. }
  683. static const char * _getNameOfQueryClass(uint16_t qc){
  684. int i;
  685. qc &= 0x00FF;
  686. for(i = 0; i < (sizeof(NameList_QueryClass)/ sizeof(NameList_QueryClass[0])); i++){
  687. if(NameList_QueryClass[i].num == qc)
  688. return NameList_QueryClass[i].s;
  689. }
  690. return NULL;
  691. }
  692. static void _resolveHeader(const DNSHdr *hdr){
  693. printf("ID: %u\r\n",hdr->TransID);
  694. if(hdr->QR)
  695. printf("Respond message.");
  696. else
  697. printf("Query message.");
  698. if(hdr->RD)
  699. printf("Recursion expected.");
  700. if(hdr->RA)
  701. printf("Recursion avail.");
  702. if(hdr->AA)
  703. printf("Authoritative.");
  704. if(hdr->TC)
  705. printf("truncated.");
  706. printf("\r\nOperation:");
  707. switch (hdr->opcode){
  708. case DNSOC_Query:
  709. printf("Standard Query");
  710. break;
  711. case DNSOC_IQuery:
  712. printf("Inverse IQuery");
  713. break;
  714. case DNSOC_Status:
  715. printf("Server Status Request");
  716. break;
  717. case DNSOC_Notify:
  718. printf("Request Zone Transfer");
  719. break;
  720. case DNSOC_Update:
  721. printf("Change Resource Records");
  722. break;
  723. default:
  724. printf("0x%2x", hdr->opcode);
  725. break;
  726. }
  727. printf("\r\n%u Questions\r\n%u AnswersRR\r\n%u AuthorityRR\r\n%u AdditionalRRs\r\n",
  728. hdr->Questions,hdr->AnswerRRs,hdr->AuthorityRRs,hdr->AdditionalRRs);
  729. }
  730. static void _resolveQuery(const DNSQue *que){
  731. const char *s;
  732. printf("Domain Name: %s\r\nQuery Type: ", que->Name);
  733. s = _getNameOfQueryType(que->Type);
  734. if(s != NULL)
  735. printf(s);
  736. else
  737. printf("0x%2x", que->Type);
  738. printf("\r\nQuery Class: ");
  739. s = _getNameOfQueryClass(que->Class);
  740. if(s != NULL)
  741. printf(s);
  742. else
  743. printf("0x%2x", que->Class);
  744. if(que->Class & 0x8000)
  745. printf(",unicast accept(mDNS)");
  746. printf("\r\n");
  747. }
  748. static void _resolveRR(const DNSRR *rr){
  749. const char *s;
  750. uint16_t i;
  751. printf("Domain Name: %s\r\nQuery Type: ", rr->Name);
  752. s = _getNameOfQueryType(rr->Type);
  753. if(s != NULL)
  754. printf(s);
  755. else
  756. printf("0x%2x", rr->Type);
  757. printf("\r\nQuery Class: ");
  758. s = _getNameOfQueryClass(rr->Class);
  759. if(s != NULL)
  760. printf(s);
  761. else
  762. printf("0x%2x", rr->Class);
  763. if(rr->Class & 0x8000)
  764. printf(",cache flush(mDNS)");
  765. printf("\r\n");
  766. printf("TTL: %lu\r\n", rr->TTL);
  767. switch (rr->Type){
  768. case DNSQT_A:
  769. printf("IPv4: ");
  770. if(rr->RData.A.addr)
  771. printf("%u.%u.%u.%u", rr->RData.A.addr[0], rr->RData.A.addr[1],
  772. rr->RData.A.addr[2], rr->RData.A.addr[3]);
  773. break;
  774. case DNSQT_AAAA:
  775. printf("IPv6: ");
  776. if(rr->RData.AAAA.addr)
  777. for(i = 0; i < 15; i += 2){
  778. if(i > 0)
  779. printf(":");
  780. printf("%02X%02X", rr->RData.AAAA.addr[i], rr->RData.AAAA.addr[i + 1]);
  781. }
  782. break;
  783. case DNSQT_CNAME: case DNSQT_PTR: case DNSQT_MB: case DNSQT_MD:
  784. case DNSQT_MF: case DNSQT_MG: case DNSQT_MR: case DNSQT_NS:
  785. printf("Name: ");
  786. if(rr->RData.CNAME.dname)
  787. printf("%s",rr->RData.CNAME.dname);
  788. break;
  789. case DNSQT_NULL:
  790. printf("NULL");
  791. break;
  792. case DNSQT_SOA:
  793. printf("Server: ");
  794. if(rr->RData.SOA.MName)
  795. printf("%s",rr->RData.SOA.MName);
  796. printf("\r\nContact: ");
  797. if(rr->RData.SOA.RName)
  798. printf("%s",rr->RData.SOA.RName);
  799. printf("\r\nSerial: %lx", (long) rr->RData.SOA.serial);
  800. printf("\r\nRefresh: %6lu", (long) rr->RData.SOA.refresh);
  801. printf("\r\nRetry: %6lu", (long) rr->RData.SOA.retry);
  802. printf("\r\nExpire: %6lu", (long) rr->RData.SOA.expire);
  803. printf("\r\nMinimum: %6lu", (long) rr->RData.SOA.minimum);
  804. break;
  805. case DNSQT_SRV:
  806. printf("Priority: %u", rr->RData.SRV.priority);
  807. printf("\r\nWeight: %u", rr->RData.SRV.weight);
  808. printf("\r\nPort: %u", rr->RData.SRV.port);
  809. printf("\r\nTarget: ");
  810. if(rr->RData.SRV.target)
  811. printf("%s", rr->RData.SRV.target);
  812. break;
  813. case DNSQT_NSEC:
  814. printf("Next Domain field: ");
  815. if(rr->RData.NSEC.NextDName)
  816. printf("%s",rr->RData.NSEC.NextDName);
  817. printf("\r\nBit Map(only for the first 256 bits): ");
  818. for(i = 0; i < rr->RData.NSEC.TypeBitMapsLength; i++)
  819. printf("%2x ", rr->RData.NSEC.TypeBitMaps[i]);
  820. break;
  821. case DNSQT_TXT:
  822. printf("len: %u\r\ndata:", rr->RData.TXT.len);
  823. for(i = 0; i < rr->RData.TXT.len; i++){
  824. if(isprint(rr->RData.TXT.data[i])){
  825. printf("%c", rr->RData.TXT.data[i]);
  826. }else{
  827. printf(" %#X ", rr->RData.TXT.data[i]);
  828. }
  829. }
  830. break;
  831. default:
  832. printf("Unrecognized type");
  833. break;
  834. }
  835. printf("\r\n");
  836. }
  837. BOOL DNSQue_isEqual(const DNSQue *que1, const DNSQue *que2){
  838. if(!DNSDName_isEqual(que1->Name,que2->Name))
  839. return FALSE;
  840. if(que1->Type != que2->Type)
  841. return FALSE;
  842. if(que1->Class != que2->Class)
  843. return FALSE;
  844. return TRUE;
  845. }
  846. int DNSRR_isEqual(const DNSRR *rr1, const DNSRR *rr2){
  847. if(rr1->TTL != rr2->TTL)
  848. return FALSE;
  849. return DNSRR_isEqualIgnoreTTL(rr1, rr2);
  850. }
  851. int DNSRR_isEqualIgnoreTTL(const DNSRR *rr1, const DNSRR *rr2){
  852. int i, len;
  853. if(!DNSQue_isEqual((const DNSQue *)rr1, (const DNSQue *)rr2))
  854. return FALSE;
  855. switch ((uint8_t)rr1->Type){
  856. case DNSQT_A:case DNSQT_AAAA:
  857. len = ((uint8_t)rr1->Type == DNSQT_A)? 4: 16;
  858. return memcmp(rr1->RData.A.addr,rr1->RData.A.addr, len) == 0;
  859. case DNSQT_CNAME: case DNSQT_PTR: case DNSQT_MB: case DNSQT_MD:
  860. case DNSQT_MF: case DNSQT_MG: case DNSQT_MR: case DNSQT_NS:
  861. return DNSDName_isEqual(rr1->RData.CNAME.dname,rr2->RData.CNAME.dname);
  862. case DNSQT_SOA:
  863. if(!DNSDName_isEqual(rr1->RData.SOA.MName,rr2->RData.SOA.MName))
  864. return FALSE;
  865. if(!DNSDName_isEqual(rr1->RData.SOA.RName,rr2->RData.SOA.RName))
  866. return FALSE;
  867. if(rr1->RData.SOA.serial != rr2->RData.SOA.serial)
  868. return FALSE;
  869. if(rr1->RData.SOA.refresh != rr2->RData.SOA.refresh)
  870. return FALSE;
  871. if(rr1->RData.SOA.retry != rr2->RData.SOA.retry)
  872. return FALSE;
  873. if(rr1->RData.SOA.expire != rr2->RData.SOA.expire)
  874. return FALSE;
  875. return rr1->RData.SOA.minimum == rr2->RData.SOA.minimum;
  876. case DNSQT_SRV:
  877. if(rr1->RData.SRV.priority != rr2->RData.SRV.priority)
  878. return FALSE;
  879. if(rr1->RData.SRV.weight != rr2->RData.SRV.weight)
  880. return FALSE;
  881. if(rr1->RData.SRV.port != rr2->RData.SRV.port)
  882. return FALSE;
  883. return DNSDName_isEqual(rr1->RData.SRV.target,rr2->RData.SRV.target);
  884. case DNSQT_NSEC:
  885. if(!DNSDName_isEqual(rr1->RData.NSEC.NextDName,rr2->RData.NSEC.NextDName))
  886. return FALSE;
  887. len = (rr1->RData.NSEC.TypeBitMapsLength < rr2->RData.NSEC.TypeBitMapsLength)?
  888. rr1->RData.NSEC.TypeBitMapsLength: rr2->RData.NSEC.TypeBitMapsLength;
  889. if(len > 0 && memcmp(rr1->RData.NSEC.TypeBitMaps, rr2->RData.NSEC.TypeBitMaps, len)!= 0)
  890. return FALSE;
  891. for(i = len; i < rr1->RData.NSEC.TypeBitMapsLength; i++)
  892. if(rr1->RData.NSEC.TypeBitMaps[i] != 0)
  893. return FALSE;
  894. for(i = len; i < rr2->RData.NSEC.TypeBitMapsLength; i++)
  895. if(rr2->RData.NSEC.TypeBitMaps[i] != 0)
  896. return FALSE;
  897. return TRUE;
  898. case DNSQT_TXT:
  899. if(rr1->RData.TXT.len != rr2->RData.TXT.len)
  900. return FALSE;
  901. return rr1->RData.TXT.len == 0 ||
  902. memcmp(rr1->RData.TXT.data, rr2->RData.TXT.data, rr1->RData.TXT.len) == 0;
  903. default:
  904. return -1;
  905. }
  906. }
  907. BOOL DNSDName_isEqual(const char *dn1, const char *dn2){
  908. dn1 = (dn1 == NULL)? _emptyStr: dn1;
  909. dn2 = (dn2 == NULL)? _emptyStr: dn2;
  910. return dn1 == dn2 || strcasecmp(dn1, dn2) == 0;
  911. }

依赖

“NetworkLib” 在NTP模块里头已经发出来了,就不再发一遍了。直接点进去下。
https://blog.csdn.net/lin\_strong/article/details/90678838\#t5

“lib_lite” 主要是为了 strcasecmp 这个函数,如果你的平台上没有的话,我直接这里贴出实现。

  1. #include <ctype.h>
  2. int strcasecmp (const char *s1, const char *s2){
  3. char c1, c2;
  4. while (*s1 && *s2){
  5. c1 = *s1;
  6. c2 = *s2;
  7. c1 = isupper(c1)?(c1 - ('A' - 'a')): c1;
  8. c2 = isupper(c2)?(c2 - ('A' - 'a')): c2;
  9. if(c1 != c2)
  10. return c1 - c2;
  11. s1++;
  12. s2++;
  13. }
  14. return *s1 - *s2;
  15. }

“common.h” 则只是宏定义了下BOOL、TRUE、FALSE而已。

模块简介

这个模块简单来说就是实现了对DNS报文的解析和构造功能。

RR记录的RDATA部分由于不同的记录类型不一样,需要分别实现。目前支持: A、AAAA、CNAME、NSEC、MB、MD、MF、MG、MR、NS、PTR、NULL、SOA、SRV、TXT类型。

支持域名指针。

不支持构造时的域名压缩。

解析时使用了malloc进行一些内部内存分配,务必记得调用对应接口进行解析,否则会有内存泄露。

结构体DNSHdr、DNSQue和DNSRR分别对应报文的报头、Queries区域以及RR区域。

DNSRR中RDATA根据不同的类型有不同的结构,选择对应的使用。

含构造的接口名字都为printXXXX、解析接口都为scanXXXX。

使用示例

构造报文

这里我们示例按之前说的请求过程构造一个对www.baidu.com的DNS请求报文:

  1. uint8_t buf[300];
  2. uint8_t *p = buf;
  3. DNSQue que;
  4. DNSHdr hdr;
  5. // Header全部字段清零
  6. memset(&hdr, 0, sizeof(DNSHdr));
  7. // 请求类型为标准查询
  8. hdr.opcode = DNSOC_Query;
  9. // 是查询报文
  10. hdr.QR = 0;
  11. // ID随便设为0x5343
  12. hdr.TransID = 0x5343;
  13. // 递归查询
  14. hdr.RD = 1;
  15. // 问题部分有一个记录
  16. hdr.Questions = 1;
  17. // 构造报头部分,返回报头的下一个位置的指针
  18. p = DNSMsg_printHeader(buf, sizeof(buf), &hdr);
  19. // 询问的域名为www.baidu.com
  20. que.Name = "www.baidu.com";
  21. // 查询类型为A(IPv4)
  22. que.Type = DNSQT_A;
  23. // 查询类为IN因特网
  24. que.Class = DNSQC_IN;
  25. // 从报头的下一个位置起打印一个询问,返回下一个位置的指针
  26. p = DNSMsg_printQuery(buf, sizeof(buf), p, &que);
  27. // buf到p的之间的内容即为请求报文

当然,因为这个需求太常见了,我已经将其进行了封装,其实直接这样调用就行了,打开看内部源码几乎一样的:

  1. msgLen = DnsMsg_printStandardQueryIPv4Message(buf,sizeof(buf), 0x5343,"www.baidu.com");

然后根据你实际的平台,将其发送给DNS服务器的53端口。正常就能得到答复报文了。

解析报文

收到了答复报文后我们就要进行解析了,基本就是这个样:

  1. // 假设收到的报文存在recvBuf里,报文长度为recvSize
  2. uint8_t recvBuf[500];
  3. uint16_t recvSize;
  4. DNSHdr hdr;
  5. DNSQue que;
  6. DNSRR rr;
  7. const uint8_t * p;
  8. uint16_t i;
  9. // 解析DNS报头,成功则返回的指针指向报头的下一个字节,否则返回NULL
  10. p = DNSMsg_scanHeader(msg, msgLen, &hdr);
  11. if(p == NULL){
  12. // 解析报头有问题,对应处理
  13. }
  14. // 现在DNS报头的各个信息就存在hdr里了,比如此时,hdr.TransID应为0x5343,hdr.QR应为1为答复报文
  15. // 先解析Queries区域
  16. for(i = 0; i < hdr.Questions; i++){
  17. // 解析Queries区域的一个记录,成功则返回的指针指向下一个字节,否则返回NULL
  18. p = DNSMsg_scanQuery(msg, msgLen, p, &que);
  19. if(p == NULL){
  20. // 解析有问题,对应处理
  21. }
  22. // 解析结果存在que里。
  23. // 解析成功务必记得调用以下接口释放内存
  24. DNSMsg_freeQueReturnByScan(&que);
  25. }
  26. // 然后解析Answers区域,里头应该有放着需要的那个地址记录
  27. for(i = 0; i < hdr.AnswerRRs; i++){
  28. p = DNSMsg_scanRR(msg, msgLen, p, &rr);
  29. if(p == NULL){
  30. // 解析有问题,对应处理
  31. }
  32. // 解析结果存在rr里。
  33. if(rr.Type == DNSQT_A){
  34. printf("地址为%u.%u.%u.%u\r\n", rr.RData.A.addr[0], rr.RData.A.addr[1],
  35. rr.RData.A.addr[2], rr.RData.A.addr[3]);
  36. }
  37. // 解析成功务必记得调用以下接口释放内存
  38. DNSMsg_freeRRReturnByScan(&rr);
  39. }
  40. // 然后依次解析剩下两个sections,格式同上。

当然,因为这个需求也很常见,所以我把打印整个报文信息的接口也进行了封装:

  1. DnsMsg_resolveMessage((const uint8_t *)recvBuf, recvSize);

综合示例

下面是使用我这个模块在window平台上进行DNS请求的程序示例:

  1. #include <stdio.h>
  2. #include <winsock2.h>
  3. extern "C"{
  4. #include "DNS.h"
  5. };
  6. #pragma comment(lib, "ws2_32.lib")
  7. static char _recvBuf[513];
  8. static uint8_t _sendBuf[300];
  9. int main(int argc, char* argv[])
  10. {
  11. WORD socketVersion = MAKEWORD(2,2);
  12. WSADATA wsaData;
  13. if(WSAStartup(socketVersion, &wsaData) != 0)
  14. {
  15. return 0;
  16. }
  17. SOCKET sclient = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  18. sockaddr_in sin;
  19. sin.sin_family = AF_INET;
  20. sin.sin_port = htons(53);
  21. // 一般直接发给网关就好了,现在的路由器上一般都提供DNS服务
  22. sin.sin_addr.S_un.S_addr = inet_addr("192.168.1.1");
  23. int len = sizeof(sin);
  24. int msgLen;
  25. // 构造请求报文
  26. msgLen = DnsMsg_printStandardQueryIPv4Message(_sendBuf,sizeof(_sendBuf), 0x5343,"www.baidu.com");
  27. printf("发送DNS报文,长度:%i\r\n", msgLen);
  28. // 打印请求报文
  29. DnsMsg_resolveMessage((const uint8_t *)_sendBuf,msgLen);
  30. // 发送请求
  31. sendto(sclient,(const char *) _sendBuf, msgLen, 0, (sockaddr *)&sin, len);
  32. // 接收答复
  33. int ret = recvfrom(sclient, _recvBuf, 513, 0, (sockaddr *)&sin, &len);
  34. if(ret > 0){
  35. printf("收到答复报文,长度:%i\r\n", ret);
  36. // 打印答复报文
  37. DnsMsg_resolveMessage((const uint8_t *)_recvBuf,ret);
  38. }
  39. closesocket(sclient);
  40. WSACleanup();
  41. return 0;
  42. }

这是运行结果:
watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpbl9zdHJvbmc_size_16_color_FFFFFF_t_70 2
我们可以看到答复报文重复了Queries部分,然后在Answers部分表示:www.baidu.com的别名为www.a.shifen.com,而www.a.shifen.com又对应着182.61.200.6以及182.61.200.7这两个地址。然后在后面的授权部分和额外部分又带上了授权服务器的相关信息。

如果你想进一步深入研究下的话,这是请求报文:
20191002190826755.png
这是答复报文:
watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpbl9zdHJvbmc_size_16_color_FFFFFF_t_70 3
一个个字节推一遍整个报文的话绝对可以加深理解,立刻尝试下吧,看好你哦!

后记

有什么建议和意见欢迎留言。

另,现在还没想清楚怎么实现构造报文时的域名压缩算法,哪个大神知道的话请赐教!

更新历史

2019/10/02 第一版
2020/06/04 更新到V1.1

发表评论

表情:
评论列表 (有 0 条评论,260人围观)

还没有评论,来说两句吧...

相关阅读