1 // Copyright 2013 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef CLOUD_PRINT_GCP20_PROTOTYPE_DNS_PACKET_PARSER_H_ 6 #define CLOUD_PRINT_GCP20_PROTOTYPE_DNS_PACKET_PARSER_H_ 7 8 #include <string> 9 10 #include "net/dns/dns_protocol.h" 11 #include "net/dns/dns_response.h" 12 13 // Parsed response record. 14 struct DnsQueryRecord { 15 DnsQueryRecord() : qtype(0), qclass(0) {} 16 ~DnsQueryRecord() {} 17 18 std::string qname; // in dotted form 19 uint16 qtype; 20 uint16 qclass; 21 }; 22 23 // Iterator to walk over records of the DNS response packet. Encapsulates 24 // |DnsRecordParser| object for using its functionality. 25 class DnsPacketParser { 26 public: 27 // Constructs an iterator to process the |packet| of given |length|. 28 DnsPacketParser(const char* packet, size_t length); 29 30 // Destroys the object. 31 ~DnsPacketParser() {} 32 33 bool IsValid() const { return record_parser_.IsValid() && is_header_read_; } 34 35 // Returns |true| if no more bytes remain in the packet. 36 bool AtEnd() const { return record_parser_.AtEnd(); } 37 38 // Returns header of DNS packet. 39 const net::dns_protocol::Header& header() const { return header_; } 40 41 // Parses the next query record into |record|. Returns true if succeeded. 42 bool ReadRecord(DnsQueryRecord* record); 43 44 // Parses the next resource record into |record|. Returns true if succeeded. 45 bool ReadRecord(net::DnsResourceRecord* record) { 46 return record_parser_.ReadRecord(record); 47 } 48 49 private: 50 // Returns current offset into the packet. 51 size_t GetOffset() const { return record_parser_.GetOffset(); } 52 53 // Parses a (possibly compressed) DNS name from the packet starting at 54 // |pos|. Stores output (even partial) in |out| unless |out| is NULL. |out| 55 // is stored in the dotted form, e.g., "example.com". Returns number of bytes 56 // consumed or 0 on failure. 57 // This is exposed to allow parsing compressed names within RRDATA for TYPEs 58 // such as NS, CNAME, PTR, MX, SOA. 59 // See RFC 1035 section 4.1.4. 60 unsigned ReadName(std::string* out) const { 61 return record_parser_.ReadName(packet_ + GetOffset(), out); 62 } 63 64 const char* packet_; 65 size_t length_; 66 67 // Contents parsed header_; 68 net::dns_protocol::Header header_; 69 bool is_header_read_; 70 71 // Encapsulated parser. 72 net::DnsRecordParser record_parser_; 73 74 DISALLOW_COPY_AND_ASSIGN(DnsPacketParser); 75 }; 76 77 #endif // CLOUD_PRINT_GCP20_PROTOTYPE_DNS_PACKET_PARSER_H_ 78 79