Code Monkey home page Code Monkey logo

dnsclient's Introduction

NioDNS

Async DNS resolution, with all the DNS features you need!

Join our Discord for any questions and friendly banter.

Installation ๐Ÿ’ฅ

Add the package:

.package(url: "https://github.com/orlandos-nl/DNSClient.git", from: "2.0.0"),

And to your target:

.product(name: "DNSClient", package: "DNSClient"),

Usage ๐Ÿคฏ

Connect to your default DNS Server using UDP:

let client = try DNSClient.connect(on: loop).wait()

Connect to a specific DNS Server:

let googleDNS = SocketAddress(ipAddress: "8.8.8.8", port: 53)
let client = try DNSClient.connect(on: loop, config: [googleDNS]).wait()

Resolve SRV Records:

let records = try client.sendQuery(forHost: "example.com", type: .srv).wait()

Resolve TXT Records:

let records = try client.sendQuery(forHost: "example.com", type: .txt).wait()

Resolve PTR Records:

let records = try client.ipv4InverseAddress("198.51.100.1").wait()

let records = try client.ipv6InverseAddress("2001:DB8::").wait()

Need I say more?

Note: You can replace .wait() function calls with .get() to get the result using async/await.

iOS and TCP Support

On iOS 12+, you can connect using Network.Framework:

import NIOTransportServices
import DNSClient

let client = try DNSClient.connect(on: loop, host: "1.1.1.1").wait()

There is also another overload that implements TCP support:

let client = try DNSClient.connectTSTCP(on: loop, host: "1.1.1.1").wait()

TCP support is also available on Linux as DNSClient.connectTCP(on: loop, host: ...)

Note that NIOTS (TransportServices) needs their own EventLoop type, whereas NIO's MultiThreadedEventLoopGroup is used for the POSIX/Linux implementation.

Notes

The DNS Client doesn't retain itself during requests. This means that you cannot do the following:

DNSClient.connect(on: request.eventLoop).flatMap { client in
    // client.doQueryStuff()
}

The client will deallocate itself, resulting in a timeout. Make sure that the client is strongly referenced, either until all results are in or by setting it on a shared context. In Vapor, that can be the request's storage container. On other services, you could consider a global, ThreadSpecificVariable or a property on your class.

Featured In ๐Ÿ›

dnsclient's People

Contributors

alessionossa avatar andrewangeta avatar azm87 avatar camunro avatar jaapwijnen avatar joannis avatar pepijn98 avatar popflamingo avatar tayloraswift avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

dnsclient's Issues

package should be named swift-nio-dns

for consistency with other packages like swift-nio, swift-nio-ssl, this package should be renamed swift-nio-dns to follow swift package naming conventions.

DNS query failure in async paradigm

DNS request will failure with this async test as expected.

2019-09-17 15:14:22.499290+0900 xctest[7603:427732] [si_destination_compare] send failed: Invalid argument
2019-09-17 15:14:22.499516+0900 xctest[7603:427732] [si_destination_compare] send failed: Undefined error: 0
NioDNS/Tests/DNSClientTests/DNSClientTests.swift:54: error: -[DNSClientTests.DNSClientTests testSRVRecordsAsync] : Asynchronous wait failed: Exceeded timeout of 5 seconds, with unfulfilled expectations: "getSRVRecords".

No callback is called and it shows send failed error in console.

DNSClient possibly not thread safe

It crashes in DNSClient.send. It looks like multiple threads can access dnsDecoder.messageCache at the same time. I got this crash with the following code

let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let client = try await DNSClient.connectTCP(
                    on: eventLoopGroup.next(),
                    host: "1.1.1.1"
                ).get()
async let result = client.initiateAAAAQuery(host: hostname, port: 0).get()
async let result2 = client.initiateAAAAQuery(host: hostname, port: 0).get()
async let result3 = client.initiateAAAAQuery(host: hostname, port: 0).get()

Package dependency conflicts cause XCode build to fail

Using XCode 14.2 and DNSClient 2.3.2
When resolving the packages and dependencies, XCode runs into a problem with the NioDNS package. The error message is as follows:

'niodns' dependency on 'https://github.com/Joannis/swift-nio-transport-services.git' conflicts with dependency on 'https://github.com/apple/swift-nio-transport-services.git' which has the same identity 'swift-nio-transport-services'. this will be escalated to an error in future versions of SwiftPM.

XCode seems to resolve the dependency graph without error, but this causes the underlying code from the DNSClient package to stop working. In the swift file "DNSClient+Connect," it can no longer find the reference "NIOTSDatagramBootstrap".

Specifically, the error occurs in the DNSClient extension:

