Skip to content

Commit 6992fad

Browse files
methaneBrigitte Lamarche
authored and
Brigitte Lamarche
committed
Fix tls=true didn't work with host without port (go-sql-driver#718)
Fixes go-sql-driver#717
1 parent 9031984 commit 6992fad

File tree

2 files changed

+37
-11
lines changed

2 files changed

+37
-11
lines changed

dsn.go

+9-11
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,15 @@ func (cfg *Config) normalize() error {
9595
cfg.Addr = ensureHavePort(cfg.Addr)
9696
}
9797

98+
if cfg.tls != nil {
99+
if cfg.tls.ServerName == "" && !cfg.tls.InsecureSkipVerify {
100+
host, _, err := net.SplitHostPort(cfg.Addr)
101+
if err == nil {
102+
cfg.tls.ServerName = host
103+
}
104+
}
105+
}
106+
98107
return nil
99108
}
100109

@@ -526,10 +535,6 @@ func parseDSNParams(cfg *Config, params string) (err error) {
526535
if boolValue {
527536
cfg.TLSConfig = "true"
528537
cfg.tls = &tls.Config{}
529-
host, _, err := net.SplitHostPort(cfg.Addr)
530-
if err == nil {
531-
cfg.tls.ServerName = host
532-
}
533538
} else {
534539
cfg.TLSConfig = "false"
535540
}
@@ -543,13 +548,6 @@ func parseDSNParams(cfg *Config, params string) (err error) {
543548
}
544549

545550
if tlsConfig := getTLSConfigClone(name); tlsConfig != nil {
546-
if len(tlsConfig.ServerName) == 0 && !tlsConfig.InsecureSkipVerify {
547-
host, _, err := net.SplitHostPort(cfg.Addr)
548-
if err == nil {
549-
tlsConfig.ServerName = host
550-
}
551-
}
552-
553551
cfg.TLSConfig = name
554552
cfg.tls = tlsConfig
555553
} else {

dsn_test.go

+28
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,34 @@ func TestDSNWithCustomTLS(t *testing.T) {
177177
DeregisterTLSConfig("utils_test")
178178
}
179179

180+
func TestDSNTLSConfig(t *testing.T) {
181+
expectedServerName := "example.com"
182+
dsn := "tcp(example.com:1234)/?tls=true"
183+
184+
cfg, err := ParseDSN(dsn)
185+
if err != nil {
186+
t.Error(err.Error())
187+
}
188+
if cfg.tls == nil {
189+
t.Error("cfg.tls should not be nil")
190+
}
191+
if cfg.tls.ServerName != expectedServerName {
192+
t.Errorf("cfg.tls.ServerName should be %q, got %q (host with port)", expectedServerName, cfg.tls.ServerName)
193+
}
194+
195+
dsn = "tcp(example.com)/?tls=true"
196+
cfg, err = ParseDSN(dsn)
197+
if err != nil {
198+
t.Error(err.Error())
199+
}
200+
if cfg.tls == nil {
201+
t.Error("cfg.tls should not be nil")
202+
}
203+
if cfg.tls.ServerName != expectedServerName {
204+
t.Errorf("cfg.tls.ServerName should be %q, got %q (host without port)", expectedServerName, cfg.tls.ServerName)
205+
}
206+
}
207+
180208
func TestDSNWithCustomTLSQueryEscape(t *testing.T) {
181209
const configKey = "&%!:"
182210
dsn := "User:password@tcp(localhost:5555)/dbname?tls=" + url.QueryEscape(configKey)

0 commit comments

Comments
 (0)