package isolation import ( "context" "encoding/json" "errors" "fmt" "io" "log/slog" "net/http" "os" "path/filepath" "regexp" "strconv" "strings" "time" ) var ( phpSiteNamePattern = regexp.MustCompile(`^sv[a-f0-9]{10}(?:_[1-9][0-9]{0,19})?$`) phpVersionPattern = regexp.MustCompile(`^[5-9]\.[0-9]$`) ) type phpIdentityPaths struct { config, pid, socket, nginx string } func (a Agent) decodePHPIdentity(w http.ResponseWriter, r *http.Request) (PHPIdentitySpec, bool) { var spec PHPIdentitySpec decoder := json.NewDecoder(r.Body) decoder.DisallowUnknownFields() if err := decoder.Decode(&spec); err != nil || decoder.Decode(&struct{}{}) != io.EOF || !safeName.MatchString(spec.Project.HostName) || !phpSiteNamePattern.MatchString(spec.SiteName) || !webDomainPattern.MatchString(spec.Domain) || !phpVersionPattern.MatchString(spec.Version) || !validProjectRunPath(spec.Project.RunPath) || spec.Project.TenantID == 0 || spec.Project.StorageBytes == 0 || spec.Project.ProcessLimit == 0 || spec.ProcessLimit == 0 || spec.ProcessLimit > 100_000 { http.Error(w, "invalid request", http.StatusBadRequest) return PHPIdentitySpec{}, false } return spec, true } func (a Agent) configurePHPIdentity(w http.ResponseWriter, r *http.Request) { spec, ok := a.decodePHPIdentity(w, r) if !ok { return } ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() paths, binary, projectRoot, err := a.phpIdentityEnvironment(spec) if err != nil { http.Error(w, "PHP identity environment unavailable", http.StatusPreconditionFailed) return } tempRoot, err := a.preparePHPTempDirectory(ctx, projectRoot, spec.Project.HostName) if err != nil { http.Error(w, "cannot prepare isolated PHP temporary directory", http.StatusInternalServerError) return } content := renderPHPIdentityConfig(spec, projectRoot, tempRoot, paths) if err = writePrivateFile(paths.config, []byte(content)); err != nil { http.Error(w, "cannot write PHP identity configuration", http.StatusInternalServerError) return } if err = a.command(ctx, "chown", "root:"+spec.Project.HostName, paths.config); err != nil || a.command(ctx, "chmod", "0640", paths.config) != nil { http.Error(w, "cannot secure PHP identity configuration", http.StatusInternalServerError) return } // Validate as the tenant identity, not as root. PHP-FPM opens its configured // error log even during `-t`; a root validation would leave a root-owned // file in the tenant runtime directory and can also follow a tenant-created // symlink with root privileges. if err = testPHPAsIdentity(ctx, binary, paths.config, spec.Project.HostName); err != nil { slog.Error("PHP-FPM rejected isolated pool configuration", "site", spec.SiteName, "error", err) http.Error(w, "PHP-FPM rejected isolated pool configuration", http.StatusPreconditionFailed) return } _ = a.stopPHPIdentityProcess(ctx, paths) if err = a.startPHPIdentityProcess(ctx, binary, paths, spec.Project.HostName); err != nil { slog.Error("cannot start isolated PHP-FPM pool", "site", spec.SiteName, "identity", spec.Project.HostName, "error", err) http.Error(w, "cannot start isolated PHP-FPM pool", http.StatusInternalServerError) return } nginxContent := []byte(renderPHPNginxAdapter(paths.socket)) restore, err := writeManagedFile(paths.nginx, nginxContent) if err != nil { _ = a.stopPHPIdentityProcess(ctx, paths) http.Error(w, "cannot write isolated PHP adapter", http.StatusInternalServerError) return } rollback := func() { _ = restore() _ = a.runNginx(ctx, "-t") _ = a.runNginx(ctx, "-s", "reload") _ = a.stopPHPIdentityProcess(ctx, paths) } if err = a.runNginx(ctx, "-t"); err != nil { slog.Error("nginx rejected isolated PHP adapter", "site", spec.SiteName, "domain", spec.Domain, "error", err) rollback() http.Error(w, "Nginx rejected isolated PHP adapter", http.StatusPreconditionFailed) return } if err = a.runNginx(ctx, "-s", "reload"); err != nil { rollback() http.Error(w, "cannot reload Nginx for isolated PHP pool", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } func (a Agent) startPHPIdentity(w http.ResponseWriter, r *http.Request) { spec, ok := a.decodePHPIdentity(w, r) if !ok { return } ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) defer cancel() paths, binary, _, err := a.phpIdentityEnvironment(spec) if err != nil { http.Error(w, "PHP identity environment unavailable", http.StatusPreconditionFailed) return } if _, err = os.Stat(paths.config); err != nil { http.Error(w, "PHP identity has not been configured", http.StatusPreconditionFailed) return } if err = a.startPHPIdentityProcess(ctx, binary, paths, spec.Project.HostName); err != nil { slog.Error("cannot start isolated PHP-FPM pool", "site", spec.SiteName, "identity", spec.Project.HostName, "error", err) http.Error(w, "cannot start isolated PHP-FPM pool", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } func (a Agent) stopPHPIdentity(w http.ResponseWriter, r *http.Request) { spec, ok := a.decodePHPIdentity(w, r) if !ok { return } ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) defer cancel() paths, _, _, err := a.phpIdentityEnvironment(spec) if err != nil { http.Error(w, "PHP identity environment unavailable", http.StatusPreconditionFailed) return } if err = a.stopPHPIdentityProcess(ctx, paths); err != nil { http.Error(w, "cannot stop isolated PHP-FPM pool", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } func (a Agent) removePHPIdentity(w http.ResponseWriter, r *http.Request) { spec, ok := a.decodePHPIdentity(w, r) if !ok { return } ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second) defer cancel() paths, siteConfig, err := a.phpIdentityRemovalPaths(spec) if err != nil { http.Error(w, "PHP identity environment unavailable", http.StatusPreconditionFailed) return } if err = a.stopPHPIdentityProcess(ctx, paths); err != nil { http.Error(w, "cannot stop isolated PHP-FPM pool", http.StatusInternalServerError) return } var oldNginx []byte if oldNginx, err = os.ReadFile(paths.nginx); err != nil && !errors.Is(err, os.ErrNotExist) { http.Error(w, "cannot read isolated PHP adapter", http.StatusInternalServerError) return } if err == nil { if err = os.Remove(paths.nginx); err != nil { http.Error(w, "cannot remove isolated PHP adapter", http.StatusInternalServerError) return } if _, statErr := os.Stat(siteConfig); statErr == nil { if err = a.runNginx(ctx, "-t"); err != nil { _, _ = writeManagedFile(paths.nginx, oldNginx) http.Error(w, "Nginx rejected isolated PHP adapter removal", http.StatusPreconditionFailed) return } if err = a.runNginx(ctx, "-s", "reload"); err != nil { _, _ = writeManagedFile(paths.nginx, oldNginx) _ = a.runNginx(ctx, "-t") _ = a.runNginx(ctx, "-s", "reload") http.Error(w, "cannot reload Nginx after PHP adapter removal", http.StatusInternalServerError) return } } } for _, target := range []string{paths.config, paths.pid, paths.socket} { if info, statErr := os.Lstat(target); statErr == nil { if !info.Mode().IsRegular() && info.Mode()&os.ModeSocket == 0 { http.Error(w, "unsafe PHP identity state", http.StatusPreconditionFailed) return } _ = os.Remove(target) } } _ = os.Remove(filepath.Dir(paths.pid)) w.WriteHeader(http.StatusOK) } func (a Agent) phpIdentityEnvironment(spec PHPIdentitySpec) (phpIdentityPaths, string, string, error) { projectRoot, err := a.projectPath(spec.Project) if err != nil || requirePhysicalDirectory(projectRoot) != nil { return phpIdentityPaths{}, "", "", errors.New("project root unavailable") } if _, err = physicalRunDirectory(projectRoot, spec.Project.RunPath); err != nil { return phpIdentityPaths{}, "", "", err } stateRoot := strings.TrimSpace(a.PHPStateRoot) if stateRoot == "" { stateRoot = "/var/lib/sea-vhost-agent/php" } runRoot := strings.TrimSpace(a.PHPRunRoot) if runRoot == "" { runRoot = "/run/sea-vhost-php" } if !filepath.IsAbs(stateRoot) || !filepath.IsAbs(runRoot) { return phpIdentityPaths{}, "", "", errors.New("invalid PHP identity root") } if err = ensurePhysicalDirectory(stateRoot, 0700); err != nil { return phpIdentityPaths{}, "", "", err } if err = os.Chmod(stateRoot, 0711); err != nil { return phpIdentityPaths{}, "", "", err } if err = ensurePhysicalDirectory(runRoot, 0755); err != nil { return phpIdentityPaths{}, "", "", err } version := strings.ReplaceAll(spec.Version, ".", "") binary := filepath.Join("/www/server/php", version, "sbin/php-fpm") info, err := os.Lstat(binary) if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 || info.Mode()&0111 == 0 { return phpIdentityPaths{}, "", "", errors.New("PHP-FPM binary unavailable") } webPaths, err := a.webProtectionPaths(WebProtectionSpec{Project: spec.Project, Domain: spec.Domain}) if err != nil || verifySiteExtensionInclude(webPaths.siteConfig, webPaths.siteExtension) != nil { return phpIdentityPaths{}, "", "", errors.New("managed Nginx site unavailable") } key := spec.SiteName instanceRunRoot := filepath.Join(runRoot, key) permissionCtx, cancelPermissions := context.WithTimeout(context.Background(), 5*time.Second) defer cancelPermissions() if err = ensurePhysicalDirectory(instanceRunRoot, 0770); err != nil || a.command(permissionCtx, "chown", "root:"+spec.Project.HostName, instanceRunRoot) != nil || a.command(permissionCtx, "chmod", "0770", instanceRunRoot) != nil || a.command(permissionCtx, "setfacl", "-m", "u:www:--x,m::rwx,o::---", instanceRunRoot) != nil { return phpIdentityPaths{}, "", "", errors.New("cannot prepare PHP identity runtime directory") } for _, legacyPath := range []string{filepath.Join(runRoot, key+".pid"), filepath.Join(runRoot, key+".sock")} { if legacyInfo, legacyErr := os.Lstat(legacyPath); legacyErr == nil && (legacyInfo.Mode().IsRegular() || legacyInfo.Mode()&os.ModeSocket != 0) { _ = os.Remove(legacyPath) } } paths := phpIdentityPaths{ config: filepath.Join(stateRoot, key+".conf"), pid: filepath.Join(instanceRunRoot, "php-fpm.pid"), socket: filepath.Join(instanceRunRoot, "php-fpm.sock"), nginx: filepath.Join(filepath.Dir(webPaths.siteExtension), "sea-vhost-php.conf"), } return paths, binary, projectRoot, nil } func (a Agent) phpIdentityRemovalPaths(spec PHPIdentitySpec) (phpIdentityPaths, string, error) { stateRoot := strings.TrimSpace(a.PHPStateRoot) if stateRoot == "" { stateRoot = "/var/lib/sea-vhost-agent/php" } runRoot := strings.TrimSpace(a.PHPRunRoot) if runRoot == "" { runRoot = "/run/sea-vhost-php" } vhostRoot, err := filepath.Abs(a.NginxVhostRoot) if err != nil || !filepath.IsAbs(stateRoot) || !filepath.IsAbs(runRoot) || !filepath.IsAbs(vhostRoot) { return phpIdentityPaths{}, "", errors.New("invalid PHP identity path") } for _, root := range []string{stateRoot, runRoot, vhostRoot} { if err = requirePhysicalDirectory(root); err != nil { return phpIdentityPaths{}, "", err } } extensionRoot := filepath.Join(vhostRoot, "extension", strings.ToLower(spec.Domain)) if err = requirePhysicalDirectory(extensionRoot); err != nil && !errors.Is(err, os.ErrNotExist) { return phpIdentityPaths{}, "", err } paths := phpIdentityPaths{ config: filepath.Join(stateRoot, spec.SiteName+".conf"), pid: filepath.Join(runRoot, spec.SiteName, "php-fpm.pid"), socket: filepath.Join(runRoot, spec.SiteName, "php-fpm.sock"), nginx: filepath.Join(extensionRoot, "sea-vhost-php.conf"), } return paths, filepath.Join(vhostRoot, strings.ToLower(spec.Domain)+".conf"), nil } func (a Agent) preparePHPTempDirectory(ctx context.Context, projectRoot, hostName string) (string, error) { if err := ensureProjectRunDirectory(projectRoot, "/.sea-runtime/php"); err != nil { return "", err } tempRoot, err := physicalRunDirectory(projectRoot, "/.sea-runtime/php") if err != nil { return "", err } fileOwner := strings.TrimSpace(a.FileOwner) if fileOwner == "" { fileOwner = "sea-vhost" } if err = a.command(ctx, "chown", fileOwner+":"+hostName, tempRoot); err != nil { return "", err } if err = a.command(ctx, "chmod", "0770", tempRoot); err != nil { return "", err } if err = a.command(ctx, "setfacl", "-m", "u:www:---,m::rwx,o::---", tempRoot); err != nil { return "", err } return filepath.ToSlash(tempRoot), nil } func renderPHPIdentityConfig(spec PHPIdentitySpec, projectRoot, tempRoot string, paths phpIdentityPaths) string { children := int(spec.ProcessLimit) if children > 50 { children = 50 } if children < 1 { children = 1 } return fmt.Sprintf(`[global] pid = %s error_log = %s daemonize = yes [%s] user = %s group = %s listen = %s listen.mode = 0660 pm = ondemand pm.max_children = %d pm.process_idle_timeout = 15s pm.max_requests = 500 request_terminate_timeout = 120s catch_workers_output = yes clear_env = no php_admin_value[pcre.jit] = 0 security.limit_extensions = .php php_admin_value[open_basedir] = %s/ php_admin_value[sys_temp_dir] = %s php_admin_value[upload_tmp_dir] = %s php_admin_value[session.save_path] = %s `, paths.pid, filepath.ToSlash(filepath.Join(tempRoot, "fpm-error.log")), spec.SiteName, spec.Project.HostName, spec.Project.HostName, paths.socket, children, projectRoot, tempRoot, tempRoot, tempRoot) } func renderPHPNginxAdapter(socket string) string { return fmt.Sprintf(`# Managed by Sea vHost. Local changes will be replaced. # aaPanel's shared PHP include declares its own regex location later in the # server block. This equivalent, deliberately distinct expression is loaded # first from the site's extension directory and therefore selects the private # per-host socket without creating a duplicate Nginx location. location ~ ^.+\.php(?:/|$) { try_files $uri =404; fastcgi_pass unix:%s; fastcgi_index index.php; include fastcgi.conf; include pathinfo.conf; } `, filepath.ToSlash(socket)) } func (a Agent) startPHPIdentityProcess(ctx context.Context, binary string, paths phpIdentityPaths, identity string) error { if a.phpIdentityRunning(ctx, paths) { return nil } _ = os.Remove(paths.pid) _ = os.Remove(paths.socket) if err := startPHPAsIdentity(ctx, binary, paths.config, identity); err != nil { return err } for attempt := 0; attempt < 40; attempt++ { if a.phpIdentityRunning(ctx, paths) { if info, err := os.Lstat(paths.socket); err == nil && info.Mode()&os.ModeSocket != 0 { if err = a.command(ctx, "chown", identity+":www", paths.socket); err != nil || a.command(ctx, "chmod", "0660", paths.socket) != nil { return errors.New("cannot publish PHP-FPM socket") } return nil } } select { case <-ctx.Done(): return ctx.Err() case <-time.After(100 * time.Millisecond): } } return errors.New("PHP-FPM pool did not become ready") } func (a Agent) stopPHPIdentityProcess(ctx context.Context, paths phpIdentityPaths) error { pid, err := readPID(paths.pid) if errors.Is(err, os.ErrNotExist) { _ = os.Remove(paths.socket) return nil } if err != nil { return err } if err = a.signalPHPProcess(ctx, paths, "TERM", pid); err != nil && a.signalPHPProcess(ctx, paths, "0", pid) == nil { return err } for attempt := 0; attempt < 50; attempt++ { if a.signalPHPProcess(ctx, paths, "0", pid) != nil { _ = os.Remove(paths.pid) _ = os.Remove(paths.socket) return nil } select { case <-ctx.Done(): return ctx.Err() case <-time.After(100 * time.Millisecond): } } return errors.New("PHP-FPM pool did not stop") } func (a Agent) phpIdentityRunning(ctx context.Context, paths phpIdentityPaths) bool { pid, err := readPID(paths.pid) return err == nil && a.signalPHPProcess(ctx, paths, "0", pid) == nil } func (a Agent) signalPHPProcess(ctx context.Context, paths phpIdentityPaths, signal string, pid int) error { if a.runCommand != nil { return a.command(ctx, "kill", "-"+signal, strconv.Itoa(pid)) } return signalPHPAsIdentity(ctx, paths.config, signal, pid) } func readPID(path string) (int, error) { data, err := os.ReadFile(path) if err != nil { return 0, err } pid, err := strconv.Atoi(strings.TrimSpace(string(data))) if err != nil || pid < 2 { return 0, errors.New("invalid PHP-FPM pid") } return pid, nil } func writePrivateFile(path string, content []byte) error { if len(content) > 128<<10 { return errors.New("private managed file is too large") } directory := filepath.Dir(path) if err := requirePhysicalDirectory(directory); err != nil { return err } temporary, err := os.CreateTemp(directory, ".sea-vhost-php-*") if err != nil { return err } name := temporary.Name() defer os.Remove(name) if err = temporary.Chmod(0600); err == nil { _, err = temporary.Write(content) } if syncErr := temporary.Sync(); err == nil { err = syncErr } if closeErr := temporary.Close(); err == nil { err = closeErr } if err != nil { return err } return os.Rename(name, path) }