aboutsummaryrefslogtreecommitdiff
path: root/lib/dns/message.go
AgeCommit message (Collapse)Author
2026-01-26lib/dns: add method to set TTL on MessageShulhan
The SetTTL method set all RRs answer time to live.
2025-01-23all: use for-range with numericShulhan
Go 1.22 now support for-range on numeric value.
2025-01-23all: replace [lib/bytes.WriteXxx] with standard libraryShulhan
The "encoding/binary.BigEndian" in standard library provides method PutXxx that do the same thing.
2025-01-23all: replace "lib/bytes.AppendXxx" with standard libraryShulhan
Since Go 1.19, package "encoding/binary.BigEndian" support appending byte order.
2025-01-17lib/dns: detect invalid header earlierShulhan
Previously, we unpack the header and then question without detecting whether the header itself is valid or not, for example the op-code, the response code. This cause the unpacking question return an error like label length overflow at index xxx One of the case is when someone sent random or HTTP request to DoT port.
2024-04-12lib/dns: return errInvalidMessage when received message cannot be parsedShulhan
By returning error errInvalidMessage, the caller can check whether the issue is in connection or in the message itself. If the issue is not in the message, the caller needs to re-create the connection.
2024-04-12lib/dns: fix packing and unpacking OPT recordShulhan
The RDATA in OPT records can contains zero or _more_ options. Previously, we only handle unpacking and packing one option, now we handle multiple options.
2024-03-27lib/dns: refactor [Message.Unpack] to [UnpackMessage]Shulhan
The previous API for Message is a little bit weird. Its provides creating Message manually, but expose the method [UnpackHeaderQuestion], meanwhile the field packet itself is unexported. In order to make it more clear we refactor [Message.Unpack] to function [UnpackMessage] that accept raw DNS packet.
2024-03-26lib/dns: implements RFC 9460 for SVCB RR and HTTPS RRShulhan
2024-03-05all: comply with linter recommendations #2Shulhan
HTTP request now implicitly create request with context. Any false positive related to not closing HTTP response body has been annotated with "nolint:bodyclose". In the example code, use consistent "// Output:" comment format, by prefixing with single space. Any comment on code now also prefixing with single space. An error returned without variables now use [errors.New] instead of [fmt.Errorf]. Any error returned using [fmt.Errorf] now wrapped using "%w" instead of "%s". Also, replace error checking using [errors.Is] or [errors.As], instead of using equal/not-equal operator. Any statement like "x = x OP y" now replaced with "x OP= y". Also, swap statement is simplified using "x, y = y, x". Any switch statement with single case now replaced with if-condition. Any call to defer on function or program that call [os.Exit], now replaced by calling the deferred function directly. Any if-else condition now replaced with switch statement, if possible.
2024-03-02all: move the repository to "git.sr.ht/~shulhan/pakakeh.go"Shulhan
There are several reasons that why we move from github.com. First, related to the name of package. We accidentally name the package with "share" a common word in English that does not reflect the content of repository. By moving to other repository, we can rename it to better and unique name, in this "pakakeh.go". Pakakeh is Minang word for tools, and ".go" suffix indicate that the repository related to Go programming language. Second, supporting open source. The new repository is hosted under sourcehut.org, the founder is known to support open source, and all their services are licensed under AGPL, unlike GitHub that are closed sources. Third, regarding GitHub CoPilot. The GitHub Terms of Service [1], allow any public content that are hosted there granted them to parse the content. On one side, GitHub helps and flourish the open source, but on another side have an issues regarding scraping the copyleft license [2]. [1]: https://docs.github.com/en/site-policy/github-terms/github-terms-of-service#4-license-grant-to-us [2]: https://githubcopilotinvestigation.com
2024-02-25lib/dns: ignore invalid messageShulhan
If Query return a message but the failed to unpack due to invalid format, for example unpackOPT: data length is out of range ignore it instead of disconnect the client connection.
2023-08-06lib/dns: add method AddAuthority to MessageShulhan
The AddAuthority add the rr to list of Authority. Calling this method mark the message as answer, instead of query. If the rr is SOA, it will replace the existing record if exist and set the flag authoritative answer (IsAA) in header to true. If the rr is NS, it will be added only if its not exist. It will return an error if the rr type is not SOA or NS or the size of records in Authority is full, maximum four records.
2023-05-20all: remove any usage of debug.Value in all packagesShulhan
Using global debug value for all packages turns out is not a good idea.
2023-03-26lib/dns: fix packing, parsing, and saving MINFO resource dataShulhan
Even thought the MINFO record not formally obsolete, according to Wikipedia [1], we still need to support this for backward compatibility. When packing the resource data length does not include total length. When parsing, the RMailBox and EmailBox should be added the origin suffix if its not end with dot. When saving, the origin should be trimmed from RMailBox and EmailBox. [1] https://en.wikipedia.org/wiki/List_of_DNS_record_types#Obsolete_record_types
2023-03-26lib/dns: fix packing and unpacking resource record HINFOShulhan
The rdata for HINFO contains two character-strings: CPU and OS. Previously, we pack the rdata section sequentially, without adding length on each of them: <RDLEN><CPU><OS>. The correct pack format should <RDLEN><LENGTH><CPU><LENGTH><OS>.
2023-03-25lib/dns: fix all lint warnings suggested by revive and fieldalignmentShulhan
2023-03-22lib/dns: use the packet length to derive current offsetShulhan
This remove unnecessary calculating offset (on msg.off) manually.
2022-05-17lib/dns: return the removed record on caches RemoveCachesByRRShulhan
If the record being removed found on caches, it will return it; otherwise it will return nil without error.
2022-05-12all: rewrite all codes to use "var" instead of ":="Shulhan
Using ":=" simplify the code but we lose the type. For example, v := F() The only way we know what the type of v is by inspecting the function F. Another disadvantages of using ":=" may cause extra variables allocation where two or more variables with same type is declared inside body of function where it could be only one. While at it, we split the struct for test case into separate type.
2022-05-09all: reformat all codes using gofmt 1.19 (the Go tip)Shulhan
2021-11-15lib/dns: realign all struct fieldsShulhan
Using the fieldalignment, we got the following output, answer.go:15:13: struct with 56 pointer bytes could be 24 = 32 bytes caches.go:27:13: struct with 24 pointer bytes could be 16 = 8 dot_client.go:20:16: struct with 16 pointer bytes could be 8 = 8 hosts_file.go:24:16: struct with 64 pointer bytes could be 48 = 16 message.go:53:14: struct of size 176 could be 168 = 8 rdata_mx.go:20:14: struct with 16 pointer bytes could be 8 = 8 rdata_opt.go:18:15: struct with 16 pointer bytes could be 8 = 8 rdata_srv.go:16:15: struct with 64 pointer bytes could be 56 = 8 rdata_wks.go:30:15: struct with 40 pointer bytes could be 32 = 8 request.go:20:14: struct with 32 pointer bytes could be 24 = 8 resource_record.go:24:21: struct with 56 pointer bytes could be 40 = 16 server.go:76:13: struct with 120 pointer bytes could be 112 = 8 server_options.go:20:20: struct of size 240 could be 224 = 16 tcp_client.go:21:16: struct with 40 pointer bytes could be 24 = 16 udp_client.go:24:16: struct with 24 pointer bytes could be 16 = 8 udp_client_pool.go:25:20: struct with 24 pointer bytes could be 16 = 8 zone_file.go:22:15: struct with 128 pointer bytes could be 120 = 8 zone_parser.go:53:17: struct with 88 pointer bytes could be 72 = 16 Turns out the struct that we frequently used, answer and resource_record, is not optimized. This changes reorder all structs field to save space in memory.
2021-11-15lib/dns: refactoring message questionShulhan
Previously the type for message question section SectionQuestion. This changes, rename the type to MessageQuestion.
2021-11-14lib/dns: refactoring the section headerShulhan
This changes rename the SectionHeader into MessageHeader. The pack() method is optimized with the following results, benchmark old ns/op new ns/op delta BenchmarkMessageHeader_pack-8 66.2 21.7 -67.31% benchmark old allocs new allocs delta BenchmarkMessageHeader_pack-8 3 1 -66.67% benchmark old bytes new bytes delta BenchmarkMessageHeader_pack-8 32 16 -50.00% The unpack() method is simplified by minimizing the if-condition. This changes also fix the pack and unpack OpCode for value other then 0, due to wrong shift value, 2 instead of 3.
2021-11-14lib/dns: refactoring, introduce new type RecordClassShulhan
Previously, the record class is represented by uint16 using prefix QueryClassXxx. This changes make the record class to be an independent type, to make code more strict (prevent passing invalid value), and readable.
2021-11-14lib/dns: refactoring, create type RecordType to represent type of RRShulhan
Previously, we use uint16 to represent type for ResourceRecord Type or Question type. To make the code more strict, where parameter or return value, must be expected as record type, we add new type to represent the RR type: RecordType. This changes also rename any variable name of QType or qtype to RType or rtype because QType is misleading. The type defined the ResourceRecord to be queried not only question.
2021-11-13lib/dns: remove internal field off from ResourceRecordShulhan
The off field previously used to record the next index after parsing domain name with offset. Since the field only used once, after calling unpackDomainName, we return the off value instead as "end". This changes make the unpackDomainName() become a function. This changes rename field offTTL to idxTTL to match with their value. This changes alos pefix all errors with the method or function names.
2021-11-11lib/dns: use different packet between UDP and TCP messagesShulhan
Previously, all packet size for reading and sending the message is fixed to 4096, even on UDP. This changes set the UDP packet size maximum to 512 bytes and others to 4096 bytes. While at it, minimize copying packet if its not reusable inside a method.
2021-10-17lib/bytes: refactoring and cleaning up the bytes packageShulhan
The bytes package, and many other packages in this module, is written when I still learning and using the Go language for master thesis. Some of the code, like function signature, does not follow the Go idiom, at least not how the Go source code looks like. A breaking changes, * WriteUint16 and WriteUint32 accept slice only without pointer. There is no need to pass slice as pointer to function if we want to modify the content, as long as the backing storage is not changed. Bug fixes, * PrintHex: fix print layout on the last line * ReadHexByte: fix possible index out of range * SkipAfterToken return -1 and false if no token found, as promised in the comment, instead of the length of text. We move all unit test to example so we have test and example in the documentation at the same time. This changes make all test coverage 100%.
2021-10-14lib/bytes: refactoring AppendXxx functionsShulhan
Previously, we pass pointer to slice on AppendInt16, AppendInt32, AppendUint16, and AppendUint32 functions. This model of function signature is not a Go idiom. It is written when I am still new to Go.
2021-10-14lib/ascii: change signature of ToLower and ToUpperShulhan
Using pointer to slice on method or function is not a Go idiom. It is created when I still new to Go.
2020-09-06dns: unexport the Messsage's Packet fieldShulhan
This field is used for storing the actual DNS packet after Message.Pack has been called.
2020-09-06dns: export function to get query type by address valueShulhan
2020-08-18dns: rename AddRR to AddAnswer on Message typeShulhan
While at it, * split the SOA record into single field * rename the "out" field into "zone" on masterParser
2020-08-17dns: add method to remove RR from cache and master fileShulhan
The RemoveCachesByRR() method on Server will remove single RR from message in the cache and from master file.
2020-08-15dns: refactoring the ResourceRecord values from []byte to stringShulhan
There are two reasons for this changes. First, to allow JSON encoded of ResourceRecord.Value without encoded to base64. Second, to minimize unreleased packet due to the backing storage is still used when assigned to Value (or any []byte field in RDataXXX).
2020-08-15dns: add method to update/insert resource record to cachesShulhan
The exported method, UpsertCacheByRR(),in the server allow client to add or replace local cache by only passing single resource record.
2020-08-03dns: refactoring resource record fieldsShulhan
Previously, each record data is represented b¥ its own type, except for A, NS, CNAME, MB, MG, NULL, PTR, and TXT; represented b¥ slice of byte. This changes replace all record data with an interface{}.
2020-07-26dns: add method to create Message from hostname and list of addressesShulhan
The NewMessageAddress create new DNS message for hostname that contains one or more A or AAAA addresses. The addresses must be all IPv4 or IPv6, the first address define the query type. If hname is not valid hostname or one of the address is not valid IP address it will return nil.
2020-06-06all: use default linter optionsShulhan
2020-06-06dns: replace RDataText with plain []byteShulhan
2020-02-13all: suppress false-positive linter warningsShulhan
2019-12-09dns: allocate raw packet on receiveShulhan
2019-12-04dns: remove the use of pointer on Message fieldsShulhan
2019-12-04dns: remove the use of ResourceRecord poolShulhan
Let the GC handle the memory resource.
2019-10-22dns: return an error if section question contains invalid packetShulhan
2019-06-14ascii: new library for working with ASCII charactersShulhan
This library previously part of bytes package. To make it bytes package consistent (only working with slice of byte), we move all ASCII related constants, variables, and functions into new package.
2019-05-21dns: always return true when answers RR exist and no TTL is zeroShulhan
Previous IsExpired() will return true if answers exist but one of TTL in authority or additional RR is zero. Since authority and additional RR are complementary, any Message with EDNS that by default have zero TTL will always return true. This change check TLL expiration only on answers. As long as the answers RR exist and no zero TTL it will return false. We also remove zero TTL check on additional RR due to default zero value for EDNS message.
2019-05-07dns: check for zero TTL on authorities and additionals RR on IsExpiredShulhan
Since the server accept empty answers on query response (as long as the response code is OK), the response message should be expired if one of resource record in authority or additional is zero.
2019-04-12dns/message: remove elapsed parameter on message IsExpired()Shulhan
Since this function is called after the TTL has been subtracted, there is no need to compare them with elapsed time; we only need to check if TTL is zero or not.