| 9 |
| 10 | "k8s.io/utils/clock" |
| 11 |
| 12 | "github.com/fatedier/frp/pkg/config/types" |
| 13 | ) |
| 14 |
| 15 | const ( |
| 16 | MinPort = 1 |
| 17 | MaxPort = 65535 |
| 18 | MaxPortReservedDuration = time.Duration(24) * time.Hour |
| 19 | CleanReservedPortsInterval = time.Hour |
| 20 | ) |
| 21 |
| 22 | var ( |
| 23 | ErrPortAlreadyUsed = errors.New("port already used") |
| 24 | ErrPortNotAllowed = errors.New("port not allowed") |
| 25 | ErrPortUnAvailable = errors.New("port unavailable") |
| 26 | ErrNoAvailablePort = errors.New("no available port") |
| 27 | ) |
| 28 |
| 29 | type PortCtx struct { |
| 30 | ProxyName string |
| 31 | Port int |
| 32 | Closed bool |
| 33 | UpdateTime time.Time |
| 34 | } |
| 35 |
| 36 | type Manager struct { |
| 37 | reservedPorts map[string]*PortCtx |
| 38 | usedPorts map[int]*PortCtx |
| 39 | freePorts map[int]struct{} |
| 40 |
| 41 | bindAddr string |
| 42 | netType string |
| 43 | clock clock.WithTicker |
| 44 | mu sync.Mutex |
| 45 | } |
| 46 |
| 47 | func NewManager(netType string, bindAddr string, allowPorts []types.PortsRange) *Manager { |
| 48 | return newManagerWithClock(netType, bindAddr, allowPorts, clock.RealClock{}) |
| 49 | } |
| 50 |
| 51 | func newManagerWithClock(netType string, bindAddr string, allowPorts []types.PortsRange, clk clock.WithTicker) *Manager { |
| 52 | if clk == nil { |
| 53 | clk = clock.RealClock{} |
| 54 | } |
| 55 | pm := &Manager{ |
| 56 | reservedPorts: make(map[string]*PortCtx), |
| 57 | usedPorts: make(map[int]*PortCtx), |
| 58 | freePorts: make(map[int]struct{}), |
| 59 | bindAddr: bindAddr, |
| 60 | netType: netType, |
| 61 | clock: clk, |
| 62 | } |
| 63 | if len(allowPorts) > 0 { |
| 64 | for _, pair := range allowPorts { |
| 65 | if pair.Single > 0 { |
| 66 | pm.freePorts[pair.Single] = struct{}{} |
| 67 | } else { |
| 68 | for i := pair.Start; i <= pair.End; i++ { |
| 69 | pm.freePorts[i] = struct{}{} |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | } else { |
| 74 | for i := MinPort; i <= MaxPort; i++ { |
| 75 | pm.freePorts[i] = struct{}{} |
| 76 | } |
| 77 | } |
| 78 | go pm.cleanReservedPortsWorker() |
| 79 | return pm |
| 80 | } |
| 81 |
| 82 | func (pm *Manager) Acquire(name string, port int) (realPort int, err error) { |
| 83 | portCtx := &PortCtx{ |
| 84 | ProxyName: name, |
| 85 | Closed: false, |
| 86 | UpdateTime: pm.clock.Now(), |
| 87 | } |
| 88 |
| 89 | var ok bool |
| 90 |
| 91 | pm.mu.Lock() |
| 92 | defer func() { |
| 93 | if err == nil { |
| 94 | portCtx.Port = realPort |
| 95 | } |
| 96 | pm.mu.Unlock() |
| 97 | }() |
| 98 |
| 99 | // check reserved ports first |
| 100 | if port == 0 { |
| 101 | if ctx, ok := pm.reservedPorts[name]; ok { |
| 102 | if pm.isPortAvailable(ctx.Port) { |
| 103 | realPort = ctx.Port |
| 104 | pm.markPortAcquiredLocked(name, realPort, portCtx) |
| 105 | return |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 |
| 110 | if port == 0 { |
| 111 | // get random port |
| 112 | count := 0 |
| 113 | maxTryTimes := 5 |
| 114 | for k := range pm.freePorts { |
| 115 | count++ |
| 116 | if count > maxTryTimes { |
| 117 | break |
| 118 | } |
| 119 | if pm.isPortAvailable(k) { |
| 120 | realPort = k |
| 121 | pm.markPortAcquiredLocked(name, realPort, portCtx) |
| 122 | break |
| 123 | } |
| 124 | } |
| 125 | if realPort == 0 { |
| 126 | err = ErrNoAvailablePort |
| 127 | } |
| 128 | } else { |
| 129 | // specified port |
| 130 | if _, ok = pm.freePorts[port]; ok { |
| 131 | if pm.isPortAvailable(port) { |
| 132 | realPort = port |
| 133 | pm.markPortAcquiredLocked(name, realPort, portCtx) |
| 134 | } else { |
| 135 | err = ErrPortUnAvailable |
| 136 | } |
| 137 | } else { |
| 138 | if _, ok = pm.usedPorts[port]; ok { |
| 139 | err = ErrPortAlreadyUsed |
| 140 | } else { |
| 141 | err = ErrPortNotAllowed |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | return |
| 146 | } |
| 147 |
| 148 | // markPortAcquiredLocked records a successful acquisition. pm.mu must be held. |
| 149 | func (pm *Manager) markPortAcquiredLocked(name string, port int, portCtx *PortCtx) { |
| 150 | pm.usedPorts[port] = portCtx |
| 151 | pm.reservedPorts[name] = portCtx |
| 152 | delete(pm.freePorts, port) |
| 153 | } |
| 154 |
| 155 | func (pm *Manager) isPortAvailable(port int) bool { |
| 156 | if pm.netType == "udp" { |
| 157 | addr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(pm.bindAddr, strconv.Itoa(port))) |
| 158 | if err != nil { |
| 159 | return false |
| 160 | } |
| 161 | l, err := net.ListenUDP("udp", addr) |
| 162 | if err != nil { |
| 163 | return false |
| 164 | } |
| 165 | l.Close() |
| 166 | return true |
| 167 | } |
| 168 |
| 169 | l, err := net.Listen(pm.netType, net.JoinHostPort(pm.bindAddr, strconv.Itoa(port))) |
| 170 | if err != nil { |
| 171 | return false |
| 172 | } |
| 173 | l.Close() |
| 174 | return true |
| 175 | } |
| 176 |
| 177 | func (pm *Manager) Release(port int) { |
| 178 | pm.mu.Lock() |
| 179 | defer pm.mu.Unlock() |
| 180 | if ctx, ok := pm.usedPorts[port]; ok { |
| 181 | pm.freePorts[port] = struct{}{} |
| 182 | delete(pm.usedPorts, port) |
| 183 | ctx.Closed = true |
| 184 | ctx.UpdateTime = pm.clock.Now() |
| 185 | } |
| 186 | } |
| 187 |
| 188 | // Release reserved port if it isn't used in last 24 hours. |
| 189 | func (pm *Manager) cleanReservedPortsWorker() { |
| 190 | pm.cleanReservedPortsWorkerUntil(nil) |
| 191 | } |
| 192 |
| 193 | func (pm *Manager) cleanReservedPortsWorkerUntil(stopCh <-chan struct{}) { |
| 194 | ticker := pm.clock.NewTicker(CleanReservedPortsInterval) |
| 195 | defer ticker.Stop() |
| 196 |
| 197 | for { |
| 198 | select { |
| 199 | case <-ticker.C(): |
| 200 | pm.cleanReservedPortsOnce() |
| 201 | case <-stopCh: |
| 202 | return |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 |
| 207 | func (pm *Manager) cleanReservedPortsOnce() { |
| 208 | pm.mu.Lock() |
| 209 | defer pm.mu.Unlock() |
| 210 |
| 211 | for name, ctx := range pm.reservedPorts { |
| 212 | if ctx.Closed && pm.clock.Since(ctx.UpdateTime) > MaxPortReservedDuration { |
| 213 | delete(pm.reservedPorts, name) |
| 214 | } |
| 215 | } |
| 216 | } |