syncthing/lib/connections/util.go
Jakob Borg b62b7d269e
lib/connections: Correctly fixup port in IPv6 listen URLs (#6786)
Previously tcp://[fe80::1] would get "fixed" to tcp://[[fe80::1]]:22000
which is not great.
2020-06-22 16:47:15 +01:00

35 lines
983 B
Go

// Copyright (C) 2016 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
package connections
import (
"net"
"net/url"
"strconv"
"strings"
)
func fixupPort(uri *url.URL, defaultPort int) *url.URL {
copyURI := *uri
host, port, err := net.SplitHostPort(uri.Host)
if err != nil && strings.Contains(err.Error(), "missing port") {
// addr is on the form "1.2.3.4" or "[fe80::1]"
host = uri.Host
if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
// net.JoinHostPort will add the brackets again
host = host[1 : len(host)-1]
}
copyURI.Host = net.JoinHostPort(host, strconv.Itoa(defaultPort))
} else if err == nil && port == "" {
// addr is on the form "1.2.3.4:" or "[fe80::1]:"
copyURI.Host = net.JoinHostPort(host, strconv.Itoa(defaultPort))
}
return &copyURI
}