mirror of
https://github.com/ProtonMail/proton-bridge.git
synced 2025-12-10 04:36:43 +00:00
feat(GODT-2538): implement smart picking of default IMAP/SMTP ports
This commit is contained in:
@ -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
|
||||
|
||||
@ -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()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user