extension DNSClient {
    /// Connect to the dns server using TCP using NIOTransportServices. This is only available on iOS 12 and above.
    /// - parameters:
    ///   - group: EventLoops to use
    ///   - config: DNS servers to use
    /// - returns: Future with the NioDNS client. Use 
    public static func connectTS(on group: NIOTSEventLoopGroup, config: [SocketAddress]) -> EventLoopFuture<DNSClient> {
        guard let address = config.preferred else {
            return group.next().makeFailedFuture(MissingNameservers())
        }


        let dnsDecoder = DNSDecoder(group: group)
        
        return NIOTSDatagramBootstrap(group: group)
            .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
            .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEPORT), value: 1)
            .channelInitializer { channel in
                return channel.pipeline.addHandlers(dnsDecoder, DNSEncoder())
        }
        .connect(to: address)
        .map { channel -> DNSClient in
            let client = DNSClient(
                channel: channel,
                address: address,
                decoder: dnsDecoder
            )

            dnsDecoder.mainClient = client
            return client
        }
    }
    /// Connect to the dns server using TCP using NIOTransportServices. This is only available on iOS 12 and above.
    /// The DNS Host is read from /etc/resolv.conf
    /// - parameters:
    ///   - group: EventLoops to use
    public static func connectTS(on group: NIOTSEventLoopGroup) -> EventLoopFuture<DNSClient> {
        do {
            let configString = try String(contentsOfFile: "/etc/resolv.conf")
            let config = try ResolvConf(from: configString)

            return connectTS(on: group, config: config.nameservers)
        } catch {
            return group.next().makeFailedFuture(UnableToParseConfig())
        }
    }
}

Minor fixes to support iOS targets (with packages that depend on it ex. MongoKitten & Meow).

Hey there,

These modifications are necessary to allow packages using MongoKitten + Meow to target iOS which otherwise would result in a failing build.

The modifications needed are as follows:

1.) Useless variable, which is untyped, a build error.

https://github.com/Wabi-Studios/NioDNS/commit/f8c52ff6287b2935671bb0bff79429940ac6f70d

2.) Should NIOTransportServices be added as a dependency?

https://github.com/Wabi-Studios/NioDNS/commit/5e3b84b3c926e3b578befd69ceeffc7a50cd5fb3

ProtocolError while decoding response

When I try to decode a response, I get ProtocolError.

You can reproduce the issue with this test (the test server is no longer available):

func testComplexSRVRecords() throws {
    let expectation = self.expectation(description: "getComplexSRVRecords")
    
    var testComplexClient: DNSClient!
    
    do {
        let serverSocketAddress = try SocketAddress(ipAddress: "IP_ADDRESS(removed)", port: 5356)
        testComplexClient = try DNSClient.connect(on: group, config: [serverSocketAddress]).wait()
    } catch let error {
        XCTFail("\(error)")
    }
    
    let zone = "c7lu2ylhzmwmmaoa2xgie6nihfxrn25frxauuifp5lxvtjgw4icq====._wireguard._udp.exampleniodns.org."
    testComplexClient.getSRVRecords(from: zone)
    .whenComplete { (result) in
        switch result {
        case .failure(let error):
            XCTFail("\(error)")
        case .success(let answers):
            print(answers)
            XCTAssertGreaterThanOrEqual(answers.count, 1, "The returned answers should be greater than or equal to 1")
        }
        expectation.fulfill()
    }
    self.waitForExpectations(timeout: 5, handler: nil)
}

Running the same query with dig, I get the correct result:

$ dig @IP_ADDRESS(removed) -p 5356 c7lu2ylhzmwmmaoa2xgie6nihfxrn25frxauuifp5lxvtjgw4icq====._wireguard._udp.exampleniodns.org. SRV +noall +answer +additional

; <<>> DiG 9.10.6 <<>> @IP_ADDRESS(removed) -p 5356 c7lu2ylhzmwmmaoa2xgie6nihfxrn25frxauuifp5lxvtjgw4icq====._wireguard._udp.exampleniodns.org. SRV +noall +answer +additional
; (1 server found)
;; global options: +cmd
c7lu2ylhzmwmmaoa2xgie6nihfxrn25frxauuifp5lxvtjgw4icq====._wireguard._udp.exampleniodns.org. 0 IN SRV 0 0 51820 c7lu2ylhzmwmmaoa2xgie6nihfxrn25frxauuifp5lxvtjgw4icq====._wireguard._udp.exampleniodns.org.
c7lu2ylhzmwmmaoa2xgie6nihfxrn25frxauuifp5lxvtjgw4icq====._wireguard._udp.exampleniodns.org. 0 IN A 82.52.204.201
c7lu2ylhzmwmmaoa2xgie6nihfxrn25frxauuifp5lxvtjgw4icq====._wireguard._udp.exampleniodns.org. 0 IN TXT "txtvers=1" "pub=F9dNYWfLLMYBwNXMgnmoOW8W66WNwUogr+rvWaTW4gU=" "allowed=10.101.0.2/32"

The error is thrown at this line:
https://github.com/orlandos-nl/NioDNS/blob/de0b66fdedab85b4b84535df3efbef2e6605f89b/Sources/DNSClient/DNSDecoder.swift#L52-L54

while decoding additionalData
https://github.com/orlandos-nl/NioDNS/blob/de0b66fdedab85b4b84535df3efbef2e6605f89b/Sources/DNSClient/DNSDecoder.swift#L68

UPDATE 29/12/2021
The error is thrown while decoding TXT record
https://github.com/orlandos-nl/NioDNS/blob/de0b66fdedab85b4b84535df3efbef2e6605f89b/Sources/DNSClient/Helpers.swift#L154-L156

Publish on Cocoapods

It would be great if you could publish this package on Cocoapods as well. Some old applications that are still using it for package management would be able to use this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.