package isolation import ( "bytes" "context" "encoding/json" "errors" "io" "net/http" "os" "path/filepath" "regexp" "strconv" "strings" "sync" "time" ) var trafficPolicyMu sync.Mutex var ftpAltLogLine = regexp.MustCompile(`(?mi)^\s*AltLog\s+[^\r\n]*`) func (a Agent) configureTrafficLimits(w http.ResponseWriter, r *http.Request) { var spec TrafficLimitSpec decoder := json.NewDecoder(r.Body) decoder.DisallowUnknownFields() if decoder.Decode(&spec) != nil || decoder.Decode(&struct{}{}) != io.EOF || !managedWebHostPattern.MatchString(spec.Project.HostName) || spec.Mbps > 10000 || !validUsageSpec(ResourceUsageSpec{Project: spec.Project, Domains: spec.Domains}) || len(spec.Domains) > 100 { http.Error(w, "invalid traffic policy", 400) return } root, err := a.projectPath(spec.Project) if err != nil || requirePhysicalDirectory(root) != nil { http.Error(w, "managed project root unavailable", 412) return } trafficPolicyMu.Lock() defer trafficPolicyMu.Unlock() ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second) defer cancel() if err = a.applyTrafficLimits(ctx, spec); err != nil { http.Error(w, "cannot enforce traffic policy: "+err.Error(), 412) return } w.WriteHeader(200) } func (a Agent) trafficLimitStatePath(host string) (string, error) { path := a.UsageStatePath if path == "" { path = "/var/lib/sea-vhost-agent/traffic.json" } dir := filepath.Join(filepath.Dir(path), "limits") if err := os.MkdirAll(dir, 0700); err != nil { return "", err } if err := requirePhysicalDirectory(dir); err != nil { return "", err } return filepath.Join(dir, host+".json"), nil } func (a Agent) applyTrafficLimits(ctx context.Context, spec TrafficLimitSpec) error { var restore []func() error changed := false rollback := func() { for _, f := range restore { _ = f() } _ = a.runNginx(ctx, "-t") _ = a.runNginx(ctx, "-s", "reload") } for _, domain := range spec.Domains { paths, err := a.webProtectionPaths(WebProtectionSpec{Project: spec.Project, Domain: domain}) if err != nil { rollback() return err } if err = verifySiteExtensionInclude(paths.siteConfig, paths.siteExtension); err != nil { rollback() return err } target := filepath.Join(filepath.Dir(paths.siteExtension), "sea-vhost-rate.conf") content := []byte("# Managed Sea vHost HTTP rate: per request, not aggregate host speed.\nlimit_rate " + strconv.FormatUint(uint64(spec.Mbps)*125000, 10) + ";\nlimit_rate_after 0;\nproxy_ignore_headers X-Accel-Limit-Rate;\nfastcgi_ignore_headers X-Accel-Limit-Rate;\n") old, err := os.ReadFile(target) if err == nil && bytes.Equal(old, content) { continue } undo, err := writeManagedFile(target, content) if err != nil { rollback() return err } restore = append(restore, undo) changed = true } if changed { if err := a.runNginx(ctx, "-t"); err != nil { rollback() return errors.New("Nginx rejected bandwidth limit") } if err := a.runNginx(ctx, "-s", "reload"); err != nil { rollback() return err } } statePath, err := a.trafficLimitStatePath(spec.Project.HostName) if err != nil { return err } var previous struct { Mbps uint32 `json:"mbps"` Applied bool `json:"applied"` } if info, err := os.Lstat(statePath); err == nil { if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 { return errors.New("unsafe traffic policy state") } data, err := os.ReadFile(statePath) if err != nil { return err } _ = json.Unmarshal(data, &previous) } if !previous.Applied || previous.Mbps != spec.Mbps { binary := a.PurePWBinary if binary == "" { binary = "/www/server/pure-ftpd/bin/pure-pw" } rate := "" if spec.Mbps > 0 { rate = strconv.FormatUint(uint64(spec.Mbps)*125000/1024, 10) } if err = a.command(ctx, binary, "usermod", spec.Project.HostName, "-t", rate, "-T", rate, "-m"); err != nil { return errors.New("cannot set FTP account transfer limit") } data, _ := json.Marshal(map[string]any{"mbps": spec.Mbps, "applied": true}) if err = writeSecureFile(statePath, data, 0600); err != nil { return err } } return a.ensureFTPTransferLog(ctx) } func (a Agent) ftpTransferLogPath() string { if a.FTPLogPath != "" { return a.FTPLogPath } return "/www/wwwlogs/sea-vhost-ftp.log" } func (a Agent) ensureFTPTransferLog(ctx context.Context) error { configPath := a.PureFTPConfig if configPath == "" { configPath = "/www/server/pure-ftpd/etc/pure-ftpd.conf" } info, err := os.Lstat(configPath) if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 { return errors.New("unsafe FTP configuration") } content, err := os.ReadFile(configPath) if err != nil { return err } logPath := a.ftpTransferLogPath() if !filepath.IsAbs(logPath) || strings.ContainsAny(logPath, "\r\n\x00 ") { return errors.New("invalid FTP transfer log path") } wanted := []byte("AltLog stats:" + logPath) matches := ftpAltLogLine.FindAll(content, -1) if len(matches) == 1 && bytes.Equal(bytes.TrimSpace(matches[0]), wanted) { return nil } if requirePhysicalDirectory(filepath.Dir(logPath)) != nil { return errors.New("FTP log directory unavailable") } if existing, err := os.Lstat(logPath); err == nil { if !existing.Mode().IsRegular() || existing.Mode()&os.ModeSymlink != 0 { return errors.New("unsafe FTP log") } } else if !errors.Is(err, os.ErrNotExist) { return err } if len(matches) > 0 { backup := configPath + ".sea-vhost-before-stats" if _, err = os.Lstat(backup); errors.Is(err, os.ErrNotExist) { if err = writeSecureFile(backup, content, 0600); err != nil { return err } } } updated := ftpAltLogLine.ReplaceAll(content, nil) updated = append(bytes.TrimRight(updated, "\r\n"), '\n') updated = append(updated, wanted...) updated = append(updated, '\n') if err = writeSecureFile(configPath, updated, info.Mode().Perm()); err != nil { return err } if err = a.restartPureFTP(ctx, configPath); err != nil { _ = writeSecureFile(configPath, content, info.Mode().Perm()) _ = a.restartPureFTP(ctx, configPath) return errors.New("cannot activate FTP transfer log") } return nil }