package proxy import ( "context" "crypto/sha256" "encoding/hex" "errors" "fmt" "os" "path/filepath" "time" ) const whitelistLockStaleAfter = 2 * time.Minute const whitelistMarkerTTL = 10 * time.Minute type whitelistGuard struct { path string markerPath string } func acquireWhitelistLock(ctx context.Context, baseURL, no, ip string) (*whitelistGuard, error) { sum := sha256.Sum256([]byte(baseURL + "\x00" + no + "\x00" + ip)) dir := filepath.Join(os.TempDir(), "douyu-go-whitelist") if err := os.MkdirAll(dir, 0o700); err != nil { return nil, err } key := hex.EncodeToString(sum[:16]) path := filepath.Join(dir, key+".lock") guard := &whitelistGuard{ path: path, markerPath: filepath.Join(dir, key+".ok"), } for { file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) if err == nil { _, _ = fmt.Fprintf(file, "%d\n%s\n", os.Getpid(), time.Now().Format(time.RFC3339Nano)) _ = file.Close() return guard, nil } if !errors.Is(err, os.ErrExist) { return nil, err } if info, statErr := os.Stat(path); statErr == nil && time.Since(info.ModTime()) > whitelistLockStaleAfter { _ = os.Remove(path) continue } timer := time.NewTimer(200 * time.Millisecond) select { case <-ctx.Done(): timer.Stop() return nil, ctx.Err() case <-timer.C: } } } func (g *whitelistGuard) recentlyAdded() bool { if g == nil { return false } info, err := os.Stat(g.markerPath) if err != nil { return false } age := time.Since(info.ModTime()) return age >= 0 && age < whitelistMarkerTTL } func (g *whitelistGuard) markAdded() { if g == nil { return } _ = os.WriteFile(g.markerPath, []byte(time.Now().Format(time.RFC3339Nano)), 0o600) } func (g *whitelistGuard) release() { if g != nil { _ = os.Remove(g.path) } }