From 7214ac6aae55309d4fb8d45d713d7020fe3c7cc8 Mon Sep 17 00:00:00 2001 From: Boris Zhao Date: Sat, 28 Nov 2020 23:07:48 +0800 Subject: [PATCH 1/3] [bug fix] correctly comparing 2 IP addresses --- cmd/dnsupdater/main.go | 33 ++++++------- internal/{configs => common}/config.go | 15 +++--- internal/{configs => common}/config_test.go | 12 ++--- internal/{constants => common}/errormsg.go | 2 +- internal/common/ip_address_utils.go | 15 ++++++ internal/common/ip_address_utils_test.go | 31 ++++++++++++ internal/helper/aliyun/alidns_helper.go | 49 +++++++++---------- internal/helper/aliyun/alidns_helper_test.go | 8 +-- .../cloudflare/cloudflare_dns_helper.go | 49 +++++++++---------- .../cloudflare/cloudflare_dns_helper_test.go | 8 +-- scripts/Makefile | 2 +- sonar-project.properties | 2 +- 12 files changed, 134 insertions(+), 92 deletions(-) rename internal/{configs => common}/config.go (91%) rename internal/{configs => common}/config_test.go (80%) rename internal/{constants => common}/errormsg.go (99%) create mode 100644 internal/common/ip_address_utils.go create mode 100644 internal/common/ip_address_utils_test.go diff --git a/cmd/dnsupdater/main.go b/cmd/dnsupdater/main.go index 7d50008..1f0d7e8 100644 --- a/cmd/dnsupdater/main.go +++ b/cmd/dnsupdater/main.go @@ -3,8 +3,7 @@ package main import ( "errors" "flag" - "github.com/boris1993/dnsupdater/internal/configs" - "github.com/boris1993/dnsupdater/internal/constants" + "github.com/boris1993/dnsupdater/internal/common" "github.com/boris1993/dnsupdater/internal/helper/aliyun" "github.com/boris1993/dnsupdater/internal/helper/cloudflare" log "github.com/sirupsen/logrus" @@ -16,7 +15,7 @@ import ( func main() { var err error - config, err := configs.Get() + config, err := common.GetConfig() if err != nil { log.Fatalln(err) } @@ -31,7 +30,7 @@ func main() { // the currentIPv6Address will be an empty string var currentIPv6Address = "" if config.System.IPv6AddrAPI == "" { - log.Info(constants.MsgIPv6Disabled) + log.Info(common.MsgIPv6Disabled) } else { currentIPv6Address, err = getCurrentIPv6Address(*config) if err != nil { @@ -60,14 +59,14 @@ func main() { } func init() { - flag.StringVar(&configs.Path, "config", "", "Path to the config file.") - flag.BoolVar(&configs.Debug, "debug", false, "Enable debug logging.") + flag.StringVar(&common.ConfigFilePath, "config", "", "Path to the config file.") + flag.BoolVar(&common.Debug, "debug", false, "Enable debug logging.") flag.Parse() log.SetFormatter(&log.TextFormatter{DisableLevelTruncation: true}) - if configs.Debug == true { + if common.Debug == true { log.SetLevel(log.DebugLevel) } else { log.SetLevel(log.InfoLevel) @@ -75,12 +74,12 @@ func init() { } // getCurrentIPv4Address returns the external IP address for your network. -func getCurrentIPv4Address(config configs.Config) (string, error) { +func getCurrentIPv4Address(config common.Config) (string, error) { if config.System.IPAddrAPI == "" { - return "", errors.New(constants.ErrIPAddressFetchingAPIEmpty) + return "", errors.New(common.ErrIPAddressFetchingAPIEmpty) } - log.Println(constants.MsgCheckingCurrentIPv4Addr) + log.Println(common.MsgCheckingCurrentIPv4Addr) //region fetch your IPv4 address resp, err := http.Get(config.System.IPAddrAPI) @@ -93,7 +92,7 @@ func getCurrentIPv4Address(config configs.Config) (string, error) { err := resp.Body.Close() if err != nil { - log.Errorln(constants.ErrCloseHTTPConnectionFail, err) + log.Errorln(common.ErrCloseHTTPConnectionFail, err) } }() @@ -106,19 +105,19 @@ func getCurrentIPv4Address(config configs.Config) (string, error) { ipAddress := string(body) //endregion - log.Println(constants.MsgHeaderCurrentIPv4Addr, ipAddress) + log.Println(common.MsgHeaderCurrentIPv4Addr, ipAddress) return ipAddress, nil } // getCurrentIPv6Address returns the external IPv6 address for your network. // Typically this should be your "temporary" IPv6 address. -func getCurrentIPv6Address(config configs.Config) (string, error) { +func getCurrentIPv6Address(config common.Config) (string, error) { if config.System.IPv6AddrAPI == "" { - return "", errors.New(constants.ErrIPAddressFetchingAPIEmpty) + return "", errors.New(common.ErrIPAddressFetchingAPIEmpty) } - log.Println(constants.MsgCheckingCurrentIPv6Addr) + log.Println(common.MsgCheckingCurrentIPv6Addr) resp, err := http.Get(config.System.IPv6AddrAPI) if err != nil { @@ -130,7 +129,7 @@ func getCurrentIPv6Address(config configs.Config) (string, error) { err := resp.Body.Close() if err != nil { - log.Errorln(constants.ErrCloseHTTPConnectionFail, err) + log.Errorln(common.ErrCloseHTTPConnectionFail, err) } }() @@ -142,7 +141,7 @@ func getCurrentIPv6Address(config configs.Config) (string, error) { // Body only contains the IP address ipv6Address := string(body) - log.Println(constants.MsgHeaderCurrentIPv6Addr, ipv6Address) + log.Println(common.MsgHeaderCurrentIPv6Addr, ipv6Address) return ipv6Address, nil } diff --git a/internal/configs/config.go b/internal/common/config.go similarity index 91% rename from internal/configs/config.go rename to internal/common/config.go index 3cf74f3..24dab23 100644 --- a/internal/configs/config.go +++ b/internal/common/config.go @@ -1,8 +1,7 @@ // Package conf provides all models needed by this programme. -package configs +package common import ( - "github.com/boris1993/dnsupdater/internal/constants" log "github.com/sirupsen/logrus" "gopkg.in/yaml.v2" "io/ioutil" @@ -15,7 +14,7 @@ var once = new(sync.Once) var Debug bool -var Path string +var ConfigFilePath string var conf Config var errorInInitConfig error @@ -52,7 +51,7 @@ type AliDNS struct { DomainType string `yaml:"DomainType"` } -func Get() (*Config, error) { +func GetConfig() (*Config, error) { once.Do(func() { err := initConfig() @@ -71,18 +70,18 @@ func Get() (*Config, error) { // initConfig reads the Config.yaml and saves the properties in a variable. func initConfig() error { - if Path == "" { + if ConfigFilePath == "" { absPath, err := filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { return err } - Path = filepath.Join(absPath, "config.yaml") + ConfigFilePath = filepath.Join(absPath, "config.yaml") } - log.Println(constants.MsgHeaderLoadingConfig, Path) + log.Println(MsgHeaderLoadingConfig, ConfigFilePath) - bytes, err := ioutil.ReadFile(Path) + bytes, err := ioutil.ReadFile(ConfigFilePath) if err != nil { return err diff --git a/internal/configs/config_test.go b/internal/common/config_test.go similarity index 80% rename from internal/configs/config_test.go rename to internal/common/config_test.go index e45108f..cba42da 100644 --- a/internal/configs/config_test.go +++ b/internal/common/config_test.go @@ -1,4 +1,4 @@ -package configs +package common import ( "os" @@ -16,13 +16,13 @@ func TestGet(t *testing.T) { func testGetSuccess(t *testing.T) { Debug = true - Path = testResourcePath + "/test_config.yaml" - if _, err := os.Stat(Path); os.IsNotExist(err) { + ConfigFilePath = testResourcePath + "/test_config.yaml" + if _, err := os.Stat(ConfigFilePath); os.IsNotExist(err) { t.Errorf("test_config.yaml doesn't exist") return } - config, err := Get() + config, err := GetConfig() if err != nil { t.Error(err) return @@ -49,9 +49,9 @@ func testGetSuccess(t *testing.T) { func testGetFail(t *testing.T) { Debug = true - Path = testResourcePath + "/non_existent_config.yaml" + ConfigFilePath = testResourcePath + "/non_existent_config.yaml" - _, err := Get() + _, err := GetConfig() if err == nil { t.Error("TestGetFail should fail") } diff --git a/internal/constants/errormsg.go b/internal/common/errormsg.go similarity index 99% rename from internal/constants/errormsg.go rename to internal/common/errormsg.go index 9563aa5..5faf220 100644 --- a/internal/constants/errormsg.go +++ b/internal/common/errormsg.go @@ -1,5 +1,5 @@ // Package constants contains all constants needed in this programme -package constants +package common const MsgHeaderDNSRecordUpdateSuccessful = "Successfully updated the DNS record" const MsgHeaderCurrentIPv4Addr = "Current IPv4 address is:" diff --git a/internal/common/ip_address_utils.go b/internal/common/ip_address_utils.go new file mode 100644 index 0000000..a569501 --- /dev/null +++ b/internal/common/ip_address_utils.go @@ -0,0 +1,15 @@ +package common + +import "net" + +// CompareAddresses compares 2 given IP address string and see if they are the same IP address +func CompareAddresses(address1 string, address2 string) bool { + ipAddr1 := net.ParseIP(address1) + ipAddr2 := net.ParseIP(address2) + + if ipAddr1 == nil || ipAddr2 == nil { + return false + } + + return ipAddr1.Equal(ipAddr2) +} diff --git a/internal/common/ip_address_utils_test.go b/internal/common/ip_address_utils_test.go new file mode 100644 index 0000000..1665f9a --- /dev/null +++ b/internal/common/ip_address_utils_test.go @@ -0,0 +1,31 @@ +package common + +import "testing" + +func TestCompareAddresses(t *testing.T) { + var sameAddress bool + var failTestMessage = "%s and %s should be the same address" + + sameAddress = CompareAddresses("192.168.1.1", "192.168.001.001") + if !sameAddress { + t.Errorf(failTestMessage, "192.168.1.1", "192.168.001.001") + } + + sameAddress = CompareAddresses( + "2001:0db8:0000:0000:0000:ff00:0042:8329", "2001:db8:0:0:0:ff00:42:8329") + if !sameAddress { + t.Errorf(failTestMessage, "2001:0db8:0000:0000:0000:ff00:0042:8329", "2001:db8:0:0:0:ff00:42:8329") + } + + sameAddress = CompareAddresses( + "2001:0db8:0000:0000:0000:ff00:0042:8329", "2001:db8::ff00:42:8329") + if !sameAddress { + t.Errorf(failTestMessage, "2001:0db8:0000:0000:0000:ff00:0042:8329", "2001:db8::ff00:42:8329") + } + + sameAddress = CompareAddresses( + "2001:db8:0:0:0:ff00:42:8329", "2001:db8::ff00:42:8329") + if !sameAddress { + t.Errorf(failTestMessage, "2001:db8:0:0:0:ff00:42:8329", "2001:db8::ff00:42:8329") + } +} diff --git a/internal/helper/aliyun/alidns_helper.go b/internal/helper/aliyun/alidns_helper.go index 9d5323f..272e74c 100644 --- a/internal/helper/aliyun/alidns_helper.go +++ b/internal/helper/aliyun/alidns_helper.go @@ -3,8 +3,7 @@ package aliyun import ( "encoding/json" "errors" - "github.com/boris1993/dnsupdater/internal/configs" - "github.com/boris1993/dnsupdater/internal/constants" + "github.com/boris1993/dnsupdater/internal/common" log "github.com/sirupsen/logrus" "io/ioutil" "net/http" @@ -14,16 +13,16 @@ import ( // ProcessRecords takes the configuration as well as the current IP address // then check and update each DNS record in Aliyun DNS func ProcessRecords(currentIPv4Address string, currentIPv6Address string) error { - config, err := configs.Get() + config, err := common.GetConfig() if err != nil { return err } if config.System.AliyunAPIEndpoint == "" { - return errors.New(constants.ErrAliyunAPIAddressEmpty) + return errors.New(common.ErrAliyunAPIAddressEmpty) } - log.Println(len(config.AliDNSRecords), constants.MsgAliDNSRecordsFoundSuffix) + log.Println(len(config.AliDNSRecords), common.MsgAliDNSRecordsFoundSuffix) for _, aliDNSRecord := range config.AliDNSRecords { if aliDNSRecord.RegionID == "" || @@ -32,16 +31,16 @@ func ProcessRecords(currentIPv4Address string, currentIPv6Address string) error aliDNSRecord.DomainName == "" || aliDNSRecord.DomainType == "" { // Print error and skip to next record when bad configuration found - log.Errorln(constants.ErrAliDNSRecordConfigIncomplete) + log.Errorln(common.ErrAliDNSRecordConfigIncomplete) continue } if aliDNSRecord.DomainType != "A" && aliDNSRecord.DomainType != "AAAA" { - log.Errorln(constants.ErrInvalidDomainType) + log.Errorln(common.ErrInvalidDomainType) continue } - log.Println(constants.MsgHeaderDomainProcessing, aliDNSRecord.DomainName) + log.Println(common.MsgHeaderDomainProcessing, aliDNSRecord.DomainName) recordId, recordIP, err := getDomainRecordID(aliDNSRecord) if err != nil { @@ -49,9 +48,9 @@ func ProcessRecords(currentIPv4Address string, currentIPv6Address string) error continue } - if (aliDNSRecord.DomainType == "A" && recordIP == currentIPv4Address) || - (aliDNSRecord.DomainType == "AAAA" && recordIP == currentIPv6Address) { - log.Println(constants.MsgIPAddrNotChanged) + if (aliDNSRecord.DomainType == "A" && common.CompareAddresses(currentIPv4Address, recordIP)) || + (aliDNSRecord.DomainType == "AAAA" && common.CompareAddresses(currentIPv6Address, recordIP)) { + log.Println(common.MsgIPAddrNotChanged) continue } @@ -68,7 +67,7 @@ func ProcessRecords(currentIPv4Address string, currentIPv6Address string) error // If there's no valid IPv6 internet address, // then skip updating this record and head to the next one if currentIPv6Address == "" { - log.Info(constants.MsgIPv6AddrNotAvailable) + log.Info(common.MsgIPv6AddrNotAvailable) continue } @@ -82,9 +81,9 @@ func ProcessRecords(currentIPv4Address string, currentIPv6Address string) error } if !status { - log.Errorln(constants.ErrMsgHeaderUpdateDNSRecordFailed, aliDNSRecord.DomainName) + log.Errorln(common.ErrMsgHeaderUpdateDNSRecordFailed, aliDNSRecord.DomainName) } else { - log.Println(constants.MsgHeaderDNSRecordUpdateSuccessful, aliDNSRecord.DomainName) + log.Println(common.MsgHeaderDNSRecordUpdateSuccessful, aliDNSRecord.DomainName) } } @@ -94,8 +93,8 @@ func ProcessRecords(currentIPv4Address string, currentIPv6Address string) error // getDomainRecordID fetches the information of the specified record. // // See document: https://help.aliyun.com/document_detail/29776.html?spm=a2c4g.11186623.2.37.1de5425696HU8m#h2-u8FD4u56DEu53C2u65703 -func getDomainRecordID(aliDNSConfigRecord configs.AliDNS) (recordId string, recordAddress string, err error) { - config, err := configs.Get() +func getDomainRecordID(aliDNSConfigRecord common.AliDNS) (recordId string, recordAddress string, err error) { + config, err := common.GetConfig() if err != nil { return "", "", err } @@ -120,7 +119,7 @@ func getDomainRecordID(aliDNSConfigRecord configs.AliDNS) (recordId string, reco param, ) - log.Println(constants.MsgHeaderFetchingIPOfDomain, aliDNSConfigRecord.DomainName) + log.Println(common.MsgHeaderFetchingIPOfDomain, aliDNSConfigRecord.DomainName) httpClient := &http.Client{} response, err := httpClient.Do(request) @@ -133,7 +132,7 @@ func getDomainRecordID(aliDNSConfigRecord configs.AliDNS) (recordId string, reco err := response.Body.Close() if err != nil { - log.Errorln(constants.ErrCloseHTTPConnectionFail, err) + log.Errorln(common.ErrCloseHTTPConnectionFail, err) } }() if err != nil { @@ -157,7 +156,7 @@ func getDomainRecordID(aliDNSConfigRecord configs.AliDNS) (recordId string, reco } if len(describeDomainRecordsResponse.DomainRecords.Record) == 0 { - err := errors.New(constants.ErrNoDNSRecordFoundPrefix + aliDNSConfigRecord.DomainName) + err := errors.New(common.ErrNoDNSRecordFoundPrefix + aliDNSConfigRecord.DomainName) return "", "", err } @@ -165,7 +164,7 @@ func getDomainRecordID(aliDNSConfigRecord configs.AliDNS) (recordId string, reco // so I have to iterate the response and find the matched one. for _, domainRecord := range describeDomainRecordsResponse.DomainRecords.Record { if domainRecord.RR == hostRecord && domainRecord.Type == aliDNSConfigRecord.DomainType { - log.Printf(constants.MsgFormatAliDNSFetchResult, + log.Printf(common.MsgFormatAliDNSFetchResult, aliDNSConfigRecord.DomainName, domainRecord.Value, domainRecord.RecordID) @@ -176,14 +175,14 @@ func getDomainRecordID(aliDNSConfigRecord configs.AliDNS) (recordId string, reco return "", "", - errors.New(constants.ErrMsgHeaderFetchDomainInfoFailed + aliDNSConfigRecord.DomainName) + errors.New(common.ErrMsgHeaderFetchDomainInfoFailed + aliDNSConfigRecord.DomainName) } // Updates the IP address of the specified domain. // // See document: https://help.aliyun.com/document_detail/29774.html?spm=a2c4g.11186623.2.35.1de5425696HU8m -func updateAliDNSRecord(recordId string, RR string, currentIPAddress string, aliDNSConfigRecord configs.AliDNS) (bool, error) { - config, err := configs.Get() +func updateAliDNSRecord(recordId string, RR string, currentIPAddress string, aliDNSConfigRecord common.AliDNS) (bool, error) { + config, err := common.GetConfig() if err != nil { return false, err } @@ -202,7 +201,7 @@ func updateAliDNSRecord(recordId string, RR string, currentIPAddress string, ali param, ) - log.Printf(constants.MsgFormatUpdatingDNS, recordId, currentIPAddress) + log.Printf(common.MsgFormatUpdatingDNS, recordId, currentIPAddress) httpClient := &http.Client{} response, err := httpClient.Do(request) @@ -221,7 +220,7 @@ func updateAliDNSRecord(recordId string, RR string, currentIPAddress string, ali err := response.Body.Close() if err != nil { - log.Errorln(constants.ErrCloseHTTPConnectionFail, err) + log.Errorln(common.ErrCloseHTTPConnectionFail, err) } }() if err != nil { diff --git a/internal/helper/aliyun/alidns_helper_test.go b/internal/helper/aliyun/alidns_helper_test.go index 8d6c851..e9596ec 100644 --- a/internal/helper/aliyun/alidns_helper_test.go +++ b/internal/helper/aliyun/alidns_helper_test.go @@ -2,7 +2,7 @@ package aliyun import ( "encoding/json" - "github.com/boris1993/dnsupdater/internal/configs" + "github.com/boris1993/dnsupdater/internal/common" log "github.com/sirupsen/logrus" "io/ioutil" "net/http" @@ -13,7 +13,7 @@ import ( const testResourcePath = "../../test" var testHTTPServer *httptest.Server -var config *configs.Config +var config *common.Config var serverRecords []AliDNSRecord @@ -86,9 +86,9 @@ func stopTestHTTPServer() { func setEndpointToTestServer() error { var err error - configs.Path = testResourcePath + "/test_config.yaml" + common.ConfigFilePath = testResourcePath + "/test_config.yaml" - config, err = configs.Get() + config, err = common.GetConfig() if err != nil { return err } diff --git a/internal/helper/cloudflare/cloudflare_dns_helper.go b/internal/helper/cloudflare/cloudflare_dns_helper.go index 2ffdede..83e22f3 100644 --- a/internal/helper/cloudflare/cloudflare_dns_helper.go +++ b/internal/helper/cloudflare/cloudflare_dns_helper.go @@ -4,8 +4,7 @@ import ( "bytes" "encoding/json" "errors" - "github.com/boris1993/dnsupdater/internal/configs" - "github.com/boris1993/dnsupdater/internal/constants" + "github.com/boris1993/dnsupdater/internal/common" log "github.com/sirupsen/logrus" "io/ioutil" "net/http" @@ -14,16 +13,16 @@ import ( // ProcessRecords takes the configuration as well as the current IP address, // then check and update each DNS record in CloudFlare func ProcessRecords(currentIPv4Address string, currentIPv6Address string) error { - config, err := configs.Get() + config, err := common.GetConfig() if err != nil { return err } if config.System.CloudFlareAPIEndpoint == "" { - return errors.New(constants.ErrCloudFlareAPIAddressEmpty) + return errors.New(common.ErrCloudFlareAPIAddressEmpty) } - log.Println(len(config.CloudFlareRecords), constants.MsgCloudFlareRecordsFoundSuffix) + log.Println(len(config.CloudFlareRecords), common.MsgCloudFlareRecordsFoundSuffix) // Process each CloudFlare DNS record for _, cloudFlareRecord := range config.CloudFlareRecords { @@ -34,17 +33,17 @@ func ProcessRecords(currentIPv4Address string, currentIPv6Address string) error cloudFlareRecord.ZoneID == "" || cloudFlareRecord.DomainType == "" { // Print error and skip to next record when bad configuration found - log.Errorln(constants.ErrCloudFlareRecordConfigIncomplete) + log.Errorln(common.ErrCloudFlareRecordConfigIncomplete) continue } if cloudFlareRecord.DomainType != "A" && cloudFlareRecord.DomainType != "AAAA" { - log.Errorln(constants.ErrInvalidDomainType) + log.Errorln(common.ErrInvalidDomainType) continue } // Prints which record is being processed - log.Println(constants.MsgHeaderDomainProcessing, cloudFlareRecord.DomainName) + log.Println(common.MsgHeaderDomainProcessing, cloudFlareRecord.DomainName) // Then fetch the IP address of the specified DNS record id, recordAddress, err := getCFDnsRecordIpAddress(cloudFlareRecord) @@ -55,9 +54,9 @@ func ProcessRecords(currentIPv4Address string, currentIPv6Address string) error } // Do nothing when the IP address didn't change. - if (cloudFlareRecord.DomainType == "A" && currentIPv4Address == recordAddress) || - (cloudFlareRecord.DomainType == "AAAA" && currentIPv6Address == recordAddress) { - log.Println(constants.MsgIPAddrNotChanged) + if (cloudFlareRecord.DomainType == "A" && common.CompareAddresses(currentIPv4Address, recordAddress)) || + (cloudFlareRecord.DomainType == "AAAA" && common.CompareAddresses(currentIPv6Address, recordAddress)) { + log.Println(common.MsgIPAddrNotChanged) continue } else { var status bool @@ -72,7 +71,7 @@ func ProcessRecords(currentIPv4Address string, currentIPv6Address string) error // If there's no valid IPv6 internet address, // then skip updating this record and head to the next one if currentIPv6Address == "" { - log.Info(constants.MsgIPv6AddrNotAvailable) + log.Info(common.MsgIPv6AddrNotAvailable) continue } @@ -86,10 +85,10 @@ func ProcessRecords(currentIPv4Address string, currentIPv6Address string) error } if !status { - log.Errorln(constants.ErrMsgHeaderUpdateDNSRecordFailed, cloudFlareRecord.DomainName) + log.Errorln(common.ErrMsgHeaderUpdateDNSRecordFailed, cloudFlareRecord.DomainName) continue } else { - log.Println(constants.MsgHeaderDNSRecordUpdateSuccessful, cloudFlareRecord.DomainName) + log.Println(common.MsgHeaderDNSRecordUpdateSuccessful, cloudFlareRecord.DomainName) } } } @@ -105,8 +104,8 @@ func ProcessRecords(currentIPv4Address string, currentIPv6Address string) error // The first value returned is the ID of this DNS record, // the second value returned is the IP address of this record, // or an error will be returned if any error occurs. -func getCFDnsRecordIpAddress(cloudFlareRecord configs.CloudFlare) (string, string, error) { - config, err := configs.Get() +func getCFDnsRecordIpAddress(cloudFlareRecord common.CloudFlare) (string, string, error) { + config, err := common.GetConfig() if err != nil { return "", "", err } @@ -131,7 +130,7 @@ func getCFDnsRecordIpAddress(cloudFlareRecord configs.CloudFlare) (string, strin req.Header.Add("Authorization", "Bearer "+cloudFlareRecord.APIKey) req.Header.Add("Content-Type", "application/json") - log.Println(constants.MsgHeaderFetchingIPOfDomain, cloudFlareRecord.DomainName) + log.Println(common.MsgHeaderFetchingIPOfDomain, cloudFlareRecord.DomainName) resp, err := client.Do(req) if err != nil { @@ -166,22 +165,22 @@ func getCFDnsRecordIpAddress(cloudFlareRecord configs.CloudFlare) (string, strin err = resp.Body.Close() if err != nil { - log.Errorln(constants.ErrCloseHTTPConnectionFail, err) + log.Errorln(common.ErrCloseHTTPConnectionFail, err) } }() if len(cfAPIResponse.Result) == 0 { - return "", "", errors.New(constants.ErrNoDNSRecordFoundPrefix + cloudFlareRecord.DomainName) + return "", "", errors.New(common.ErrNoDNSRecordFoundPrefix + cloudFlareRecord.DomainName) } if !cfAPIResponse.Success { - return "", "", errors.New(constants.ErrMsgHeaderFetchDomainInfoFailed + cloudFlareRecord.DomainName) + return "", "", errors.New(common.ErrMsgHeaderFetchDomainInfoFailed + cloudFlareRecord.DomainName) } id := cfAPIResponse.Result[0].ID ipAddrInDns := cfAPIResponse.Result[0].Content - log.Printf(constants.MsgFormatDNSFetchResult, cloudFlareRecord.DomainName, ipAddrInDns) + log.Printf(common.MsgFormatDNSFetchResult, cloudFlareRecord.DomainName, ipAddrInDns) return id, ipAddrInDns, nil } @@ -192,8 +191,8 @@ func getCFDnsRecordIpAddress(cloudFlareRecord configs.CloudFlare) (string, strin // // The return value is the status(true or false) of the update process, // or an error will be returned if any error occurs. -func updateCFDNSRecord(id string, address string, cloudFlareRecord configs.CloudFlare) (bool, error) { - config, err := configs.Get() +func updateCFDNSRecord(id string, address string, cloudFlareRecord common.CloudFlare) (bool, error) { + config, err := common.GetConfig() if err != nil { return false, err } @@ -222,7 +221,7 @@ func updateCFDNSRecord(id string, address string, cloudFlareRecord configs.Cloud req.Header.Add("Authorization", "Bearer "+cloudFlareRecord.APIKey) req.Header.Add("Content-Type", "application/json") - log.Printf(constants.MsgFormatUpdatingDNS, cloudFlareRecord.DomainName, address) + log.Printf(common.MsgFormatUpdatingDNS, cloudFlareRecord.DomainName, address) resp, err := client.Do(req) @@ -235,7 +234,7 @@ func updateCFDNSRecord(id string, address string, cloudFlareRecord configs.Cloud err := resp.Body.Close() if err != nil { - log.Errorln(constants.ErrCloseHTTPConnectionFail, err) + log.Errorln(common.ErrCloseHTTPConnectionFail, err) } }() diff --git a/internal/helper/cloudflare/cloudflare_dns_helper_test.go b/internal/helper/cloudflare/cloudflare_dns_helper_test.go index 962bf04..a467690 100644 --- a/internal/helper/cloudflare/cloudflare_dns_helper_test.go +++ b/internal/helper/cloudflare/cloudflare_dns_helper_test.go @@ -2,7 +2,7 @@ package cloudflare import ( "encoding/json" - "github.com/boris1993/dnsupdater/internal/configs" + "github.com/boris1993/dnsupdater/internal/common" log "github.com/sirupsen/logrus" "io/ioutil" "net/http" @@ -13,7 +13,7 @@ import ( const testResourcePath = "../../test" var testHTTPServer *httptest.Server -var config *configs.Config +var config *common.Config var serverRecords []cfDnsRecordResult @@ -96,9 +96,9 @@ func stopTestHTTPServer() { func setEndpointToTestServer() error { var err error - configs.Path = testResourcePath + "/test_config.yaml" + common.ConfigFilePath = testResourcePath + "/test_config.yaml" - config, err = configs.Get() + config, err = common.GetConfig() if err != nil { return err } diff --git a/scripts/Makefile b/scripts/Makefile index 40bc4ed..dc94491 100644 --- a/scripts/Makefile +++ b/scripts/Makefile @@ -17,7 +17,7 @@ help: @echo All 4 targets will be built if target is not specified test: - $(GOTEST) $(GOTEST_ARGS) $(ROOT_DIR)/internal/helper/* $(ROOT_DIR)/internal/configs + $(GOTEST) $(GOTEST_ARGS) $(ROOT_DIR)/internal/... windows-amd64: GOARCH=amd64 GOOS=windows $(GOBUILD) $(BUILD_ARGS) -o $(ROOT_DIR)/bin/$(APP_NAME)-windows-amd64/$(APP_NAME).exe $(ROOT_DIR)/cmd/dnsupdater/main.go diff --git a/sonar-project.properties b/sonar-project.properties index 183ebf2..8f6a889 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -4,4 +4,4 @@ sonar.sources=. sonar.login=7c23b6082cd33e6b7a7c011de649823ed2f9d3fa sonar.organization=boris1993-github sonar.go.coverage.reportPaths=coverage.out -sonar.coverage.exclusions=**/*_test.go,**/constants/**,**/constants.go,cmd/** +sonar.coverage.exclusions=**/*_test.go,**/errormsg.go,**/constants.go,cmd/** From 191dba94d12779910798e9d4752239a9b0c8d3a5 Mon Sep 17 00:00:00 2001 From: Boris Zhao Date: Sat, 28 Nov 2020 23:14:59 +0800 Subject: [PATCH 2/3] Add test case for ip_address_utils_test.go --- internal/common/ip_address_utils_test.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/internal/common/ip_address_utils_test.go b/internal/common/ip_address_utils_test.go index 1665f9a..0e3225a 100644 --- a/internal/common/ip_address_utils_test.go +++ b/internal/common/ip_address_utils_test.go @@ -28,4 +28,9 @@ func TestCompareAddresses(t *testing.T) { if !sameAddress { t.Errorf(failTestMessage, "2001:db8:0:0:0:ff00:42:8329", "2001:db8::ff00:42:8329") } + + sameAddress = CompareAddresses("not valid address", "not valid address") + if sameAddress { + t.Error("Should return false when comparing invalid IP addresses") + } } From ea1c4e182fd446c05b3a49060a881b7e98b3490f Mon Sep 17 00:00:00 2001 From: Boris Zhao Date: Sat, 28 Nov 2020 23:20:13 +0800 Subject: [PATCH 3/3] Exclude test files from scanning by Sonar --- sonar-project.properties | 1 + 1 file changed, 1 insertion(+) diff --git a/sonar-project.properties b/sonar-project.properties index 8f6a889..980a307 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -4,4 +4,5 @@ sonar.sources=. sonar.login=7c23b6082cd33e6b7a7c011de649823ed2f9d3fa sonar.organization=boris1993-github sonar.go.coverage.reportPaths=coverage.out +sonar.exclusions=**/*_test.go sonar.coverage.exclusions=**/*_test.go,**/errormsg.go,**/constants.go,cmd/**