2020-04-14 19:20:00 -04:00
package client
import (
2025-10-04 10:52:34 +08:00
"bytes"
2025-09-11 04:48:49 -07:00
"context"
2020-10-04 17:01:10 -04:00
"crypto/tls"
2021-06-05 21:47:11 +02:00
"crypto/x509"
2025-09-15 21:52:57 +08:00
"encoding/hex"
2025-09-28 14:26:12 -04:00
"encoding/json"
2021-06-05 16:35:52 -04:00
"errors"
2022-11-15 21:35:22 -05:00
"fmt"
2025-01-19 23:22:41 +02:00
"io"
2020-10-04 19:49:02 -04:00
"net"
2020-04-14 19:20:00 -04:00
"net/http"
2021-06-05 21:47:11 +02:00
"net/smtp"
2025-11-04 20:42:20 -05:00
"os"
2021-07-18 20:43:44 -04:00
"runtime"
2021-06-05 21:47:11 +02:00
"strings"
2020-04-14 19:20:00 -04:00
"time"
2020-12-25 00:07:18 -05:00
2022-11-15 21:35:22 -05:00
"github.com/TwiN/gocache/v2"
2025-02-17 10:22:44 -05:00
"github.com/TwiN/logr"
2022-11-15 21:35:22 -05:00
"github.com/TwiN/whois"
2025-12-18 23:44:44 +00:00
"github.com/gorilla/websocket"
2022-11-10 08:22:13 +08:00
"github.com/ishidawataru/sctp"
2024-05-09 22:56:16 -04:00
"github.com/miekg/dns"
2023-03-26 23:26:40 +02:00
ping "github.com/prometheus-community/pro-bing"
2025-09-11 23:32:19 +03:00
"github.com/registrobr/rdap"
"github.com/registrobr/rdap/protocol"
2023-09-23 14:37:24 -03:00
"golang.org/x/crypto/ssh"
2020-04-14 19:20:00 -04:00
)
2024-05-09 22:56:16 -04:00
const (
dnsPort = 53
)
2022-11-15 21:35:22 -05:00
var (
// injectedHTTPClient is used for testing purposes
injectedHTTPClient * http . Client
whoisClient = whois . NewClient (). WithReferralCache ( true )
whoisExpirationDateCache = gocache . NewCache (). WithMaxSize ( 10000 ). WithDefaultTTL ( 24 * time . Hour )
2025-09-11 23:32:19 +03:00
rdapClient = rdap . NewClient ( nil )
2022-11-15 21:35:22 -05:00
)
2021-12-02 23:10:21 -05:00
2022-07-28 19:35:15 -04:00
// GetHTTPClient returns the shared HTTP client, or the client from the configuration passed
2021-07-28 21:41:26 -04:00
func GetHTTPClient ( config * Config ) * http . Client {
2021-12-02 23:10:21 -05:00
if injectedHTTPClient != nil {
return injectedHTTPClient
}
2021-07-29 18:13:37 -04:00
if config == nil {
return defaultConfig . getHTTPClient ()
}
return config . getHTTPClient ()
2020-04-14 19:20:00 -04:00
}
2020-10-04 19:49:02 -04:00
2022-11-15 21:35:22 -05:00
// GetDomainExpiration retrieves the duration until the domain provided expires
func GetDomainExpiration ( hostname string ) ( domainExpiration time . Duration , err error ) {
var retrievedCachedValue bool
if v , exists := whoisExpirationDateCache . Get ( hostname ); exists {
domainExpiration = time . Until ( v .( time . Time ))
retrievedCachedValue = true
// If the domain OR the TTL is not going to expire in less than 24 hours
// we don't have to refresh the cache. Otherwise, we'll refresh it.
cacheEntryTTL , _ := whoisExpirationDateCache . TTL ( hostname )
if cacheEntryTTL > 24 * time . Hour && domainExpiration > 24 * time . Hour {
// No need to refresh, so we'll just return the cached values
return domainExpiration , nil
}
}
2025-09-11 23:32:19 +03:00
whoisResponse , err := rdapQuery ( hostname )
if err != nil {
// fallback to WHOIS protocol
whoisResponse , err = whoisClient . QueryAndParse ( hostname )
}
if err != nil {
2022-11-15 21:35:22 -05:00
if ! retrievedCachedValue { // Add an error unless we already retrieved a cached value
return 0 , fmt . Errorf ( "error querying and parsing hostname using whois client: %w" , err )
}
} else {
domainExpiration = time . Until ( whoisResponse . ExpirationDate )
if domainExpiration > 720 * time . Hour {
whoisExpirationDateCache . SetWithTTL ( hostname , whoisResponse . ExpirationDate , 240 * time . Hour )
} else {
whoisExpirationDateCache . SetWithTTL ( hostname , whoisResponse . ExpirationDate , 72 * time . Hour )
}
}
return domainExpiration , nil
}
2025-07-19 19:24:03 -06:00
// parseLocalAddressPlaceholder returns a string with the local address replaced
func parseLocalAddressPlaceholder ( item string , localAddr net . Addr ) string {
item = strings . ReplaceAll ( item , "[LOCAL_ADDRESS]" , localAddr . String ())
return item
2020-10-04 19:49:02 -04:00
}
2020-12-25 00:07:18 -05:00
2025-07-19 19:24:03 -06:00
// CanCreateNetworkConnection checks whether a connection can be established with a TCP or UDP endpoint
func CanCreateNetworkConnection ( netType string , address string , body string , config * Config ) ( bool , [] byte ) {
const (
MaximumMessageSize = 1024 // in bytes
)
connection , err := net . DialTimeout ( netType , address , config . Timeout )
2022-11-10 08:22:13 +08:00
if err != nil {
2025-07-19 19:24:03 -06:00
return false , nil
}
defer connection . Close ()
if body != "" {
body = parseLocalAddressPlaceholder ( body , connection . LocalAddr ())
connection . SetDeadline ( time . Now (). Add ( config . Timeout ))
_ , err = connection . Write ([] byte ( body ))
if err != nil {
return false , nil
}
buf := make ([] byte , MaximumMessageSize )
n , err := connection . Read ( buf )
if err != nil {
return false , nil
}
return true , buf [: n ]
2022-11-10 08:22:13 +08:00
}
2025-07-19 19:24:03 -06:00
return true , nil
2022-11-10 08:22:13 +08:00
}
// CanCreateSCTPConnection checks whether a connection can be established with a SCTP endpoint
func CanCreateSCTPConnection ( address string , config * Config ) bool {
2025-01-14 10:30:15 +06:00
ch := make ( chan bool , 1 )
2022-11-10 08:22:13 +08:00
go ( func ( res chan bool ) {
addr , err := sctp . ResolveSCTPAddr ( "sctp" , address )
if err != nil {
res <- false
2025-01-14 10:30:15 +06:00
return
2022-11-10 08:22:13 +08:00
}
conn , err := sctp . DialSCTP ( "sctp" , nil , addr )
if err != nil {
res <- false
2025-01-14 10:30:15 +06:00
return
2022-11-10 08:22:13 +08:00
}
_ = conn . Close ()
res <- true
})( ch )
select {
case result := <- ch :
return result
case <- time . After ( config . Timeout ):
return false
}
}
2021-06-05 16:35:52 -04:00
// CanPerformStartTLS checks whether a connection can be established to an address using the STARTTLS protocol
2021-07-28 21:41:26 -04:00
func CanPerformStartTLS ( address string , config * Config ) ( connected bool , certificate * x509 . Certificate , err error ) {
2021-06-05 16:35:52 -04:00
hostAndPort := strings . Split ( address , ":" )
if len ( hostAndPort ) != 2 {
return false , nil , errors . New ( "invalid address for starttls, format must be host:port" )
2021-06-05 21:47:11 +02:00
}
2025-09-11 04:48:49 -07:00
var connection net . Conn
var dnsResolver * DNSResolverConfig
if config . HasCustomDNSResolver () {
dnsResolver , err = config . parseDNSResolver ()
if err != nil {
// We're ignoring the error, because it should have been validated on startup ValidateAndSetDefaults.
// It shouldn't happen, but if it does, we'll log it... Better safe than sorry ;)
logr . Errorf ( "[client.getHTTPClient] THIS SHOULD NOT HAPPEN. Silently ignoring invalid DNS resolver due to error: %s" , err . Error ())
} else {
dialer := & net . Dialer {
Resolver : & net . Resolver {
PreferGo : true ,
Dial : func ( ctx context . Context , network , address string ) ( net . Conn , error ) {
d := net . Dialer {}
return d . DialContext ( ctx , dnsResolver . Protocol , dnsResolver . Host + ":" + dnsResolver . Port )
},
},
}
connection , err = dialer . DialContext ( context . Background (), "tcp" , address )
if err != nil {
return
}
}
} else {
connection , err = net . DialTimeout ( "tcp" , address , config . Timeout )
if err != nil {
return
}
2021-09-30 22:15:17 +02:00
}
2025-09-11 04:48:49 -07:00
2021-09-30 20:56:09 -04:00
smtpClient , err := smtp . NewClient ( connection , hostAndPort [ 0 ])
2021-06-05 21:47:11 +02:00
if err != nil {
return
}
2021-06-05 16:35:52 -04:00
err = smtpClient . StartTLS ( & tls . Config {
2021-07-28 21:41:26 -04:00
InsecureSkipVerify : config . Insecure ,
2021-06-05 16:35:52 -04:00
ServerName : hostAndPort [ 0 ],
})
2021-06-05 21:47:11 +02:00
if err != nil {
return
}
2021-06-05 16:35:52 -04:00
if state , ok := smtpClient . TLSConnectionState (); ok {
2021-06-05 21:47:11 +02:00
certificate = state . PeerCertificates [ 0 ]
} else {
2021-06-05 16:35:52 -04:00
return false , nil , errors . New ( "could not get TLS connection state" )
2021-06-05 21:47:11 +02:00
}
2021-06-05 16:35:52 -04:00
return true , certificate , nil
2021-06-05 21:47:11 +02:00
}
2021-09-30 22:15:17 +02:00
// CanPerformTLS checks whether a connection can be established to an address using the TLS protocol
2025-07-19 19:24:03 -06:00
func CanPerformTLS ( address string , body string , config * Config ) ( connected bool , response [] byte , certificate * x509 . Certificate , err error ) {
const (
MaximumMessageSize = 1024 // in bytes
)
2023-08-09 10:17:26 +08:00
connection , err := tls . DialWithDialer ( & net . Dialer { Timeout : config . Timeout }, "tcp" , address , & tls . Config {
InsecureSkipVerify : config . Insecure ,
})
2021-09-30 22:15:17 +02:00
if err != nil {
2021-09-30 20:45:47 -04:00
return
2021-09-30 22:15:17 +02:00
}
2021-09-30 20:45:47 -04:00
defer connection . Close ()
verifiedChains := connection . ConnectionState (). VerifiedChains
2023-08-09 10:17:26 +08:00
// If config.Insecure is set to true, verifiedChains will be an empty list []
// We should get the parsed certificates from PeerCertificates, it can't be empty on the client side
// Reference: https://pkg.go.dev/crypto/tls#PeerCertificates
2021-09-30 20:45:47 -04:00
if len ( verifiedChains ) == 0 || len ( verifiedChains [ 0 ]) == 0 {
2023-08-09 10:17:26 +08:00
peerCertificates := connection . ConnectionState (). PeerCertificates
2025-07-19 19:24:03 -06:00
certificate = peerCertificates [ 0 ]
} else {
certificate = verifiedChains [ 0 ][ 0 ]
}
connected = true
if body != "" {
body = parseLocalAddressPlaceholder ( body , connection . LocalAddr ())
connection . SetDeadline ( time . Now (). Add ( config . Timeout ))
_ , err = connection . Write ([] byte ( body ))
if err != nil {
return
}
buf := make ([] byte , MaximumMessageSize )
var n int
n , err = connection . Read ( buf )
if err != nil {
return
}
response = buf [: n ]
2021-09-30 22:15:17 +02:00
}
2025-07-19 19:24:03 -06:00
return
2021-09-30 22:15:17 +02:00
}
2023-09-23 14:37:24 -03:00
// CanCreateSSHConnection checks whether a connection can be established and a command can be executed to an address
// using the SSH protocol.
2025-11-20 03:06:36 +05:30
func CanCreateSSHConnection ( address , username , password , privateKey string , config * Config ) ( bool , * ssh . Client , error ) {
2023-09-23 14:37:24 -03:00
var port string
if strings . Contains ( address , ":" ) {
addressAndPort := strings . Split ( address , ":" )
if len ( addressAndPort ) != 2 {
return false , nil , errors . New ( "invalid address for ssh, format must be host:port" )
}
address = addressAndPort [ 0 ]
port = addressAndPort [ 1 ]
} else {
port = "22"
}
2025-11-20 03:06:36 +05:30
// Build auth methods: prefer parsed private key if provided, fall back to password.
var authMethods [] ssh . AuthMethod
if len ( privateKey ) > 0 {
if signer , err := ssh . ParsePrivateKey ([] byte ( privateKey )); err == nil {
authMethods = append ( authMethods , ssh . PublicKeys ( signer ))
} else {
return false , nil , fmt . Errorf ( "invalid private key: %w" , err )
}
}
if len ( password ) > 0 {
authMethods = append ( authMethods , ssh . Password ( password ))
}
cli , err := ssh . Dial ( "tcp" , net . JoinHostPort ( address , port ), & ssh . ClientConfig {
2023-09-23 14:37:24 -03:00
HostKeyCallback : ssh . InsecureIgnoreHostKey (),
User : username ,
2025-11-20 03:06:36 +05:30
Auth : authMethods ,
Timeout : config . Timeout ,
2023-09-23 14:37:24 -03:00
})
if err != nil {
return false , nil , err
}
return true , cli , nil
}
2025-01-19 23:22:41 +02:00
func CheckSSHBanner ( address string , cfg * Config ) ( bool , int , error ) {
var port string
if strings . Contains ( address , ":" ) {
addressAndPort := strings . Split ( address , ":" )
if len ( addressAndPort ) != 2 {
return false , 1 , errors . New ( "invalid address for ssh, format must be ssh://host:port" )
}
address = addressAndPort [ 0 ]
port = addressAndPort [ 1 ]
} else {
port = "22"
}
dialer := net . Dialer {}
connStr := net . JoinHostPort ( address , port )
conn , err := dialer . Dial ( "tcp" , connStr )
if err != nil {
return false , 1 , err
}
defer conn . Close ()
conn . SetReadDeadline ( time . Now (). Add ( time . Second ))
buf := make ([] byte , 256 )
_ , err = io . ReadAtLeast ( conn , buf , 1 )
if err != nil {
return false , 1 , err
}
return true , 0 , err
}
2023-09-23 14:37:24 -03:00
// ExecuteSSHCommand executes a command to an address using the SSH protocol.
2025-10-04 10:52:34 +08:00
func ExecuteSSHCommand ( sshClient * ssh . Client , body string , config * Config ) ( bool , int , [] byte , error ) {
2023-09-23 14:37:24 -03:00
type Body struct {
Command string `json:"command"`
}
defer sshClient . Close ()
var b Body
2025-07-19 19:24:03 -06:00
body = parseLocalAddressPlaceholder ( body , sshClient . Conn . LocalAddr ())
2023-09-23 14:37:24 -03:00
if err := json . Unmarshal ([] byte ( body ), & b ); err != nil {
2025-10-04 10:52:34 +08:00
return false , 0 , nil , err
2023-09-23 14:37:24 -03:00
}
sess , err := sshClient . NewSession ()
if err != nil {
2025-10-04 10:52:34 +08:00
return false , 0 , nil , err
2023-09-23 14:37:24 -03:00
}
2025-10-04 10:52:34 +08:00
// Capture stdout
var stdout bytes . Buffer
sess . Stdout = & stdout
2023-09-23 14:37:24 -03:00
err = sess . Start ( b . Command )
if err != nil {
2025-10-04 10:52:34 +08:00
return false , 0 , nil , err
2023-09-23 14:37:24 -03:00
}
defer sess . Close ()
err = sess . Wait ()
2025-10-04 10:52:34 +08:00
output := stdout . Bytes ()
2023-09-23 14:37:24 -03:00
if err == nil {
2025-10-04 10:52:34 +08:00
return true , 0 , output , nil
2023-09-23 14:37:24 -03:00
}
2024-11-13 23:54:00 -05:00
var exitErr * ssh . ExitError
if ok := errors . As ( err , & exitErr ); ! ok {
2025-10-04 10:52:34 +08:00
return false , 0 , nil , err
2023-09-23 14:37:24 -03:00
}
2025-10-04 10:52:34 +08:00
return true , exitErr . ExitStatus (), output , nil
2023-09-23 14:37:24 -03:00
}
2020-12-27 17:07:50 -05:00
// Ping checks if an address can be pinged and returns the round-trip time if the address can be pinged
//
2020-12-25 00:07:18 -05:00
// Note that this function takes at least 100ms, even if the address is 127.0.0.1
2021-07-28 21:41:26 -04:00
func Ping ( address string , config * Config ) ( bool , time . Duration ) {
2024-02-07 03:15:51 +01:00
pinger := ping . New ( address )
2020-12-25 00:07:18 -05:00
pinger . Count = 1
2021-07-28 21:41:26 -04:00
pinger . Timeout = config . Timeout
2025-11-04 20:42:20 -05:00
pinger . SetPrivileged ( ShouldRunPingerAsPrivileged ())
2024-02-07 03:15:51 +01:00
pinger . SetNetwork ( config . Network )
err := pinger . Run ()
2020-12-25 00:07:18 -05:00
if err != nil {
2020-12-27 17:07:50 -05:00
return false , 0
2020-12-25 00:07:18 -05:00
}
2020-12-27 17:07:50 -05:00
if pinger . Statistics () != nil {
2021-01-12 21:08:18 -05:00
// If the packet loss is 100, it means that the packet didn't reach the host
if pinger . Statistics (). PacketLoss == 100 {
return false , pinger . Timeout
}
2020-12-27 17:07:50 -05:00
return true , pinger . Statistics (). MaxRtt
}
return true , 0
2020-12-25 00:07:18 -05:00
}
2021-12-02 23:10:21 -05:00
2025-11-04 20:42:20 -05:00
// ShouldRunPingerAsPrivileged will determine whether or not to run pinger in privileged mode.
// It should be set to privileged when running as root, and always on windows. See https://pkg.go.dev/github.com/macrat/go-parallel-pinger#Pinger.SetPrivileged
func ShouldRunPingerAsPrivileged () bool {
// Set the pinger's privileged mode to false for darwin
// See https://github.com/TwiN/gatus/issues/132
// linux should also be set to false, but there are potential complications
// See https://github.com/TwiN/gatus/pull/748 and https://github.com/TwiN/gatus/issues/697#issuecomment-2081700989
//
// Note that for this to work on Linux, Gatus must run with sudo privileges. (in certain cases)
// See https://github.com/prometheus-community/pro-bing#linux
if runtime . GOOS == "windows" {
return true
}
// To actually check for cap_net_raw capabilities, we would need to add "kernel.org/pub/linux/libs/security/libcap/cap" to gatus.
// Or use a syscall and check for permission errors, but this requires platform specific compilation
// As a backstop we can simply check the effective user id and run as privileged when running as root
return os . Geteuid () == 0
}
2023-09-28 18:35:18 -04:00
// QueryWebSocket opens a websocket connection, write `body` and return a message from the server
2025-08-02 21:06:46 +03:00
func QueryWebSocket ( address , body string , headers map [ string ] string , config * Config ) ( bool , [] byte , error ) {
2023-08-08 23:12:37 -03:00
const (
2025-12-18 23:44:44 +00:00
Origin = "http://localhost/"
2023-08-08 23:12:37 -03:00
)
2025-12-18 23:44:44 +00:00
var (
dialer = websocket . Dialer {
EnableCompression : true ,
2025-08-02 21:06:46 +03:00
}
2025-12-18 23:44:44 +00:00
wsHeaders = make ( http . Header )
)
wsHeaders . Set ( "Origin" , Origin )
for name , value := range headers {
wsHeaders . Set ( name , value )
2025-08-02 21:06:46 +03:00
}
2025-12-18 23:44:44 +00:00
ctx := context . Background ()
2023-09-28 18:35:18 -04:00
if config != nil {
2025-12-18 23:44:44 +00:00
if config . Timeout > 0 {
var cancel context . CancelFunc
ctx , cancel = context . WithTimeout ( ctx , config . Timeout )
defer cancel ()
}
dialer . TLSClientConfig = & tls . Config {
2025-07-29 18:49:36 +00:00
InsecureSkipVerify : config . Insecure ,
}
if config . HasTLSConfig () && config . TLS . isValid () == nil {
2025-12-18 23:44:44 +00:00
dialer . TLSClientConfig = configureTLS ( dialer . TLSClientConfig , * config . TLS )
2025-07-29 18:49:36 +00:00
}
2023-09-28 18:35:18 -04:00
}
2023-08-08 23:12:37 -03:00
// Dial URL
2025-12-18 23:44:44 +00:00
ws , _ , err := dialer . DialContext ( ctx , address , wsHeaders )
2023-08-08 23:12:37 -03:00
if err != nil {
return false , nil , fmt . Errorf ( "error dialing websocket: %w" , err )
}
defer ws . Close ()
2025-07-19 19:24:03 -06:00
body = parseLocalAddressPlaceholder ( body , ws . LocalAddr ())
2023-08-08 23:12:37 -03:00
// Write message
2025-12-18 23:44:44 +00:00
if err := ws . WriteMessage ( websocket . TextMessage , [] byte ( body )); err != nil {
2023-08-08 23:12:37 -03:00
return false , nil , fmt . Errorf ( "error writing websocket body: %w" , err )
}
// Read message
2025-12-18 23:44:44 +00:00
msgType , msg , err := ws . ReadMessage ()
if err != nil {
2023-08-08 23:12:37 -03:00
return false , nil , fmt . Errorf ( "error reading websocket message: %w" , err )
2025-12-18 23:44:44 +00:00
} else if msgType != websocket . TextMessage && msgType != websocket . BinaryMessage {
return false , nil , fmt . Errorf ( "unexpected websocket message type: %d, expected %d or %d" , msgType , websocket . TextMessage , websocket . BinaryMessage )
2023-08-08 23:12:37 -03:00
}
2025-12-18 23:44:44 +00:00
return true , msg , nil
2023-08-08 23:12:37 -03:00
}
2024-05-09 22:56:16 -04:00
func QueryDNS ( queryType , queryName , url string ) ( connected bool , dnsRcode string , body [] byte , err error ) {
if ! strings . Contains ( url , ":" ) {
url = fmt . Sprintf ( "%s:%d" , url , dnsPort )
}
queryTypeAsUint16 := dns . StringToType [ queryType ]
2025-09-15 21:52:57 +08:00
// Special handling: if this is a PTR query and queryName looks like a plain IP,
// convert it to the proper reverse lookup domain automatically.
if queryTypeAsUint16 == dns . TypePTR &&
! strings . HasSuffix ( queryName , ".in-addr.arpa." ) &&
! strings . HasSuffix ( queryName , ".ip6.arpa." ) {
if rev , convErr := reverseNameForIP ( queryName ); convErr == nil {
queryName = rev
} else {
return false , "" , nil , convErr
}
}
2024-05-09 22:56:16 -04:00
c := new ( dns . Client )
m := new ( dns . Msg )
m . SetQuestion ( queryName , queryTypeAsUint16 )
r , _ , err := c . Exchange ( m , url )
if err != nil {
2025-02-17 10:22:44 -05:00
logr . Infof ( "[client.QueryDNS] Error exchanging DNS message: %v" , err )
2024-05-09 22:56:16 -04:00
return false , "" , nil , err
}
connected = true
dnsRcode = dns . RcodeToString [ r . Rcode ]
for _ , rr := range r . Answer {
switch rr . Header (). Rrtype {
case dns . TypeA :
if a , ok := rr .( * dns . A ); ok {
body = [] byte ( a . A . String ())
}
case dns . TypeAAAA :
if aaaa , ok := rr .( * dns . AAAA ); ok {
body = [] byte ( aaaa . AAAA . String ())
}
case dns . TypeCNAME :
if cname , ok := rr .( * dns . CNAME ); ok {
body = [] byte ( cname . Target )
}
case dns . TypeMX :
if mx , ok := rr .( * dns . MX ); ok {
body = [] byte ( mx . Mx )
}
case dns . TypeNS :
if ns , ok := rr .( * dns . NS ); ok {
body = [] byte ( ns . Ns )
}
2024-11-28 23:21:44 +00:00
case dns . TypePTR :
if ptr , ok := rr .( * dns . PTR ); ok {
body = [] byte ( ptr . Ptr )
}
2025-02-17 10:22:44 -05:00
case dns . TypeSRV :
if srv , ok := rr .( * dns . SRV ); ok {
body = [] byte ( fmt . Sprintf ( "%s:%d" , srv . Target , srv . Port ))
}
2024-05-09 22:56:16 -04:00
default :
body = [] byte ( "query type is not supported yet" )
}
}
return connected , dnsRcode , body , nil
}
2021-12-02 23:10:21 -05:00
// InjectHTTPClient is used to inject a custom HTTP client for testing purposes
func InjectHTTPClient ( httpClient * http . Client ) {
injectedHTTPClient = httpClient
}
2025-09-11 23:32:19 +03:00
// rdapQuery returns domain expiration via RDAP protocol
func rdapQuery ( hostname string ) ( * whois . Response , error ) {
data , _ , err := rdapClient . Query ( hostname , nil , nil )
if err != nil {
return nil , err
}
domain , ok := data .( * protocol . Domain )
if ! ok {
return nil , errors . New ( "invalid domain type" )
}
response := whois . Response {}
for _ , e := range domain . Events {
if e . Action == "expiration" {
response . ExpirationDate = e . Date . Time
break
}
}
2026-04-01 08:02:04 +08:00
if response . ExpirationDate . IsZero () {
return nil , fmt . Errorf ( "no expiration event found in RDAP response for %s" , hostname )
}
2025-09-11 23:32:19 +03:00
return & response , nil
}
2025-09-15 21:52:57 +08:00
// helper to reverse IP and add in-addr.arpa. IPv4 and IPv6
func reverseNameForIP ( ipStr string ) ( string , error ) {
ip := net . ParseIP ( ipStr )
if ip == nil {
return "" , fmt . Errorf ( "invalid IP: %s" , ipStr )
}
if ipv4 := ip . To4 (); ipv4 != nil {
parts := strings . Split ( ipv4 . String (), "." )
for i , j := 0 , len ( parts ) - 1 ; i < j ; i , j = i + 1 , j - 1 {
parts [ i ], parts [ j ] = parts [ j ], parts [ i ]
}
return strings . Join ( parts , "." ) + ".in-addr.arpa." , nil
}
ip = ip . To16 ()
hexStr := hex . EncodeToString ( ip )
nibbles := strings . Split ( hexStr , "" )
for i , j := 0 , len ( nibbles ) - 1 ; i < j ; i , j = i + 1 , j - 1 {
nibbles [ i ], nibbles [ j ] = nibbles [ j ], nibbles [ i ]
}
return strings . Join ( nibbles , "." ) + ".ip6.arpa." , nil
2025-09-28 14:26:12 -04:00
}