| // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | package source |
| 16 |
| 17 | import ( |
| 18 | "errors" |
| 19 | "fmt" |
| 20 | "os" |
| 21 | "path/filepath" |
| 22 |
| 23 | v1 "github.com/fatedier/frp/pkg/config/v1" |
| 24 | "github.com/fatedier/frp/pkg/util/jsonx" |
| 25 | ) |
| 26 |
| 27 | type StoreSourceConfig struct { |
| 28 | Path string `json:"path"` |
| 29 | } |
| 30 |
| 31 | type storeData struct { |
| 32 | Proxies []v1.TypedProxyConfig `json:"proxies,omitempty"` |
| 33 | Visitors []v1.TypedVisitorConfig `json:"visitors,omitempty"` |
| 34 | } |
| 35 |
| 36 | type StoreSource struct { |
| 37 | baseSource |
| 38 | config StoreSourceConfig |
| 39 | } |
| 40 |
| 41 | var ( |
| 42 | ErrAlreadyExists = errors.New("already exists") |
| 43 | ErrNotFound = errors.New("not found") |
| 44 | ) |
| 45 |
| 46 | const ( |
| 47 | storeKindProxy = "proxy" |
| 48 | storeKindVisitor = "visitor" |
| 49 | ) |
| 50 |
| 51 | func NewStoreSource(cfg StoreSourceConfig) (*StoreSource, error) { |
| 52 | if cfg.Path == "" { |
| 53 | return nil, fmt.Errorf("path is required") |
| 54 | } |
| 55 |
| 56 | s := &StoreSource{ |
| 57 | baseSource: newBaseSource(), |
| 58 | config: cfg, |
| 59 | } |
| 60 |
| 61 | if err := s.loadFromFile(); err != nil { |
| 62 | if !os.IsNotExist(err) { |
| 63 | return nil, fmt.Errorf("failed to load existing data: %w", err) |
| 64 | } |
| 65 | } |
| 66 |
| 67 | return s, nil |
| 68 | } |
| 69 |
| 70 | func (s *StoreSource) loadFromFile() error { |
| 71 | s.mu.Lock() |
| 72 | defer s.mu.Unlock() |
| 73 | return s.loadFromFileUnlocked() |
| 74 | } |
| 75 |
| 76 | func (s *StoreSource) loadFromFileUnlocked() error { |
| 77 | data, err := os.ReadFile(s.config.Path) |
| 78 | if err != nil { |
| 79 | return err |
| 80 | } |
| 81 |
| 82 | type rawStoreData struct { |
| 83 | Proxies []jsonx.RawMessage `json:"proxies,omitempty"` |
| 84 | Visitors []jsonx.RawMessage `json:"visitors,omitempty"` |
| 85 | } |
| 86 | stored := rawStoreData{} |
| 87 | if err := jsonx.Unmarshal(data, &stored); err != nil { |
| 88 | return fmt.Errorf("failed to parse JSON: %w", err) |
| 89 | } |
| 90 |
| 91 | s.proxies = make(map[string]v1.ProxyConfigurer) |
| 92 | s.visitors = make(map[string]v1.VisitorConfigurer) |
| 93 |
| 94 | for i, proxyData := range stored.Proxies { |
| 95 | proxyCfg, err := v1.DecodeProxyConfigurerJSON(proxyData, v1.DecodeOptions{ |
| 96 | DisallowUnknownFields: false, |
| 97 | }) |
| 98 | if err != nil { |
| 99 | return fmt.Errorf("failed to decode proxy at index %d: %w", i, err) |
| 100 | } |
| 101 | name := proxyCfg.GetBaseConfig().Name |
| 102 | if name == "" { |
| 103 | return fmt.Errorf("proxy name cannot be empty") |
| 104 | } |
| 105 | s.proxies[name] = proxyCfg |
| 106 | } |
| 107 |
| 108 | for i, visitorData := range stored.Visitors { |
| 109 | visitorCfg, err := v1.DecodeVisitorConfigurerJSON(visitorData, v1.DecodeOptions{ |
| 110 | DisallowUnknownFields: false, |
| 111 | }) |
| 112 | if err != nil { |
| 113 | return fmt.Errorf("failed to decode visitor at index %d: %w", i, err) |
| 114 | } |
| 115 | name := visitorCfg.GetBaseConfig().Name |
| 116 | if name == "" { |
| 117 | return fmt.Errorf("visitor name cannot be empty") |
| 118 | } |
| 119 | s.visitors[name] = visitorCfg |
| 120 | } |
| 121 |
| 122 | return nil |
| 123 | } |
| 124 |
| 125 | func (s *StoreSource) saveToFileUnlocked() error { |
| 126 | stored := storeData{ |
| 127 | Proxies: make([]v1.TypedProxyConfig, 0, len(s.proxies)), |
| 128 | Visitors: make([]v1.TypedVisitorConfig, 0, len(s.visitors)), |
| 129 | } |
| 130 |
| 131 | for _, p := range s.proxies { |
| 132 | stored.Proxies = append(stored.Proxies, v1.TypedProxyConfig{ProxyConfigurer: p}) |
| 133 | } |
| 134 | for _, v := range s.visitors { |
| 135 | stored.Visitors = append(stored.Visitors, v1.TypedVisitorConfig{VisitorConfigurer: v}) |
| 136 | } |
| 137 |
| 138 | data, err := jsonx.MarshalIndent(stored, "", " ") |
| 139 | if err != nil { |
| 140 | return fmt.Errorf("failed to marshal JSON: %w", err) |
| 141 | } |
| 142 |
| 143 | dir := filepath.Dir(s.config.Path) |
| 144 | if err := os.MkdirAll(dir, 0o755); err != nil { |
| 145 | return fmt.Errorf("failed to create directory: %w", err) |
| 146 | } |
| 147 |
| 148 | tmpPath := s.config.Path + ".tmp" |
| 149 |
| 150 | f, err := os.OpenFile(tmpPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) |
| 151 | if err != nil { |
| 152 | return fmt.Errorf("failed to create temp file: %w", err) |
| 153 | } |
| 154 |
| 155 | if _, err := f.Write(data); err != nil { |
| 156 | f.Close() |
| 157 | os.Remove(tmpPath) |
| 158 | return fmt.Errorf("failed to write temp file: %w", err) |
| 159 | } |
| 160 |
| 161 | if err := f.Sync(); err != nil { |
| 162 | f.Close() |
| 163 | os.Remove(tmpPath) |
| 164 | return fmt.Errorf("failed to sync temp file: %w", err) |
| 165 | } |
| 166 |
| 167 | if err := f.Close(); err != nil { |
| 168 | os.Remove(tmpPath) |
| 169 | return fmt.Errorf("failed to close temp file: %w", err) |
| 170 | } |
| 171 |
| 172 | if err := os.Rename(tmpPath, s.config.Path); err != nil { |
| 173 | os.Remove(tmpPath) |
| 174 | return fmt.Errorf("failed to rename temp file: %w", err) |
| 175 | } |
| 176 |
| 177 | return nil |
| 178 | } |
| 179 |
| 180 | func (s *StoreSource) persistOrRollbackUnlocked(rollback func()) error { |
| 181 | if err := s.saveToFileUnlocked(); err != nil { |
| 182 | rollback() |
| 183 | return fmt.Errorf("failed to persist: %w", err) |
| 184 | } |
| 185 | return nil |
| 186 | } |
| 187 |
| 188 | // Store map selectors return the target map for generic helpers. |
| 189 | func proxyStoreEntries(s *StoreSource) map[string]v1.ProxyConfigurer { |
| 190 | return s.proxies |
| 191 | } |
| 192 |
| 193 | func visitorStoreEntries(s *StoreSource) map[string]v1.VisitorConfigurer { |
| 194 | return s.visitors |
| 195 | } |
| 196 |
| 197 | // Store entry helpers share mutation, persistence, and rollback for proxy and visitor maps. |
| 198 | // T is intentionally limited by callers to v1.ProxyConfigurer or v1.VisitorConfigurer. |
| 199 | func addStoreEntry[T any]( |
| 200 | s *StoreSource, |
| 201 | entriesFn func(*StoreSource) map[string]T, |
| 202 | kind string, |
| 203 | name string, |
| 204 | value T, |
| 205 | ) error { |
| 206 | s.mu.Lock() |
| 207 | defer s.mu.Unlock() |
| 208 |
| 209 | entries := entriesFn(s) |
| 210 | if _, exists := entries[name]; exists { |
| 211 | return fmt.Errorf("%w: %s %q", ErrAlreadyExists, kind, name) |
| 212 | } |
| 213 |
| 214 | entries[name] = value |
| 215 | return s.persistOrRollbackUnlocked(func() { |
| 216 | delete(entries, name) |
| 217 | }) |
| 218 | } |
| 219 |
| 220 | func updateStoreEntry[T any]( |
| 221 | s *StoreSource, |
| 222 | entriesFn func(*StoreSource) map[string]T, |
| 223 | kind string, |
| 224 | name string, |
| 225 | value T, |
| 226 | ) error { |
| 227 | s.mu.Lock() |
| 228 | defer s.mu.Unlock() |
| 229 |
| 230 | entries := entriesFn(s) |
| 231 | old, exists := entries[name] |
| 232 | if !exists { |
| 233 | return fmt.Errorf("%w: %s %q", ErrNotFound, kind, name) |
| 234 | } |
| 235 |
| 236 | entries[name] = value |
| 237 | return s.persistOrRollbackUnlocked(func() { |
| 238 | entries[name] = old |
| 239 | }) |
| 240 | } |
| 241 |
| 242 | func removeStoreEntry[T any]( |
| 243 | s *StoreSource, |
| 244 | entriesFn func(*StoreSource) map[string]T, |
| 245 | kind string, |
| 246 | name string, |
| 247 | ) error { |
| 248 | if name == "" { |
| 249 | return fmt.Errorf("%s name cannot be empty", kind) |
| 250 | } |
| 251 |
| 252 | s.mu.Lock() |
| 253 | defer s.mu.Unlock() |
| 254 |
| 255 | entries := entriesFn(s) |
| 256 | old, exists := entries[name] |
| 257 | if !exists { |
| 258 | return fmt.Errorf("%w: %s %q", ErrNotFound, kind, name) |
| 259 | } |
| 260 |
| 261 | delete(entries, name) |
| 262 | return s.persistOrRollbackUnlocked(func() { |
| 263 | entries[name] = old |
| 264 | }) |
| 265 | } |
| 266 |
| 267 | func (s *StoreSource) AddProxy(proxy v1.ProxyConfigurer) error { |
| 268 | name, err := validateProxyName(proxy) |
| 269 | if err != nil { |
| 270 | return err |
| 271 | } |
| 272 | return addStoreEntry(s, proxyStoreEntries, storeKindProxy, name, proxy) |
| 273 | } |
| 274 |
| 275 | func (s *StoreSource) UpdateProxy(proxy v1.ProxyConfigurer) error { |
| 276 | name, err := validateProxyName(proxy) |
| 277 | if err != nil { |
| 278 | return err |
| 279 | } |
| 280 | return updateStoreEntry(s, proxyStoreEntries, storeKindProxy, name, proxy) |
| 281 | } |
| 282 |
| 283 | func (s *StoreSource) RemoveProxy(name string) error { |
| 284 | return removeStoreEntry(s, proxyStoreEntries, storeKindProxy, name) |
| 285 | } |
| 286 |
| 287 | func (s *StoreSource) GetProxy(name string) v1.ProxyConfigurer { |
| 288 | s.mu.RLock() |
| 289 | defer s.mu.RUnlock() |
| 290 |
| 291 | p, exists := s.proxies[name] |
| 292 | if !exists { |
| 293 | return nil |
| 294 | } |
| 295 | return p |
| 296 | } |
| 297 |
| 298 | func (s *StoreSource) AddVisitor(visitor v1.VisitorConfigurer) error { |
| 299 | name, err := validateVisitorName(visitor) |
| 300 | if err != nil { |
| 301 | return err |
| 302 | } |
| 303 | return addStoreEntry(s, visitorStoreEntries, storeKindVisitor, name, visitor) |
| 304 | } |
| 305 |
| 306 | func (s *StoreSource) UpdateVisitor(visitor v1.VisitorConfigurer) error { |
| 307 | name, err := validateVisitorName(visitor) |
| 308 | if err != nil { |
| 309 | return err |
| 310 | } |
| 311 | return updateStoreEntry(s, visitorStoreEntries, storeKindVisitor, name, visitor) |
| 312 | } |
| 313 |
| 314 | func (s *StoreSource) RemoveVisitor(name string) error { |
| 315 | return removeStoreEntry(s, visitorStoreEntries, storeKindVisitor, name) |
| 316 | } |
| 317 |
| 318 | func (s *StoreSource) GetVisitor(name string) v1.VisitorConfigurer { |
| 319 | s.mu.RLock() |
| 320 | defer s.mu.RUnlock() |
| 321 |
| 322 | v, exists := s.visitors[name] |
| 323 | if !exists { |
| 324 | return nil |
| 325 | } |
| 326 | return v |
| 327 | } |
| 328 |
| 329 | func (s *StoreSource) GetAllProxies() ([]v1.ProxyConfigurer, error) { |
| 330 | s.mu.RLock() |
| 331 | defer s.mu.RUnlock() |
| 332 |
| 333 | result := make([]v1.ProxyConfigurer, 0, len(s.proxies)) |
| 334 | for _, p := range s.proxies { |
| 335 | result = append(result, p) |
| 336 | } |
| 337 | return result, nil |
| 338 | } |
| 339 |
| 340 | func (s *StoreSource) GetAllVisitors() ([]v1.VisitorConfigurer, error) { |
| 341 | s.mu.RLock() |
| 342 | defer s.mu.RUnlock() |
| 343 |
| 344 | result := make([]v1.VisitorConfigurer, 0, len(s.visitors)) |
| 345 | for _, v := range s.visitors { |
| 346 | result = append(result, v) |
| 347 | } |
| 348 | return result, nil |
| 349 | } |