mirror of
https://github.com/MengMengCode/CLICD.git
synced 2026-08-07 22:24:42 +08:00
FIX #16
This commit is contained in:
@@ -582,9 +582,14 @@ func getRandomPort(w http.ResponseWriter, r *http.Request, id int) {
|
||||
return
|
||||
}
|
||||
hostIP := strings.TrimSpace(r.URL.Query().Get("host_ip"))
|
||||
// Try random ports
|
||||
for tries := 0; tries < 100; tries++ {
|
||||
port := 10000 + (int(time.Now().UnixNano()) % 55535)
|
||||
start, end := config.NATPortRange()
|
||||
capacity := end - start + 1
|
||||
offset := 0
|
||||
if capacity > 0 {
|
||||
offset = int(time.Now().UnixNano() % int64(capacity))
|
||||
}
|
||||
for tries := 0; tries < capacity; tries++ {
|
||||
port := start + ((offset + tries) % capacity)
|
||||
if lxc.HostPortAvailable(c, hostIP, port, "tcp") {
|
||||
jsonResponse(w, http.StatusOK, APIResponse{Success: true, Data: map[string]int{"port": port}})
|
||||
return
|
||||
|
||||
@@ -17,6 +17,11 @@ type routeCapacity struct {
|
||||
Total string `json:"total"`
|
||||
}
|
||||
|
||||
type nat4PortRange struct {
|
||||
Start int `json:"start"`
|
||||
End int `json:"end"`
|
||||
}
|
||||
|
||||
type nat4Route struct {
|
||||
ContainerID int `json:"container_id"`
|
||||
ContainerName string `json:"container_name"`
|
||||
@@ -53,6 +58,7 @@ type ipv6Route struct {
|
||||
|
||||
type routingResponse struct {
|
||||
NAT4 routeCapacity `json:"nat4"`
|
||||
NAT4PortRange nat4PortRange `json:"nat4_port_range"`
|
||||
IPv4 routeCapacity `json:"ipv4"`
|
||||
IPv6 routeCapacity `json:"ipv6"`
|
||||
HostPublicIPv4 lxc.PublicIPInfo `json:"host_public_ipv4"`
|
||||
@@ -64,9 +70,10 @@ type routingResponse struct {
|
||||
}
|
||||
|
||||
type routingPoolsRequest struct {
|
||||
Addresses *[]string `json:"addresses"`
|
||||
Items *[]config.PublicIPv4Assignment `json:"items"`
|
||||
IPv6Prefixes *[]config.PublicIPv6Prefix `json:"ipv6_prefixes"`
|
||||
Addresses *[]string `json:"addresses"`
|
||||
Items *[]config.PublicIPv4Assignment `json:"items"`
|
||||
IPv6Prefixes *[]config.PublicIPv6Prefix `json:"ipv6_prefixes"`
|
||||
NAT4PortRange *nat4PortRange `json:"nat4_port_range"`
|
||||
}
|
||||
|
||||
type publicIPv4ScanRequest struct {
|
||||
@@ -120,13 +127,12 @@ func handleRoutingGet(w http.ResponseWriter, r *http.Request) {
|
||||
ipv4Assignments := make([]ipv4Route, 0)
|
||||
ipv6Assignments := make([]ipv6Route, 0)
|
||||
|
||||
const nat4StartPort = 20000
|
||||
const nat4EndPort = 65535
|
||||
nat4StartPort, nat4EndPort := config.NATPortRange()
|
||||
|
||||
for i := range config.AppConfig.Containers {
|
||||
c := &config.AppConfig.Containers[i]
|
||||
for _, pm := range c.PortMappings {
|
||||
if pm.HostPort >= nat4StartPort && pm.HostPort <= nat4EndPort {
|
||||
if config.NATPortInRange(pm.HostPort) {
|
||||
usedPorts[pm.HostPort] = true
|
||||
}
|
||||
nat4Mappings = append(nat4Mappings, nat4Route{
|
||||
@@ -189,7 +195,7 @@ func handleRoutingGet(w http.ResponseWriter, r *http.Request) {
|
||||
return ipv6Assignments[i].Address < ipv6Assignments[j].Address
|
||||
})
|
||||
|
||||
const totalNAT4Ports = nat4EndPort - nat4StartPort + 1
|
||||
totalNAT4Ports := config.NATPortCapacity()
|
||||
nat4Used := len(usedPorts)
|
||||
nat4Remaining := totalNAT4Ports - nat4Used
|
||||
if nat4Remaining < 0 {
|
||||
@@ -216,6 +222,10 @@ func handleRoutingGet(w http.ResponseWriter, r *http.Request) {
|
||||
Remaining: strconv.Itoa(nat4Remaining),
|
||||
Total: strconv.Itoa(totalNAT4Ports),
|
||||
},
|
||||
NAT4PortRange: nat4PortRange{
|
||||
Start: nat4StartPort,
|
||||
End: nat4EndPort,
|
||||
},
|
||||
IPv4: routeCapacity{
|
||||
Used: ipv4Used,
|
||||
Remaining: strconv.Itoa(ipv4Remaining),
|
||||
@@ -246,6 +256,19 @@ func handleRoutingPoolsUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if req.NAT4PortRange != nil {
|
||||
start, end, err := config.NormalizeNATPortRange(req.NAT4PortRange.Start, req.NAT4PortRange.End)
|
||||
if err != nil {
|
||||
jsonResponse(w, http.StatusBadRequest, APIResponse{Success: false, Message: err.Error()})
|
||||
return
|
||||
}
|
||||
config.AppConfig.NATPortStart = start
|
||||
config.AppConfig.NATPortEnd = end
|
||||
if config.AppConfig.NextSSHPort < start || config.AppConfig.NextSSHPort > end {
|
||||
config.AppConfig.NextSSHPort = start
|
||||
}
|
||||
}
|
||||
|
||||
if req.Items != nil || req.Addresses != nil {
|
||||
items := []config.PublicIPv4Assignment{}
|
||||
if req.Items != nil {
|
||||
|
||||
@@ -372,6 +372,8 @@ type ClicdConfig struct {
|
||||
NextContainerID int `json:"next_container_id"`
|
||||
NextVNCPort int `json:"next_vnc_port"`
|
||||
NextSSHPort int `json:"next_ssh_port"`
|
||||
NATPortStart int `json:"nat_port_start"`
|
||||
NATPortEnd int `json:"nat_port_end"`
|
||||
SetupComplete bool `json:"setup_complete"`
|
||||
SubUsers []SubUser `json:"sub_users"`
|
||||
ApiKeys []ApiKeyConfig `json:"api_keys"`
|
||||
@@ -394,6 +396,11 @@ var AppConfig *ClicdConfig
|
||||
|
||||
const DefaultSnapshotLimit = 3
|
||||
|
||||
const (
|
||||
DefaultNATPortStart = 20000
|
||||
DefaultNATPortEnd = 65535
|
||||
)
|
||||
|
||||
func getConfigPath() string {
|
||||
if configPath != "" {
|
||||
return configPath
|
||||
@@ -509,6 +516,8 @@ func InitConfig() (*ClicdConfig, error) {
|
||||
NextContainerID: 1,
|
||||
NextVNCPort: 5900,
|
||||
NextSSHPort: 22000,
|
||||
NATPortStart: DefaultNATPortStart,
|
||||
NATPortEnd: DefaultNATPortEnd,
|
||||
SetupComplete: false,
|
||||
SubUsers: []SubUser{},
|
||||
AuditLogs: []AuditLog{},
|
||||
@@ -552,6 +561,9 @@ func normalizeConfigDefaults(dataDir string) bool {
|
||||
AppConfig.NextSSHPort = 22000
|
||||
changed = true
|
||||
}
|
||||
if normalizeNATPortRangeDefaults() {
|
||||
changed = true
|
||||
}
|
||||
if AppConfig.NextContainerID == 0 {
|
||||
AppConfig.NextContainerID = 1
|
||||
changed = true
|
||||
@@ -1168,16 +1180,102 @@ func UpdateVNC(containers []Container) {
|
||||
SaveConfig()
|
||||
}
|
||||
|
||||
// AllocateSSHPort allocates a new SSH port, skipping ports already used by any container
|
||||
func AllocateSSHPort() int {
|
||||
used := collectAllHostPorts()
|
||||
port := AppConfig.NextSSHPort
|
||||
for used[port] {
|
||||
port++
|
||||
func NormalizeNATPortRange(start, end int) (int, int, error) {
|
||||
if start == 0 && end == 0 {
|
||||
return DefaultNATPortStart, DefaultNATPortEnd, nil
|
||||
}
|
||||
AppConfig.NextSSHPort = port + 1
|
||||
SaveConfig()
|
||||
return port
|
||||
if start == 0 {
|
||||
start = DefaultNATPortStart
|
||||
}
|
||||
if end == 0 {
|
||||
end = DefaultNATPortEnd
|
||||
}
|
||||
if start < 1 || start > 65535 {
|
||||
return 0, 0, fmt.Errorf("NAT port start must be 1-65535")
|
||||
}
|
||||
if end < 1 || end > 65535 {
|
||||
return 0, 0, fmt.Errorf("NAT port end must be 1-65535")
|
||||
}
|
||||
if start > end {
|
||||
return 0, 0, fmt.Errorf("NAT port start cannot be greater than end")
|
||||
}
|
||||
return start, end, nil
|
||||
}
|
||||
|
||||
func NATPortRange() (int, int) {
|
||||
if AppConfig == nil {
|
||||
return DefaultNATPortStart, DefaultNATPortEnd
|
||||
}
|
||||
start, end, err := NormalizeNATPortRange(AppConfig.NATPortStart, AppConfig.NATPortEnd)
|
||||
if err != nil {
|
||||
return DefaultNATPortStart, DefaultNATPortEnd
|
||||
}
|
||||
return start, end
|
||||
}
|
||||
|
||||
func NATPortCapacity() int {
|
||||
start, end := NATPortRange()
|
||||
return end - start + 1
|
||||
}
|
||||
|
||||
func NATPortInRange(port int) bool {
|
||||
start, end := NATPortRange()
|
||||
return port >= start && port <= end
|
||||
}
|
||||
|
||||
func SetNATPortRange(start, end int) error {
|
||||
start, end, err := NormalizeNATPortRange(start, end)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
AppConfig.NATPortStart = start
|
||||
AppConfig.NATPortEnd = end
|
||||
if AppConfig.NextSSHPort < start || AppConfig.NextSSHPort > end {
|
||||
AppConfig.NextSSHPort = start
|
||||
}
|
||||
return SaveConfig()
|
||||
}
|
||||
|
||||
func normalizeNATPortRangeDefaults() bool {
|
||||
if AppConfig == nil {
|
||||
return false
|
||||
}
|
||||
start, end, err := NormalizeNATPortRange(AppConfig.NATPortStart, AppConfig.NATPortEnd)
|
||||
if err != nil {
|
||||
start, end = DefaultNATPortStart, DefaultNATPortEnd
|
||||
}
|
||||
changed := AppConfig.NATPortStart != start || AppConfig.NATPortEnd != end
|
||||
AppConfig.NATPortStart = start
|
||||
AppConfig.NATPortEnd = end
|
||||
if AppConfig.NextSSHPort < start || AppConfig.NextSSHPort > end {
|
||||
AppConfig.NextSSHPort = start
|
||||
changed = true
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// AllocateSSHPort allocates a new SSH port, skipping ports already used by any container
|
||||
func AllocateSSHPort() (int, error) {
|
||||
used := collectAllHostPorts()
|
||||
start, end := NATPortRange()
|
||||
port := AppConfig.NextSSHPort
|
||||
if port < start || port > end {
|
||||
port = start
|
||||
}
|
||||
capacity := end - start + 1
|
||||
for i := 0; i < capacity; i++ {
|
||||
candidate := start + ((port - start + i) % capacity)
|
||||
if used[candidate] {
|
||||
continue
|
||||
}
|
||||
AppConfig.NextSSHPort = candidate + 1
|
||||
if AppConfig.NextSSHPort > end {
|
||||
AppConfig.NextSSHPort = start
|
||||
}
|
||||
SaveConfig()
|
||||
return candidate, nil
|
||||
}
|
||||
return 0, fmt.Errorf("no free NAT4 host port in configured range %d-%d", start, end)
|
||||
}
|
||||
|
||||
// collectAllHostPorts collects all host ports used by any container (LXC + KVM)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAllocateSSHPortUsesConfiguredNATRange(t *testing.T) {
|
||||
AppConfig = &ClicdConfig{
|
||||
NATPortStart: 30000,
|
||||
NATPortEnd: 30002,
|
||||
NextSSHPort: 22000,
|
||||
Containers: []Container{{
|
||||
PortMappings: []PortMapping{
|
||||
{HostPort: 30000},
|
||||
{HostPort: 30001},
|
||||
},
|
||||
}},
|
||||
}
|
||||
|
||||
port, err := AllocateSSHPort()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if port != 30002 {
|
||||
t.Fatalf("expected port 30002, got %d", port)
|
||||
}
|
||||
if AppConfig.NextSSHPort != 30000 {
|
||||
t.Fatalf("expected next port to wrap to 30000, got %d", AppConfig.NextSSHPort)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllocateSSHPortErrorsWhenConfiguredRangeIsFull(t *testing.T) {
|
||||
AppConfig = &ClicdConfig{
|
||||
NATPortStart: 31000,
|
||||
NATPortEnd: 31001,
|
||||
NextSSHPort: 31000,
|
||||
Containers: []Container{{
|
||||
PortMappings: []PortMapping{
|
||||
{HostPort: 31000},
|
||||
{HostPort: 31001},
|
||||
},
|
||||
}},
|
||||
}
|
||||
|
||||
if port, err := AllocateSSHPort(); err == nil {
|
||||
t.Fatalf("expected exhausted NAT range error, got port %d", port)
|
||||
}
|
||||
}
|
||||
@@ -524,6 +524,8 @@ func loadConfigFromDB() (*ClicdConfig, bool, error) {
|
||||
NextContainerID: atoi(meta["next_container_id"]),
|
||||
NextVNCPort: atoi(meta["next_vnc_port"]),
|
||||
NextSSHPort: atoi(meta["next_ssh_port"]),
|
||||
NATPortStart: atoi(meta["nat_port_start"]),
|
||||
NATPortEnd: atoi(meta["nat_port_end"]),
|
||||
SetupComplete: atob(meta["setup_complete"]),
|
||||
SecurityAutoShutdown: atob(meta["security_auto_shutdown"]),
|
||||
Language: meta["language"],
|
||||
@@ -651,6 +653,8 @@ func saveMeta(tx *sql.Tx) error {
|
||||
"next_container_id": strconv.Itoa(AppConfig.NextContainerID),
|
||||
"next_vnc_port": strconv.Itoa(AppConfig.NextVNCPort),
|
||||
"next_ssh_port": strconv.Itoa(AppConfig.NextSSHPort),
|
||||
"nat_port_start": strconv.Itoa(AppConfig.NATPortStart),
|
||||
"nat_port_end": strconv.Itoa(AppConfig.NATPortEnd),
|
||||
"setup_complete": btoa(AppConfig.SetupComplete),
|
||||
"security_auto_shutdown": btoa(AppConfig.SecurityAutoShutdown),
|
||||
"language": NormalizeLanguage(AppConfig.Language),
|
||||
|
||||
@@ -487,7 +487,10 @@ func (m *Manager) defineContainer(id int, vmName string, cfg lxc.ContainerConfig
|
||||
sshPort := 0
|
||||
portMappings := []config.PortMapping{}
|
||||
if allocatePorts && cfg.WantsNAT() {
|
||||
sshPort = config.AllocateSSHPort()
|
||||
sshPort, err = config.AllocateSSHPort()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if IsWindowsImage(image.ID) {
|
||||
// Windows: RDP (3389) instead of SSH (22)
|
||||
portMappings = []config.PortMapping{{
|
||||
@@ -2406,7 +2409,11 @@ func normalizeKVMManagementPortMapping(c *config.Container) {
|
||||
}
|
||||
hostPort := c.SSHPort
|
||||
if hostPort <= 0 {
|
||||
hostPort = config.AllocateSSHPort()
|
||||
allocated, err := config.AllocateSSHPort()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
hostPort = allocated
|
||||
c.SSHPort = hostPort
|
||||
}
|
||||
desiredPort := 22
|
||||
@@ -3908,7 +3915,8 @@ func allocateDefaultEqualPorts(c *config.Container, count int) []int {
|
||||
}
|
||||
}
|
||||
ports := make([]int, 0, count)
|
||||
for next := 20000; next <= 65535 && len(ports) < count; next++ {
|
||||
start, end := config.NATPortRange()
|
||||
for next := start; next <= end && len(ports) < count; next++ {
|
||||
if !used[next] {
|
||||
ports = append(ports, next)
|
||||
}
|
||||
|
||||
@@ -74,6 +74,9 @@ func (m *Manager) DetectIPv6Status() IPv6Status {
|
||||
}
|
||||
|
||||
func DetectPublicIPv6Prefixes() []IPv6PrefixInfo {
|
||||
if configured := ConfiguredPublicIPv6Prefixes(); len(configured) > 0 {
|
||||
return configured
|
||||
}
|
||||
return detectPublicIPv6Prefixes(detectIPv6DefaultRoutes())
|
||||
}
|
||||
|
||||
|
||||
@@ -381,7 +381,11 @@ func (m *Manager) CreateContainer(cfg ContainerConfig) error {
|
||||
sshPort := 0
|
||||
portMappings := []config.PortMapping{}
|
||||
if cfg.WantsNAT() {
|
||||
sshPort = config.AllocateSSHPort()
|
||||
sshPort, err = config.AllocateSSHPort()
|
||||
if err != nil {
|
||||
_ = m.cleanupContainerStorage(lxcName)
|
||||
return err
|
||||
}
|
||||
|
||||
// Setup default port mappings (SSH only)
|
||||
portMappings = SetupDefaultPortMappings(sshPort)
|
||||
|
||||
@@ -395,6 +395,10 @@ func normalizePortMapping(c *config.Container, skipIndex int, pm config.PortMapp
|
||||
if pm.HostPort <= 0 {
|
||||
pm.HostPort = pm.ContainerPort
|
||||
}
|
||||
if pm.HostIP == "" && !config.NATPortInRange(pm.HostPort) {
|
||||
start, end := config.NATPortRange()
|
||||
return pm, fmt.Errorf("host port must be within configured NAT4 range %d-%d", start, end)
|
||||
}
|
||||
// Check current container's own mappings
|
||||
for i, existing := range c.PortMappings {
|
||||
if i == skipIndex {
|
||||
@@ -444,16 +448,12 @@ func allocateDefaultEqualPorts(c *config.Container, count int) []int {
|
||||
}
|
||||
}
|
||||
ports := make([]int, 0, count)
|
||||
next := 20000
|
||||
for len(ports) < count {
|
||||
start, end := config.NATPortRange()
|
||||
for next := start; next <= end && len(ports) < count; next++ {
|
||||
hostIP := c.PrimaryPublicIPv4()
|
||||
if !used[hostPortKey(hostIP, next)] && !used[next] {
|
||||
ports = append(ports, next)
|
||||
}
|
||||
next++
|
||||
if next > 65535 || len(ports) >= count {
|
||||
break
|
||||
}
|
||||
}
|
||||
return ports
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user