feat(GODT-2538): implement smart picking of default IMAP/SMTP ports

This commit is contained in:
Xavier Michelon
2023-04-06 15:08:41 +02:00
parent 54b209f9e1
commit 3ddd88e127
9 changed files with 182 additions and 12 deletions

View File

@ -22,6 +22,7 @@ import (
"net"
"github.com/ProtonMail/proton-bridge/v3/internal/constants"
"golang.org/x/exp/slices"
)
const (
@ -43,19 +44,19 @@ func IsPortFree(port int) bool {
func isOccupied(port string) bool {
// Try to create server at port.
dummyserver, err := net.Listen("tcp", port)
dummyServer, err := net.Listen("tcp", port)
if err != nil {
return true
}
_ = dummyserver.Close()
_ = dummyServer.Close()
return false
}
// FindFreePortFrom finds first empty port, starting with `startPort`.
func FindFreePortFrom(startPort int) int {
// FindFreePortFrom finds first empty port, starting with `startPort`, and excluding ports listed in exclude.
func FindFreePortFrom(startPort int, exclude ...int) int {
loopedOnce := false
freePort := startPort
for !IsPortFree(freePort) {
for slices.Contains(exclude, freePort) || !IsPortFree(freePort) {
freePort++
if freePort >= maxPortNumber {
freePort = 1

View File

@ -32,12 +32,12 @@ func TestFreePort(t *testing.T) {
}
func TestOccupiedPort(t *testing.T) {
dummyserver, err := net.Listen("tcp", ":"+strconv.Itoa(testPort))
dummyServer, err := net.Listen("tcp", ":"+strconv.Itoa(testPort))
require.NoError(t, err)
require.True(t, !IsPortFree(testPort), "port should be occupied")
_ = dummyserver.Close()
_ = dummyServer.Close()
}
func TestFindFreePortFromDirectly(t *testing.T) {
@ -46,11 +46,21 @@ func TestFindFreePortFromDirectly(t *testing.T) {
}
func TestFindFreePortFromNextOne(t *testing.T) {
dummyserver, err := net.Listen("tcp", ":"+strconv.Itoa(testPort))
dummyServer, err := net.Listen("tcp", ":"+strconv.Itoa(testPort))
require.NoError(t, err)
foundPort := FindFreePortFrom(testPort)
require.Equal(t, testPort+1, foundPort)
_ = dummyserver.Close()
_ = dummyServer.Close()
}
func TestFindFreePortExcluding(t *testing.T) {
dummyServer, err := net.Listen("tcp", ":"+strconv.Itoa(testPort))
require.NoError(t, err)
foundPort := FindFreePortFrom(testPort, testPort+1, testPort+2)
require.Equal(t, testPort+3, foundPort)
_ = dummyServer.Close()
}