package panel import ( "context" "crypto/md5" "crypto/tls" "crypto/x509" "encoding/hex" "encoding/json" "errors" "fmt" "io" "math" "net" "net/http" "net/url" pathpkg "path" "regexp" "sea-vhost/internal/schedulerbridge" "slices" "sort" "strconv" "strings" "sync" "time" ) type Client struct { baseURL string apiKey string http *http.Client goMetadataMu sync.Mutex goRefreshAfter time.Time goLastGood []byte goLastGoodAt time.Time } type apiResponse struct { Status any `json:"status"` Msg string `json:"msg"` Message string `json:"message"` ErrorMsg string `json:"error_msg"` Index string `json:"index"` SiteID int64 `json:"siteId"` ID int64 `json:"id"` } type javaInstallation struct { Name string `json:"name"` Path string `json:"path"` Operation int `json:"operation"` } type pythonInstallation struct { Version string `json:"version"` PythonPath string `json:"python_path"` } type runtimeSDK struct { Version string `json:"version"` Installed any `json:"installed"` Installing any `json:"is_install"` } type runtimePluginInfo struct { Name string `json:"name"` Title string `json:"title"` Price any `json:"price"` PanelFree any `json:"panel_free"` Setup any `json:"setup"` MVersion string `json:"m_version"` MinVersion string `json:"version"` Versions []runtimePluginRelease `json:"versions"` } type runtimePluginRelease struct { MVersion string `json:"m_version"` Version string `json:"version"` Beta int `json:"beta"` } type runtimePluginPreparation struct { Status any `json:"status"` Msg string `json:"msg"` Message string `json:"message"` ErrorMsg string `json:"error_msg"` Name string `json:"name"` TmpPath string `json:"tmp_path"` InstallOpt string `json:"install_opt"` } var runtimeVersionPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,39}$`) var stablePythonVersionPattern = regexp.MustCompile(`^3\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$`) // freePanelRequestPolicy is deliberately explicit. Sea vHost must not grow // accidental dependencies on aaPanel Professional/Enterprise plugins through // a generic request helper. var freePanelRequestPolicy = map[string]map[string]bool{ "POST /crontab": {"GetCrontab": true, "AddCrontab": true, "set_cron_status": true}, "POST /system": {"GetSystemTotal": true}, "POST /site": { "GetPHPVersion": true, "AddSite": true, "multiple_basedir": true, "DeleteSite": true, "AddDomain": true, "DelDomain": true, "CreateProxy": true, "GetProxyList": true, "RemoveProxy": true, "SetSiteRunPath": true, "SetPath": true, "SiteStart": true, "SiteStop": true, "SetSSL": true, "CloseSSLConf": true, }, "POST /ftp": {"AddUser": true, "DeleteUser": true, "SetStatus": true, "SetUserPassword": true}, "POST /database": {"AddDatabase": true, "DeleteDatabase": true, "GetInfo": true, "ResDatabasePassword": true}, "POST /data": {"getData": true}, "POST /acme": {"apply_cert_api": true, "get_order_find": true, "SetCertToSite": true, "remove_order": true}, "POST /project/nodejs/get_nodejs_version/stype": {"": true}, "POST /project/nodejs/is_install_nodejs/stype": {"": true}, "POST /project/nodejs/get_project_list/stype": {"": true}, "POST /project/nodejs/create_project/stype": {"": true}, "POST /project/nodejs/start_project/stype": {"": true}, "POST /project/nodejs/stop_project/stype": {"": true}, "POST /project/nodejs/remove_project/stype": {"": true}, "POST /project/python/list_py_version/stype": {"": true}, "POST /project/python/GetProjectList/stype": {"": true}, "POST /mod/python/environment/add_environment/stype": {"": true}, // The trailing /stype path argument overwrites the Python create form's // stype=command value on aaPanel 12.0.0. Use the equivalent route without // that optional router argument for creation only. "POST /project/python/CreateProject": {"": true}, "POST /project/python/StartProject/stype": {"": true}, "POST /project/python/StopProject/stype": {"": true}, "POST /project/python/RemoveProject/stype": {"": true}, "POST /project/go/list_go_sdk/stype": {"": true}, "POST /project/go/install_go_sdk/stype": {"": true}, "POST /project/go/get_project_list/stype": {"": true}, "POST /project/go/create_project/stype": {"": true}, "POST /project/go/start_project/stype": {"": true}, "POST /project/go/stop_project/stype": {"": true}, "POST /project/go/remove_project/stype": {"": true}, "GET /mod/java/project/get_system_info/stype": {"": true}, "POST /mod/java/project/install_jdk_new/stype": {"": true}, "POST /mod/java/project/create_spring_boot_project/stype": {"": true}, "POST /mod/java/project/project_list/stype": {"": true}, "POST /mod/java/project/start_project/stype": {"": true}, "POST /mod/java/project/stop_project/stype": {"": true}, "POST /mod/java/project/remove_project/stype": {"": true}, "POST /plugin": { "get_soft_find": true, "install_plugin": true, "upgrade_plugin": true, "input_package": true, "a": true, }, } func NewClient(baseURL, apiKey string, insecureTLS bool, timeout time.Duration) *Client { transport := http.DefaultTransport.(*http.Transport).Clone() transport.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: insecureTLS} // #nosec G402 -- explicit operator setting for a loopback/self-signed panel only. return &Client{baseURL: strings.TrimRight(baseURL, "/"), apiKey: apiKey, http: &http.Client{Timeout: timeout, Transport: transport}} } func Signature(apiKey string, timestamp int64) string { inner := md5.Sum([]byte(apiKey)) // The panel protocol requires double MD5; this is not password hashing. outer := md5.Sum([]byte(strconv.FormatInt(timestamp, 10) + hex.EncodeToString(inner[:]))) return hex.EncodeToString(outer[:]) } func (c *Client) request(ctx context.Context, method, path string, values url.Values) ([]byte, error) { if err := validateFreePanelRequest(method, path, values); err != nil { return nil, err } if values == nil { values = make(url.Values) } else { values = cloneValues(values) } now := time.Now().Unix() values.Set("request_time", strconv.FormatInt(now, 10)) values.Set("request_token", Signature(c.apiKey, now)) var request *http.Request var err error if method == http.MethodGet { endpoint := c.baseURL + path + "?" + values.Encode() request, err = http.NewRequestWithContext(ctx, method, endpoint, nil) } else { request, err = http.NewRequestWithContext(ctx, method, c.baseURL+path, strings.NewReader(values.Encode())) if request != nil { request.Header.Set("Content-Type", "application/x-www-form-urlencoded") } } if err != nil { return nil, err } response, err := c.http.Do(request) if err != nil { return nil, fmt.Errorf("panel request: %w", err) } defer response.Body.Close() body, err := io.ReadAll(io.LimitReader(response.Body, (2<<20)+1)) if err != nil { return nil, err } if len(body) > 2<<20 { return nil, errors.New("panel response exceeded size limit") } if response.StatusCode < 200 || response.StatusCode > 299 { return nil, fmt.Errorf("panel HTTP %d", response.StatusCode) } return body, nil } func validateFreePanelRequest(method, path string, values url.Values) error { actions, ok := freePanelRequestPolicy[method+" "+path] if !ok || !actions[values.Get("action")] { return errors.New("panel operation is outside the free-core allowlist") } if path == "/site" && (values.Get("action") == "GetProxyList" || values.Get("action") == "RemoveProxy") { if !brokerDomainPattern.MatchString(values.Get("sitename")) || (values.Get("action") == "RemoveProxy" && values.Get("proxyname") != "sea-vhost-runtime") { return errors.New("only the fixed managed runtime proxy is allowed") } } if path == "/crontab" { switch values.Get("action") { case "GetCrontab": if values.Get("search") != schedulerbridge.CronName { return errors.New("only the Sea vHost system cron can be queried") } case "AddCrontab": if values.Get("name") != schedulerbridge.CronName || values.Get("sBody") != schedulerbridge.Command || values.Get("type") != "minute-n" || values.Get("where1") != "1" || values.Get("sType") != "toShell" || values.Get("user") != "root" { return errors.New("only the fixed Sea vHost scheduler command is allowed") } case "set_cron_status": id, e := strconv.ParseUint(values.Get("id"), 10, 64) if e != nil || id == 0 { return errors.New("invalid system cron identifier") } } } if path == "/mod/python/environment/add_environment/stype" { if values.Get("add_type") != "system" || !regexp.MustCompile(`^/www/server/python_manager/versions/3\.[0-9]+\.[0-9]+/bin/python3\.[0-9]+$`).MatchString(values.Get("path")) { return errors.New("only the managed Python SDK can be registered") } } if path == "/data" { table := values.Get("table") if table != "ftps" && table != "databases" && table != "sites" && table != "tasks" && table != "domain" { return errors.New("panel data table is outside the managed-resource allowlist") } if table == "domain" { id, err := strconv.ParseUint(values.Get("search"), 10, 64) if err != nil || id == 0 || values.Get("list") != "true" { return errors.New("domain queries require an exact site identifier") } } if table == "tasks" && values.Get("search") != "execshell" { return errors.New("only software execution task queries are allowed") } } if path == "/plugin" { switch values.Get("action") { case "get_soft_find": if !slices.Contains([]string{"nodejs", "pythonmamager"}, values.Get("sName")) && !phpSoftwarePattern.MatchString(values.Get("sName")) { return errors.New("panel plugin is outside the free runtime-component allowlist") } case "install_plugin": if phpSoftwarePattern.MatchString(values.Get("sName")) { if values.Get("type") != "0" || values.Get("upgrade") != "1" || values.Get("sName") != "php-"+values.Get("version") || !phpPatchNumberPattern.MatchString(values.Get("min_version")) { return errors.New("PHP update is outside the fixed-branch allowlist") } return nil } if !slices.Contains([]string{"nodejs", "pythonmamager"}, values.Get("sName")) || values.Get("type") != "0" || !runtimeVersionPattern.MatchString(values.Get("version")) || !runtimeVersionPattern.MatchString(values.Get("min_version")) { return errors.New("panel plugin installation is outside the free runtime-component allowlist") } case "upgrade_plugin": if !slices.Contains([]string{"nodejs", "pythonmamager"}, values.Get("plugin_name")) || !runtimeVersionPattern.MatchString(values.Get("version")) || !runtimeVersionPattern.MatchString(values.Get("min_version")) { return errors.New("panel plugin update is outside the free runtime-component allowlist") } case "input_package": pluginName := values.Get("plugin_name") if !slices.Contains([]string{"nodejs", "pythonmamager"}, pluginName) || values.Get("tmp_path") != "/www/server/panel/temp/"+pluginName || (values.Get("install_opt") != "i" && values.Get("install_opt") != "u") { return errors.New("panel plugin package import is outside the free runtime-component allowlist") } case "a": pluginName, method := values.Get("name"), values.Get("s") allowed := (pluginName == "nodejs" && slices.Contains([]string{"get_online_version_list", "install_nodejs"}, method)) || (pluginName == "pythonmamager" && method == "GetPythonV") if !allowed { return errors.New("panel plugin method is outside the free runtime-manager allowlist") } if method == "install_nodejs" && !runtimeVersionPattern.MatchString(values.Get("version")) { return errors.New("invalid runtime version") } } } return nil } func cloneValues(values url.Values) url.Values { cloned := make(url.Values, len(values)) for key, entries := range values { cloned[key] = append([]string(nil), entries...) } return cloned } func (c *Client) call(ctx context.Context, method, path string, values url.Values) (apiResponse, error) { body, err := c.request(ctx, method, path, values) if err != nil { return apiResponse{}, err } var result apiResponse if err := json.Unmarshal(body, &result); err != nil { return apiResponse{}, fmt.Errorf("panel returned non-JSON response: %w", err) } if failed(result.Status) { message := result.Msg if strings.TrimSpace(message) == "" { message = result.Message } if strings.TrimSpace(message) == "" { message = result.ErrorMsg } return result, errors.New(safeMessage(message)) } return result, nil } func failed(status any) bool { switch value := status.(type) { case bool: return !value case string: return value == "false" || value == "error" default: return false } } func safeMessage(message string) string { if strings.TrimSpace(message) == "" { return "panel operation failed" } if len(message) > 240 { return message[:240] } return message } func (c *Client) Ping(ctx context.Context) error { _, err := c.call(ctx, http.MethodPost, "/system", url.Values{"action": {"GetSystemTotal"}}) return err } func (c *Client) phpVersions(ctx context.Context) ([]string, error) { body, err := c.request(ctx, http.MethodPost, "/site", url.Values{"action": {"GetPHPVersion"}}) if err != nil { return nil, fmt.Errorf("read PHP versions: %w", err) } var phpVersions []struct { Version string `json:"version"` Status bool `json:"status"` } if err = json.Unmarshal(body, &phpVersions); err != nil { return nil, fmt.Errorf("decode PHP versions: %w", err) } php := make([]string, 0, len(phpVersions)) for _, item := range phpVersions { if item.Status && item.Version != "00" { php = append(php, normalizePHPVersion(item.Version)) } } return sortDottedVersionsDescending(cleanVersions(php)), nil } func (c *Client) nodeVersions(ctx context.Context) ([]string, error) { body, err := c.request(ctx, http.MethodPost, "/project/nodejs/get_nodejs_version/stype", nil) if err != nil { return nil, fmt.Errorf("read Node.js versions: %w", err) } var nodeVersions []string if err = json.Unmarshal(body, &nodeVersions); err != nil { return nil, fmt.Errorf("decode Node.js versions: %w", err) } return sortDottedVersionsDescending(cleanVersions(nodeVersions)), nil } func (c *Client) pythonVersions(ctx context.Context) ([]string, error) { installations, err := c.pythonInstallations(ctx) if err != nil { return nil, err } versions := make([]string, 0, len(installations)) for _, installation := range installations { versions = append(versions, installation.Version) } // Older patch releases may remain on disk for existing projects, but new // project creation must only offer the newest installed patch per branch. return latestPythonBranchVersions(versions), nil } func sortDottedVersionsDescending(versions []string) []string { sort.SliceStable(versions, func(left, right int) bool { leftParts := strings.Split(strings.TrimLeft(versions[left], "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"), ".") rightParts := strings.Split(strings.TrimLeft(versions[right], "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"), ".") partCount := max(len(leftParts), len(rightParts)) for index := 0; index < partCount; index++ { leftPart, rightPart := 0, 0 if index < len(leftParts) { leftPart, _ = strconv.Atoi(leftParts[index]) } if index < len(rightParts) { rightPart, _ = strconv.Atoi(rightParts[index]) } if leftPart != rightPart { return leftPart > rightPart } } return versions[left] > versions[right] }) return versions } func (c *Client) pythonInstallations(ctx context.Context) ([]pythonInstallation, error) { body, err := c.request(ctx, http.MethodPost, "/plugin", url.Values{"action": {"a"}, "name": {"pythonmamager"}, "s": {"GetPythonV"}}) if err != nil { return nil, fmt.Errorf("read Python installations: %w", err) } var installed []string if err = json.Unmarshal(body, &installed); err != nil { return nil, fmt.Errorf("decode Python installations: %w", err) } versions := cleanVersions(installed) result := make([]pythonInstallation, 0, len(versions)) for _, version := range versions { result = append(result, pythonInstallation{ Version: version, PythonPath: "/www/server/python_manager/versions/" + version + "/bin", }) } return result, nil } func (c *Client) pythonLatestAvailableVersions(ctx context.Context) ([]string, error) { // The legacy Python manager list contains the first patch releases of many // branches (for example 3.12.0) and is not updated consistently. aaPanel's // project SDK catalog tracks the current stable patch of each branch even // when its bundled installer cannot fetch that release. body, err := c.request(ctx, http.MethodPost, "/project/python/list_py_version/stype", nil) if err != nil { return nil, fmt.Errorf("read latest Python versions: %w", err) } var response struct { Status any `json:"status"` Msg string `json:"msg"` SDK struct { Streamline []runtimeSDK `json:"streamline"` All []runtimeSDK `json:"all"` } `json:"sdk"` } if err = json.Unmarshal(body, &response); err != nil { return nil, fmt.Errorf("decode latest Python versions: %w", err) } if failed(response.Status) { return nil, fmt.Errorf("read latest Python versions: %s", safeMessage(response.Msg)) } versions := make([]string, 0, len(response.SDK.Streamline)+len(response.SDK.All)) for _, item := range append(response.SDK.Streamline, response.SDK.All...) { versions = append(versions, item.Version) } versions = latestPythonBranchVersions(versions) if len(versions) == 0 { return nil, errors.New("latest Python branch catalog is empty") } return versions, nil } func latestPythonBranchVersions(candidates []string) []string { latest := make(map[string]string) for _, candidate := range candidates { version := strings.TrimSpace(candidate) parts := strings.Split(version, ".") if !stablePythonVersionPattern.MatchString(version) { continue } minor, err := strconv.Atoi(parts[1]) if err != nil || minor < 10 { continue } branch := parts[0] + "." + parts[1] if current := latest[branch]; current == "" || sortDottedVersionsDescending([]string{current, version})[0] == version { latest[branch] = version } } versions := make([]string, 0, len(latest)) for _, version := range latest { versions = append(versions, version) } return sortDottedVersionsDescending(cleanVersions(versions)) } func (c *Client) goVersions(ctx context.Context) ([]string, error) { body, err := c.goSDKInventory(ctx, false) if err != nil { return nil, fmt.Errorf("read Go versions: %w", err) } var goResponse struct { Status any `json:"status"` Msg string `json:"msg"` Installed []string `json:"installed"` } if err = json.Unmarshal(body, &goResponse); err != nil { return nil, fmt.Errorf("decode Go versions: %w", err) } if failed(goResponse.Status) { return nil, fmt.Errorf("read Go versions: %s", safeMessage(goResponse.Msg)) } return sortDottedVersionsDescending(cleanVersions(goResponse.Installed)), nil } func (c *Client) javaVersions(ctx context.Context) ([]string, error) { javaInstallations, err := c.javaInstallations(ctx) if err != nil { return nil, err } javaVersions := make([]string, 0, len(javaInstallations)) for _, item := range javaInstallations { if item.Operation == 1 || strings.TrimSpace(item.Path) != "" { javaVersions = append(javaVersions, item.Name) } } return sortDottedVersionsDescending(cleanVersions(javaVersions)), nil } func (c *Client) RuntimeCapabilities(ctx context.Context) (RuntimeCapabilities, error) { type runtimeProbe struct { name, policy string read func(context.Context) ([]string, error) } type runtimeProbeResult struct { probe runtimeProbe versions []string err error } probes := []runtimeProbe{ {name: "PHP", policy: PolicyFreeCore, read: c.phpVersions}, {name: "Node.js", policy: PolicyFreeProject, read: c.nodeVersions}, {name: "Python", policy: PolicyFreeProject, read: c.pythonVersions}, {name: "Go", policy: PolicyFreeProject, read: c.goVersions}, {name: "Java", policy: PolicyFreeProject, read: c.javaVersions}, } results := make(chan runtimeProbeResult, len(probes)) for _, item := range probes { item := item go func() { versions, err := item.read(ctx) results <- runtimeProbeResult{probe: item, versions: versions, err: err} }() } capabilities := make(RuntimeCapabilities, len(probes)) for range probes { result := <-results capability := RuntimeCapability{Status: RuntimeAvailable, Versions: result.versions, Policy: result.probe.policy} if result.err != nil { capability.Status = RuntimeProbeFailed capability.Versions = []string{} capability.Detail = runtimeProbeDetail(result.err) } else if len(result.versions) == 0 { capability.Status = RuntimeNotInstalled capability.Versions = []string{} } capabilities[result.probe.name] = capability } return capabilities, nil } func runtimeProbeDetail(err error) string { message := strings.ToLower(err.Error()) switch { case strings.Contains(message, "http 404") || strings.Contains(message, "not found"): return "接口不存在或组件未安装" case strings.Contains(message, "decode") || strings.Contains(message, "non-json"): return "接口返回格式与当前适配器不兼容" case errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled): return "运行环境探测超时" default: return "运行环境接口暂不可用" } } func (c *Client) RuntimeCatalog(ctx context.Context) (RuntimeCatalog, error) { capabilities, err := c.RuntimeCapabilities(ctx) if err != nil { return nil, err } catalog := make(RuntimeCatalog, len(capabilities)) for name, capability := range capabilities { catalog[name] = capability.Versions } return catalog, nil } func (c *Client) javaInstallations(ctx context.Context) ([]javaInstallation, error) { body, err := c.request(ctx, http.MethodGet, "/mod/java/project/get_system_info/stype", nil) if err != nil { return nil, fmt.Errorf("read Java versions: %w", err) } var response struct { Status any `json:"status"` Msg string `json:"msg"` Data struct { JDKInfo []javaInstallation `json:"jdk_info"` } `json:"data"` } if err = json.Unmarshal(body, &response); err != nil { return nil, fmt.Errorf("decode Java versions: %w", err) } if failed(response.Status) { return nil, fmt.Errorf("read Java versions: %s", safeMessage(response.Msg)) } return response.Data.JDKInfo, nil } func normalizePHPVersion(version string) string { version = strings.TrimSpace(version) if strings.Contains(version, ".") { return version } if len(version) >= 2 { return version[:len(version)-1] + "." + version[len(version)-1:] } return version } func cleanVersions(versions []string) []string { cleaned := make([]string, 0, len(versions)) seen := make(map[string]bool, len(versions)) for _, version := range versions { version = strings.TrimSpace(version) if !runtimeVersionPattern.MatchString(version) || seen[version] { continue } seen[version] = true cleaned = append(cleaned, version) } return cleaned } func panelNumberEquals(value any, expected string) bool { switch item := value.(type) { case float64: parsed, err := strconv.ParseFloat(expected, 64) return err == nil && item == parsed case string: return strings.TrimSpace(item) == expected case bool: return (expected == "1" && item) || (expected == "0" && !item) default: return false } } func (c *Client) runtimePlugin(ctx context.Context, pluginName, componentTitle string) (runtimePluginInfo, error) { body, err := c.request(ctx, http.MethodPost, "/plugin", url.Values{"action": {"get_soft_find"}, "sName": {pluginName}}) if err != nil { return runtimePluginInfo{}, fmt.Errorf("read %s component: %w", componentTitle, err) } var result runtimePluginInfo if err = json.Unmarshal(body, &result); err != nil { return runtimePluginInfo{}, fmt.Errorf("decode %s component: %w", componentTitle, err) } if result.Name != pluginName || !panelNumberEquals(result.Price, "0") || !panelNumberEquals(result.PanelFree, "1") { return runtimePluginInfo{}, fmt.Errorf("%s is not available as a free official component", componentTitle) } return result, nil } func latestRuntimePluginRelease(plugin runtimePluginInfo) (runtimePluginRelease, bool) { for _, release := range plugin.Versions { if release.Beta == 0 && runtimeVersionPattern.MatchString(release.MVersion) && runtimeVersionPattern.MatchString(release.Version) { return release, true } } if runtimeVersionPattern.MatchString(plugin.MVersion) && runtimeVersionPattern.MatchString(plugin.MinVersion) { return runtimePluginRelease{MVersion: plugin.MVersion, Version: plugin.MinVersion}, true } return runtimePluginRelease{}, false } func runtimePluginReleaseLabel(release runtimePluginRelease) string { return release.MVersion + "." + release.Version } func runtimePluginVersionCurrent(current string, release runtimePluginRelease) bool { current = strings.TrimSpace(current) return current == release.Version || current == runtimePluginReleaseLabel(release) } func (c *Client) nodeAvailableVersions(ctx context.Context) ([]string, error) { body, err := c.request(ctx, http.MethodPost, "/plugin", url.Values{"action": {"a"}, "name": {"nodejs"}, "s": {"get_online_version_list"}}) if err != nil { return nil, fmt.Errorf("read available Node.js versions: %w", err) } type nodeVersion struct { Version string `json:"version"` } var direct []nodeVersion if json.Unmarshal(body, &direct) == nil { versions := make([]string, 0, len(direct)) for _, item := range direct { versions = append(versions, item.Version) } return cleanVersions(versions), nil } var wrapped struct { Status any `json:"status"` Msg string `json:"msg"` Data []nodeVersion `json:"data"` } if err = json.Unmarshal(body, &wrapped); err != nil { return nil, fmt.Errorf("decode available Node.js versions: %w", err) } if failed(wrapped.Status) { return nil, errors.New(safeMessage(wrapped.Msg)) } versions := make([]string, 0, len(wrapped.Data)) for _, item := range wrapped.Data { versions = append(versions, item.Version) } return cleanVersions(versions), nil } func splitSDK(items []runtimeSDK) (available, installed, installing []string) { for _, item := range items { version := strings.TrimSpace(item.Version) if !runtimeVersionPattern.MatchString(version) { continue } available = append(available, version) if panelTruthy(item.Installed) { installed = append(installed, version) } if panelTruthy(item.Installing) { installing = append(installing, version) } } return cleanVersions(available), cleanVersions(installed), cleanVersions(installing) } func recommendedVersion(available, installed []string) string { if len(available) == 0 { return "" } installedSet := make(map[string]bool, len(installed)) for _, version := range installed { installedSet[version] = true } if !installedSet[available[0]] { return available[0] } return "" } func (c *Client) RuntimeEnvironments(ctx context.Context) ([]RuntimeEnvironment, error) { php, phpErr := c.phpVersions(ctx) goBody, goErr := c.goSDKInventory(ctx, true) javaItems, javaErr := c.javaInstallations(ctx) nodePlugin, nodeErr := c.runtimePlugin(ctx, "nodejs", "Node.js version manager") pythonPlugin, pythonPluginErr := c.runtimePlugin(ctx, "pythonmamager", "Python project manager") items := []RuntimeEnvironment{ {Name: "PHP", ComponentTitle: "PHP 运行环境", ComponentStatus: RuntimeComponentReady, Installed: php, Available: []string{}, Installing: []string{}, Detail: "PHP 版本由宝塔软件商店管理,Sea vHost 仅使用已安装版本。"}, {Name: "Node.js", ComponentTitle: "Node.js 版本管理器", ComponentStatus: RuntimeComponentFailed, Installed: []string{}, Available: []string{}, Installing: []string{}}, {Name: "Python", ComponentTitle: "Python 项目管理器", ComponentStatus: RuntimeComponentFailed, Installed: []string{}, Available: []string{}, Installing: []string{}}, {Name: "Go", ComponentTitle: "Go 项目环境", ComponentStatus: RuntimeComponentReady, Installed: []string{}, Available: []string{}, Installing: []string{}}, {Name: "Java", ComponentTitle: "Java 项目环境", ComponentStatus: RuntimeComponentReady, Installed: []string{}, Available: []string{}, Installing: []string{}}, } if phpErr != nil { items[0].ComponentStatus, items[0].Detail = RuntimeComponentFailed, runtimeProbeDetail(phpErr) } if nodeErr != nil { items[1].Detail = runtimeProbeDetail(nodeErr) } else if !panelTruthy(nodePlugin.Setup) { items[1].ComponentStatus = RuntimeComponentMissing items[1].ComponentInstallable = true if latest, ok := latestRuntimePluginRelease(nodePlugin); ok { items[1].ComponentLatestVersion = runtimePluginReleaseLabel(latest) } items[1].Detail = "可安装宝塔官方免费 Node.js 版本管理器。" } else { items[1].ComponentStatus = RuntimeComponentReady items[1].ComponentVersion = nodePlugin.MinVersion if latest, ok := latestRuntimePluginRelease(nodePlugin); ok { items[1].ComponentLatestVersion = runtimePluginReleaseLabel(latest) items[1].ComponentUpdateAvailable = nodePlugin.MinVersion != "" && !runtimePluginVersionCurrent(nodePlugin.MinVersion, latest) items[1].ComponentInstallable = items[1].ComponentUpdateAvailable } installed, installedErr := c.nodeVersions(ctx) available, availableErr := c.nodeAvailableVersions(ctx) if installedErr != nil || availableErr != nil { items[1].ComponentStatus = RuntimeComponentFailed items[1].Detail = "Node.js 版本清单暂不可用" } else { items[1].Installed, items[1].Available = installed, available items[1].Recommended = recommendedVersion(available, installed) } } if pythonPluginErr != nil { items[2].Detail = runtimeProbeDetail(pythonPluginErr) } else if !panelTruthy(pythonPlugin.Setup) { items[2].ComponentStatus = RuntimeComponentMissing items[2].ComponentInstallable = true if latest, ok := latestRuntimePluginRelease(pythonPlugin); ok { items[2].ComponentLatestVersion = runtimePluginReleaseLabel(latest) } items[2].Detail = "可安装宝塔官方免费 Python 项目管理器,安装后再选择 Python 版本。" } else { items[2].ComponentStatus = RuntimeComponentReady items[2].ComponentVersion = pythonPlugin.MinVersion if latest, ok := latestRuntimePluginRelease(pythonPlugin); ok { items[2].ComponentLatestVersion = runtimePluginReleaseLabel(latest) items[2].ComponentUpdateAvailable = pythonPlugin.MinVersion != "" && !runtimePluginVersionCurrent(pythonPlugin.MinVersion, latest) items[2].ComponentInstallable = items[2].ComponentUpdateAvailable } installations, installedErr := c.pythonInstallations(ctx) available, availableErr := c.pythonLatestAvailableVersions(ctx) if installedErr != nil || availableErr != nil { items[2].ComponentStatus, items[2].Detail = RuntimeComponentFailed, "Python 版本清单暂不可用" } else { installed := make([]string, 0, len(installations)) for _, item := range installations { installed = append(installed, item.Version) } items[2].Available, items[2].Installed = available, cleanVersions(installed) items[2].Recommended = recommendedVersion(available, installed) } } if goErr != nil { items[3].ComponentStatus, items[3].Detail = RuntimeComponentFailed, runtimeProbeDetail(goErr) } else { var response struct { Status any `json:"status"` Installed []string `json:"installed"` SDK struct { All []runtimeSDK `json:"all"` Streamline []runtimeSDK `json:"streamline"` } `json:"sdk"` } if err := json.Unmarshal(goBody, &response); err != nil || failed(response.Status) { items[3].ComponentStatus, items[3].Detail = RuntimeComponentFailed, "Go 版本清单暂不可用" } else { available, installed, installing := splitSDK(append(response.SDK.Streamline, response.SDK.All...)) installed = cleanVersions(append(installed, response.Installed...)) items[3].Available, items[3].Installed, items[3].Installing = available, installed, installing items[3].Recommended = recommendedVersion(available, installed) } } if javaErr != nil { items[4].ComponentStatus, items[4].Detail = RuntimeComponentFailed, runtimeProbeDetail(javaErr) } else { for _, item := range javaItems { if !runtimeVersionPattern.MatchString(item.Name) { continue } items[4].Available = append(items[4].Available, item.Name) if item.Operation == 1 || strings.TrimSpace(item.Path) != "" { items[4].Installed = append(items[4].Installed, item.Name) } else if item.Operation == 3 { items[4].Installing = append(items[4].Installing, item.Name) } } items[4].Available = cleanVersions(items[4].Available) items[4].Installed = cleanVersions(items[4].Installed) items[4].Installing = cleanVersions(items[4].Installing) items[4].Recommended = recommendedVersion(items[4].Available, items[4].Installed) } items[0].Patches = c.phpRuntimePatches(ctx, php) return items, nil } func (c *Client) InstallRuntimeComponent(ctx context.Context, runtimeName string) error { pluginName := "" componentTitle := "" switch runtimeName { case "Node.js": pluginName, componentTitle = "nodejs", "Node.js version manager" case "Python": // aaPanel's official plugin identifier intentionally contains this // historical spelling; it is verified against the free-plugin metadata. pluginName, componentTitle = "pythonmamager", "Python project manager" default: return errors.New("only official free Node.js and Python managers can be installed") } plugin, err := c.runtimePlugin(ctx, pluginName, componentTitle) if err != nil { return err } release, ok := latestRuntimePluginRelease(plugin) if !ok { return fmt.Errorf("%s component metadata is invalid", runtimeName) } installed := panelTruthy(plugin.Setup) if installed && runtimePluginVersionCurrent(plugin.MinVersion, release) { return nil } values := url.Values{"action": {"install_plugin"}, "sName": {pluginName}, "version": {release.MVersion}, "min_version": {release.Version}, "type": {"0"}} if installed { values = url.Values{"action": {"upgrade_plugin"}, "plugin_name": {pluginName}, "version": {release.MVersion}, "min_version": {release.Version}} } body, err := c.request(ctx, http.MethodPost, "/plugin", values) if err != nil { return err } var prepared runtimePluginPreparation if err := json.Unmarshal(body, &prepared); err != nil { return fmt.Errorf("decode %s component package: %w", runtimeName, err) } if failed(prepared.Status) { message := prepared.Msg if strings.TrimSpace(message) == "" { message = prepared.Message } if strings.TrimSpace(message) == "" { message = prepared.ErrorMsg } return errors.New(safeMessage(message)) } // Older panel builds may complete the installation in one request. if panelTruthy(prepared.Status) && prepared.TmpPath == "" { return nil } expectedOpt := "i" if installed { expectedOpt = "u" } if prepared.Name != pluginName || prepared.TmpPath != "/www/server/panel/temp/"+pluginName || prepared.InstallOpt != expectedOpt { return fmt.Errorf("panel returned invalid %s component package metadata", runtimeName) } result, err := c.call(ctx, http.MethodPost, "/plugin", url.Values{ "action": {"input_package"}, "tmp_path": {prepared.TmpPath}, "plugin_name": {prepared.Name}, "install_opt": {prepared.InstallOpt}, }) if err != nil { return err } if !panelTruthy(result.Status) { return fmt.Errorf("panel did not confirm %s component installation", runtimeName) } return nil } func (c *Client) InstallRuntimeEnvironment(ctx context.Context, runtimeName, version string) error { if !runtimeVersionPattern.MatchString(version) || !slices.Contains([]string{"Node.js", "Python", "Go", "Java"}, runtimeName) { return errors.New("invalid runtime installation request") } inventory, err := c.RuntimeEnvironments(ctx) if err != nil { return err } allowed := false for _, item := range inventory { if item.Name == runtimeName && item.ComponentStatus == RuntimeComponentReady && slices.Contains(item.Available, version) && !slices.Contains(item.Installed, version) && !slices.Contains(item.Installing, version) { allowed = true break } } if !allowed { return errors.New("runtime version is not available for installation") } switch runtimeName { case "Node.js": _, err = c.call(ctx, http.MethodPost, "/plugin", url.Values{"action": {"a"}, "name": {"nodejs"}, "s": {"install_nodejs"}, "version": {version}}) case "Python": return errors.New("Python source installation must use the privileged isolation installer") case "Go": _, err = c.call(ctx, http.MethodPost, "/project/go/install_go_sdk/stype", url.Values{"version": {version}}) case "Java": _, err = c.call(ctx, http.MethodPost, "/mod/java/project/install_jdk_new/stype", url.Values{"version": {version}}) } return err } func (c *Client) CreateSite(ctx context.Context, spec SiteSpec) (int64, error) { version, siteType := "00", "" if spec.Runtime == "PHP" { version, siteType = strings.ReplaceAll(spec.Version, ".", ""), "PHP" } webname, _ := json.Marshal(map[string]any{"domain": spec.Domain, "domainlist": []string{}, "count": 0}) result, err := c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"AddSite"}, "webname": {string(webname)}, "path": {spec.Path}, "type": {siteType}, "version": {version}, "port": {"80"}, "ps": {"Sea vHost: " + spec.Name}, "ftp": {"false"}, "sql": {"false"}}) if err != nil { return 0, err } ids, _ := json.Marshal([]int64{result.SiteID}) if _, err = c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"multiple_basedir"}, "site_ids": {string(ids)}, "stat": {"open"}}); err != nil { _ = c.DeleteSite(context.WithoutCancel(ctx), result.SiteID, spec.Domain) return 0, fmt.Errorf("enable open_basedir: %w", err) } if spec.RunPath != "" && spec.RunPath != "/" { if err = c.SetSiteRunPath(ctx, result.SiteID, spec.RunPath); err != nil { _ = c.DeleteSite(context.WithoutCancel(ctx), result.SiteID, spec.Domain) return 0, fmt.Errorf("set site run path: %w", err) } } return result.SiteID, nil } func (c *Client) ListUnmanagedSites(ctx context.Context) ([]ExistingSite, error) { body, err := c.request(ctx, http.MethodPost, "/data", url.Values{"action": {"getData"}, "table": {"sites"}, "limit": {"1000"}, "p": {"1"}, "search": {""}}) if err != nil { return nil, err } var response struct { Status any `json:"status"` Msg string `json:"msg"` Data []json.RawMessage `json:"data"` } if err = json.Unmarshal(body, &response); err != nil || failed(response.Status) { return nil, errors.New("panel returned an invalid site list") } items := make([]ExistingSite, 0, len(response.Data)) for _, raw := range response.Data { var row struct { ID json.RawMessage `json:"id"` Name string `json:"name"` Path string `json:"path"` Status string `json:"status"` PHPVersion string `json:"php_version"` } if json.Unmarshal(raw, &row) != nil { continue } id, parseErr := parsePanelID(row.ID) domain := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(row.Name), ".")) cleanPath := pathpkg.Clean(strings.TrimSpace(row.Path)) if parseErr != nil || id <= 0 || !brokerCompatibleDomain(domain) || !pathpkg.IsAbs(cleanPath) || !strings.HasPrefix(cleanPath+"/", "/www/wwwroot/") { continue } items = append(items, ExistingSite{ID: id, Domain: domain, Path: cleanPath, PHPVersion: normalizePHPVersion(row.PHPVersion), Status: row.Status}) } return items, nil } func brokerCompatibleDomain(value string) bool { if len(value) < 4 || len(value) > 253 || strings.ContainsAny(value, " /\\:\t\r\n") { return false } return strings.Contains(value, ".") } func (c *Client) SetSitePath(ctx context.Context, siteID int64, newPath string) error { _, err := c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"SetPath"}, "id": {strconv.FormatInt(siteID, 10)}, "path": {newPath}}) return err } func (c *Client) AdoptSite(ctx context.Context, siteID int64, sourcePath string, spec SiteSpec) error { items, err := c.ListUnmanagedSites(ctx) if err != nil { return err } found := false for _, item := range items { if item.ID == siteID && item.Domain == strings.ToLower(spec.Domain) && pathpkg.Clean(item.Path) == pathpkg.Clean(sourcePath) { found = true break } } if !found { return errors.New("panel site changed before adoption") } if err = c.SetSitePath(ctx, siteID, spec.Path); err != nil { return err } if spec.RunPath != "" && spec.RunPath != "/" { if err = c.SetSiteRunPath(ctx, siteID, spec.RunPath); err != nil { _ = c.SetSitePath(context.WithoutCancel(ctx), siteID, sourcePath) return err } } ids, _ := json.Marshal([]int64{siteID}) if _, err = c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"multiple_basedir"}, "site_ids": {string(ids)}, "stat": {"open"}}); err != nil { _ = c.SetSitePath(context.WithoutCancel(ctx), siteID, sourcePath) return err } return nil } func (c *Client) RollbackAdoption(ctx context.Context, siteID int64, _ string, sourcePath string) error { return c.SetSitePath(ctx, siteID, sourcePath) } func (c *Client) SetSiteRunPath(ctx context.Context, siteID int64, runPath string) error { _, err := c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"SetSiteRunPath"}, "id": {strconv.FormatInt(siteID, 10)}, "runPath": {runPath}}) return err } func (c *Client) MigrateRuntimeIdentity(context.Context, int64, string, bool) error { return errors.New("runtime identity migration is only available through the managed broker") } func (c *Client) DeleteSite(ctx context.Context, id int64, name string) error { _, err := c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"DeleteSite"}, "id": {strconv.FormatInt(id, 10)}, "webname": {name}}) return err } func (c *Client) AddDomain(ctx context.Context, siteID int64, siteName, domain string) error { _, err := c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"AddDomain"}, "id": {strconv.FormatInt(siteID, 10)}, "webname": {siteName}, "domain": {domain}}) return err } func (c *Client) DeleteDomain(ctx context.Context, siteID int64, siteName, domain string) error { // The panel can have committed a prior attempt before a local registry save // failed. Read the exact site's bindings to make a retry safe. body, err := c.request(ctx, http.MethodPost, "/data", url.Values{"action": {"getData"}, "table": {"domain"}, "search": {strconv.FormatInt(siteID, 10)}, "list": {"true"}}) if err != nil { return err } var rows []struct { Name string `json:"name"` Port int `json:"port"` PID int64 `json:"pid"` } if err = json.Unmarshal(body, &rows); err != nil { return errors.New("panel returned an invalid domain list") } found := false for _, row := range rows { if row.PID != siteID { return errors.New("panel returned bindings from another site") } if strings.EqualFold(row.Name, domain) && row.Port == 80 { found = true } } if !found { return nil } _, err = c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"DelDomain"}, "id": {strconv.FormatInt(siteID, 10)}, "webname": {siteName}, "domain": {domain}, "port": {"80"}}) return err } func (c *Client) CreateFTP(ctx context.Context, username, password, path string, maxBytes int64) (int64, error) { // Storage enforcement is tenant-wide and implemented by Sea vHost's // directory scanner. Do not depend on aaPanel's optional FTP quota route: // it is not consistently available across free panel/Pure-FTPd versions. _ = maxBytes result, err := c.call(ctx, http.MethodPost, "/ftp", url.Values{"action": {"AddUser"}, "ftp_username": {username}, "ftp_password": {password}, "path": {path}, "ps": {"Managed by Sea vHost"}}) if err != nil { return 0, err } if result.ID <= 0 { return c.lookupResourceID(ctx, "ftps", username) } return result.ID, nil } func (c *Client) DeleteFTP(ctx context.Context, id int64, username string) error { _, err := c.call(ctx, http.MethodPost, "/ftp", url.Values{"action": {"DeleteUser"}, "id": {strconv.FormatInt(id, 10)}, "username": {username}}) return err } func (c *Client) SetFTPState(ctx context.Context, id int64, username string, enabled bool) error { status := "0" if enabled { status = "1" } _, err := c.call(ctx, http.MethodPost, "/ftp", url.Values{"action": {"SetStatus"}, "id": {strconv.FormatInt(id, 10)}, "username": {username}, "status": {status}}) return err } func (c *Client) CreateDatabase(ctx context.Context, name, username, password string, siteID int64) (int64, error) { result, err := c.call(ctx, http.MethodPost, "/database", url.Values{"action": {"AddDatabase"}, "sid": {"0"}, "name": {name}, "db_user": {username}, "password": {password}, "address": {"127.0.0.1"}, "codeing": {"utf8mb4"}, "pid": {strconv.FormatInt(siteID, 10)}, "ps": {"Managed by Sea vHost"}}) if err != nil { return 0, err } if result.ID <= 0 { return c.lookupResourceID(ctx, "databases", name) } return result.ID, nil } func (c *Client) lookupResourceID(ctx context.Context, table, exactName string) (int64, error) { body, err := c.request(ctx, http.MethodPost, "/data", url.Values{ "action": {"getData"}, "table": {table}, "search": {exactName}, "limit": {"20"}, "p": {"1"}, }) if err != nil { return 0, fmt.Errorf("resolve created %s resource: %w", table, err) } var response struct { Status any `json:"status"` Msg string `json:"msg"` Data []json.RawMessage `json:"data"` } if err = json.Unmarshal(body, &response); err != nil { return 0, fmt.Errorf("resolve created %s resource: invalid response", table) } if failed(response.Status) { return 0, fmt.Errorf("resolve created %s resource: %s", table, safeMessage(response.Msg)) } var matchedID int64 for _, raw := range response.Data { var row struct { ID json.RawMessage `json:"id"` Name string `json:"name"` Username string `json:"username"` } if json.Unmarshal(raw, &row) != nil || (row.Name != exactName && row.Username != exactName) { continue } id, parseErr := parsePanelID(row.ID) if parseErr != nil || id <= 0 || (matchedID > 0 && matchedID != id) { return 0, fmt.Errorf("resolve created %s resource: ambiguous or invalid id", table) } matchedID = id } if matchedID <= 0 { return 0, fmt.Errorf("resolve created %s resource: exact resource not found", table) } return matchedID, nil } func parsePanelID(raw json.RawMessage) (int64, error) { text := strings.TrimSpace(string(raw)) if len(text) >= 2 && text[0] == '"' && text[len(text)-1] == '"' { var value string if err := json.Unmarshal(raw, &value); err != nil { return 0, err } text = value } return strconv.ParseInt(text, 10, 64) } func (c *Client) DeleteDatabase(ctx context.Context, id int64, name string) error { _, err := c.call(ctx, http.MethodPost, "/database", url.Values{"action": {"DeleteDatabase"}, "id": {strconv.FormatInt(id, 10)}, "sid": {"0"}, "name": {name}, "db_user": {name}}) return err } // DatabaseSize uses aaPanel's free core GetInfo action. The panel returns a // human-readable binary size, so normalize it before it crosses the broker. func (c *Client) DatabaseSize(ctx context.Context, _ int64, name string) (uint64, error) { body, err := c.request(ctx, http.MethodPost, "/database", url.Values{"action": {"GetInfo"}, "db_name": {name}}) if err != nil { return 0, err } var response struct { DataSize string `json:"data_size"` Database string `json:"database"` Status any `json:"status"` Msg string `json:"msg"` } if err = json.Unmarshal(body, &response); err != nil { return 0, errors.New("panel returned an invalid database size") } if failed(response.Status) || (response.Database != "" && response.Database != name) { return 0, fmt.Errorf("database size query failed: %s", safeMessage(response.Msg)) } return parsePanelByteSize(response.DataSize) } func parsePanelByteSize(value string) (uint64, error) { match := regexp.MustCompile(`(?i)^\s*([0-9]+(?:\.[0-9]+)?)\s*(b|kb|mb|gb|tb)?\s*$`).FindStringSubmatch(value) if match == nil { return 0, errors.New("panel returned an invalid database size") } number, err := strconv.ParseFloat(match[1], 64) if err != nil || number < 0 { return 0, errors.New("panel returned an invalid database size") } power := map[string]int{"": 0, "b": 0, "kb": 1, "mb": 2, "gb": 3, "tb": 4}[strings.ToLower(match[2])] bytes := number * math.Pow(1024, float64(power)) if bytes > math.MaxUint64 { return 0, errors.New("database size overflow") } return uint64(math.Ceil(bytes)), nil } func (c *Client) ConfigureRuntime(ctx context.Context, spec RuntimeSpec) error { if spec.Runtime == "PHP" { return nil } workingDirectory := pathpkg.Join(spec.Path, strings.TrimPrefix(spec.RunPath, "/")) entryPath := pathpkg.Join(workingDirectory, spec.EntryFile) if !pathpkg.IsAbs(workingDirectory) || !strings.HasPrefix(workingDirectory+"/", strings.TrimRight(spec.Path, "/")+"/") { return errors.New("runtime working directory is outside the managed site") } var createPath string var values url.Values switch spec.Runtime { case "Node.js": versions, err := c.nodeVersions(ctx) if err != nil { return err } if !slicesContains(versions, spec.Version) { return errors.New("selected Node.js version is not installed") } projectScript := fmt.Sprintf("env PORT=%d npm run start", spec.Port) if spec.Runner { projectScript = "/usr/local/libexec/sea-vhost-run " + spec.ProjectName } createPath = "/project/nodejs/create_project/stype" values = url.Values{ "project_name": {spec.ProjectName}, "project_cwd": {workingDirectory}, "project_script": {projectScript}, "project_ps": {"Managed by Sea vHost"}, "bind_extranet": {"0"}, "domains": {"[]"}, "is_power_on": {"1"}, "run_user": {spec.RunUser}, "max_memory_limit": {"0"}, "nodejs_version": {spec.Version}, "pkg_manager": {"npm"}, "port": {strconv.Itoa(spec.Port)}, } case "Python": installations, err := c.pythonInstallations(ctx) if err != nil { return err } basePythonPath := "" for _, installation := range installations { if installation.Version == spec.Version { basePythonPath = installation.PythonPath break } } if basePythonPath == "" { return errors.New("selected Python interpreter path is unavailable") } // Register only the root-managed SDK in the panel's environment inventory. // Detecting a tenant-writable virtualenv as root could execute tenant code. // The panel inventory canonicalizes python3 symlinks to python3.. pythonBin := pathpkg.Join(basePythonPath, "python"+strings.Join(strings.Split(spec.Version, ".")[:2], ".")) if _, err = c.call(ctx, http.MethodPost, "/mod/python/environment/add_environment/stype", url.Values{"add_type": {"system"}, "path": {pythonBin}}); err != nil { return fmt.Errorf("register managed Python interpreter: %w", err) } pythonPath := pathpkg.Join(workingDirectory, ".sea-runtime/python", spec.ProjectName+"-"+spec.Version) createPath = "/project/python/CreateProject" values = url.Values{ "pjname": {spec.ProjectName}, "port": {strconv.Itoa(spec.Port)}, "stype": {"command"}, "path": {workingDirectory}, "user": {spec.RunUser}, "venv_path": {pythonPath}, "python_bin": {pythonBin}, "project_cmd": {fmt.Sprintf("env PORT=%d %s %s", spec.Port, pathpkg.Join(pythonPath, "bin", "python3"), entryPath)}, "framework": {"python"}, "auto_run": {"true"}, "env_list": {"[]"}, } case "Go": versions, err := c.goVersions(ctx) if err != nil { return err } if !slicesContains(versions, spec.Version) { return errors.New("selected Go version is not installed") } createPath = "/project/go/create_project/stype" values = url.Values{ "project_name": {spec.ProjectName}, "project_exe": {entryPath}, "project_cmd": {entryPath}, "project_ps": {"Managed by Sea vHost"}, "bind_extranet": {"0"}, "domains": {"[]"}, "is_power_on": {"1"}, "run_user": {spec.RunUser}, "port": {strconv.Itoa(spec.Port)}, "env_list": {fmt.Sprintf(`[{"k":"PORT","v":"%d"}]`, spec.Port)}, "project_log": {"1"}, "web_log": {"0"}, } case "Java": installations, err := c.javaInstallations(ctx) if err != nil { return err } jdkPath := "" for _, installation := range installations { if installation.Name == spec.Version && (installation.Operation == 1 || strings.TrimSpace(installation.Path) != "") { jdkPath = strings.TrimSpace(installation.Path) break } } if jdkPath == "" { return errors.New("selected JDK is not installed") } javaCommand := fmt.Sprintf("%s -jar %s --server.port=%d", jdkPath, entryPath, spec.Port) if spec.Runner { // The native Java module validates both paths in its command. The // launcher verifies them against root-owned state before using it. javaCommand = "/usr/local/libexec/sea-vhost-run " + spec.ProjectName + " --java " + jdkPath + " " + entryPath } data, _ := json.Marshal(map[string]any{ "project_name": spec.ProjectName, "project_jar": entryPath, "project_jdk": jdkPath, "run_user": spec.RunUser, "project_cmd": javaCommand, "project_ps": "Managed by Sea vHost", "domains": []string{}, "bind_extranet": 0, "port": spec.Port, "auth": 1, "is_separation": 0, "api_url": "/", "nohup_log": 1, }) createPath = "/mod/java/project/create_spring_boot_project/stype" values = url.Values{"data": {string(data)}} default: return fmt.Errorf("unsupported runtime %q", spec.Runtime) } if spec.Runner && (spec.Runtime == "Python" || spec.Runtime == "Go") { values.Set("project_cmd", "/usr/local/libexec/sea-vhost-run "+spec.ProjectName) } if _, err := c.call(ctx, http.MethodPost, createPath, values); err != nil { // Several aaPanel language modules insert the project and launch its // process before reporting a later PID/log failure. The broker has not // registered the runtime at this point, so its normal delete operation is // deliberately unavailable. Re-query the module and remove only an exact // name + managed-directory match to prevent an untracked tenant process. if cleanupErr := c.removePartialRuntime(context.WithoutCancel(ctx), spec); cleanupErr != nil { return fmt.Errorf("create %s project: %w; partial-project cleanup was not confirmed: %v", spec.Runtime, err, cleanupErr) } return fmt.Errorf("create %s project: %w", spec.Runtime, err) } waitAttempts := 5 if spec.Runtime == "Python" { waitAttempts = 60 } else if spec.Runtime == "Java" { waitAttempts = 30 } if err := c.waitRuntimeRunning(ctx, spec, waitAttempts); err != nil { // The create handlers in several aaPanel project modules discard the // result returned by their internal start call. Invoke start once through // its public route so a concrete launch error is surfaced to Sea vHost. if startErr := c.callRuntimeState(ctx, spec, true); startErr != nil { // Java and some Python builds report "already running" as an error. // Never trust that text, but allow the normal list/status probe to // prove the process and listening port are actually healthy. if validationErr := c.waitRuntimeRunning(ctx, spec, 15); validationErr == nil { return nil } _ = c.RemoveRuntime(context.WithoutCancel(ctx), spec) return fmt.Errorf("%s 项目启动失败: %w", spec.Runtime, startErr) } err = c.waitRuntimeRunning(ctx, spec, 15) if err == nil { return nil } _ = c.RemoveRuntime(context.WithoutCancel(ctx), spec) return err } return nil } func (c *Client) removePartialRuntime(ctx context.Context, spec RuntimeSpec) error { route, err := c.runtimeRoute(spec.Runtime, "get_project_list") if err != nil { return err } body, err := c.request(ctx, http.MethodPost, route, url.Values{"search": {spec.ProjectName}, "p": {"1"}, "limit": {"20"}}) if err != nil { return fmt.Errorf("query partial runtime: %w", err) } var response struct { Data []map[string]any `json:"data"` } if err = json.Unmarshal(body, &response); err != nil { return errors.New("query partial runtime: panel returned invalid data") } workingDirectory := pathpkg.Clean(pathpkg.Join(spec.Path, strings.TrimPrefix(spec.RunPath, "/"))) found := false for _, item := range response.Data { name, _ := item["name"].(string) if name == "" { name, _ = item["project_name"].(string) } if name != spec.ProjectName { continue } if found { return errors.New("query partial runtime: duplicate exact project names") } found = true if !runtimeRecordMatchesManagedDirectory(item, workingDirectory) { return errors.New("query partial runtime: exact project name has an untrusted path") } if value, ok := runtimeRecordPort(item); ok && value != spec.Port { return errors.New("query partial runtime: exact project name has a different port") } } if !found { return nil } if err = c.RemoveRuntime(ctx, spec); err != nil { return fmt.Errorf("remove exact partial runtime: %w", err) } return nil } func runtimeRecordMatchesManagedDirectory(item map[string]any, workingDirectory string) bool { values := []string{} appendPaths := func(source map[string]any) { for _, key := range []string{"path", "project_cwd", "project_path", "jar_path"} { if value, ok := source[key].(string); ok && strings.TrimSpace(value) != "" { values = append(values, pathpkg.Clean(value)) } } } appendPaths(item) if raw, ok := item["project_config"].(string); ok { var config map[string]any if json.Unmarshal([]byte(raw), &config) == nil { appendPaths(config) } } else if config, ok := item["project_config"].(map[string]any); ok { appendPaths(config) } for _, value := range values { if value == workingDirectory || strings.HasPrefix(value+"/", strings.TrimRight(workingDirectory, "/")+"/") { return true } } return false } func runtimeRecordPort(item map[string]any) (int, bool) { for _, source := range []map[string]any{item, runtimeRecordConfig(item)} { value, exists := source["port"] if !exists { continue } switch typed := value.(type) { case float64: if typed == float64(int(typed)) { return int(typed), true } case string: parsed, err := strconv.Atoi(strings.TrimSpace(typed)) if err == nil { return parsed, true } } } return 0, false } func runtimeRecordConfig(item map[string]any) map[string]any { if config, ok := item["project_config"].(map[string]any); ok { return config } if raw, ok := item["project_config"].(string); ok { var config map[string]any if json.Unmarshal([]byte(raw), &config) == nil { return config } } return map[string]any{} } func slicesContains(values []string, target string) bool { for _, value := range values { if value == target { return true } } return false } func (c *Client) runtimeRoute(runtimeName, operation string) (string, error) { if runtimeName == "Java" { if operation == "get_project_list" { operation = "project_list" } return "/mod/java/project/" + operation + "/stype", nil } prefix := map[string]string{ "Node.js": "/project/nodejs/", "Python": "/project/python/", "Go": "/project/go/", }[runtimeName] if prefix == "" { return "", fmt.Errorf("unsupported runtime %q", runtimeName) } if runtimeName == "Python" { operation = map[string]string{ "get_project_list": "GetProjectList", "start_project": "StartProject", "stop_project": "StopProject", "remove_project": "RemoveProject", }[operation] if operation == "" { return "", errors.New("unsupported Python project operation") } } return prefix + operation + "/stype", nil } func (c *Client) waitRuntimeRunning(ctx context.Context, spec RuntimeSpec, attempts int) error { route, err := c.runtimeRoute(spec.Runtime, "get_project_list") if err != nil { return err } var lastState string for attempt := 0; attempt < attempts; attempt++ { body, requestErr := c.request(ctx, http.MethodPost, route, url.Values{"search": {spec.ProjectName}, "p": {"1"}, "limit": {"20"}}) if requestErr == nil { var response struct { Data []struct { Name string `json:"name"` Run any `json:"run"` ListenOK any `json:"listen_ok"` PID any `json:"pid"` Listen []any `json:"listen"` } `json:"data"` } if json.Unmarshal(body, &response) == nil { for _, item := range response.Data { if item.Name != spec.ProjectName { continue } lastState = "项目记录存在但进程未运行" if spec.Runtime == "Java" { if panelTruthy(item.PID) && panelListenContains(item.Listen, spec.Port) { return nil } continue } if panelTruthy(item.Run) && (item.ListenOK == nil || panelTruthy(item.ListenOK)) { return nil } } } } select { case <-ctx.Done(): return ctx.Err() case <-time.After(time.Second): } } if lastState == "" { lastState = "宝塔未返回新建项目记录" } return fmt.Errorf("%s 项目启动验证失败: %s", spec.Runtime, lastState) } func panelTruthy(value any) bool { switch typed := value.(type) { case bool: return typed case float64: return typed > 0 case string: value := strings.TrimSpace(strings.ToLower(typed)) return value != "" && value != "0" && value != "false" && value != "none" && value != "null" default: return false } } func panelListenContains(values []any, port int) bool { wanted := strconv.Itoa(port) for _, value := range values { switch typed := value.(type) { case float64: if int(typed) == port && typed == float64(int(typed)) { return true } case string: if strings.TrimSpace(typed) == wanted { return true } } } return false } func (c *Client) RemoveRuntime(ctx context.Context, spec RuntimeSpec) error { if spec.Runtime == "PHP" { return nil } route, err := c.runtimeRoute(spec.Runtime, "remove_project") if err != nil { return err } // Python's legacy removal handler can erase the project record without // stopping processes started by the newer service manager. Stop through // the public runtime API and verify its listener before destroying the // metadata needed to find and stop the managed process. if err := c.SetRuntimeState(ctx, spec, false); err != nil { return fmt.Errorf("stop managed runtime before deletion: %w", err) } _, err = c.call(ctx, http.MethodPost, route, url.Values{"project_name": {spec.ProjectName}, "name": {spec.ProjectName}}) if err == nil { return waitRuntimePortStopped(ctx, spec, 8) } // Retrying a deletion is safe only when both the exact project record and // its managed listener are absent. Never swallow a generic panel error. present, verifyErr := c.runtimeRecordPresent(ctx, spec) if verifyErr == nil && !present && waitRuntimePortStopped(ctx, spec, 4) == nil { return nil } return err } func (c *Client) runtimeRecordPresent(ctx context.Context, spec RuntimeSpec) (bool, error) { route, err := c.runtimeRoute(spec.Runtime, "get_project_list") if err != nil { return false, err } body, err := c.request(ctx, http.MethodPost, route, url.Values{"search": {spec.ProjectName}, "p": {"1"}, "limit": {"20"}}) if err != nil { return false, err } var response struct { Data []map[string]any `json:"data"` Status any `json:"status"` } if json.Unmarshal(body, &response) != nil || response.Data == nil || failed(response.Status) { return false, errors.New("cannot verify managed runtime record") } for _, item := range response.Data { name, _ := item["name"].(string) if name == "" { name, _ = item["project_name"].(string) } if name == spec.ProjectName { return true, nil } } if len(response.Data) >= 20 { return false, errors.New("runtime record query was truncated") } return false, nil } func (c *Client) SetRuntimeState(ctx context.Context, spec RuntimeSpec, enabled bool) error { if spec.Runtime == "PHP" { return nil } stateErr := c.callRuntimeState(ctx, spec, enabled) if enabled { if stateErr != nil { return stateErr } return c.waitRuntimeRunning(ctx, spec, 30) } stopErr := waitRuntimePortStopped(ctx, spec, 20) if stopErr == nil { // Treat aaPanel's version-dependent "already stopped" response as // idempotent only when the managed backend port proves the process is // no longer serving. return nil } if stateErr != nil { return stateErr } return stopErr } func waitRuntimePortStopped(ctx context.Context, spec RuntimeSpec, attempts int) error { address := net.JoinHostPort("127.0.0.1", strconv.Itoa(spec.Port)) const requiredClosedChecks = 4 closedChecks := 0 for attempt := 0; attempt < attempts; attempt++ { connection, err := (&net.Dialer{Timeout: 500 * time.Millisecond}).DialContext(ctx, "tcp", address) if err != nil { closedChecks++ if closedChecks >= requiredClosedChecks { return nil } } else { _ = connection.Close() closedChecks = 0 } if attempt+1 == attempts { break } select { case <-ctx.Done(): return ctx.Err() case <-time.After(500 * time.Millisecond): } } return fmt.Errorf("%s 项目停止验证失败: 后端端口 %d 仍在监听", spec.Runtime, spec.Port) } func (c *Client) callRuntimeState(ctx context.Context, spec RuntimeSpec, enabled bool) error { operation := "stop_project" if enabled { operation = "start_project" } route, err := c.runtimeRoute(spec.Runtime, operation) if err != nil { return err } _, err = c.call(ctx, http.MethodPost, route, url.Values{"project_name": {spec.ProjectName}, "name": {spec.ProjectName}}) return err } func (c *Client) ConfigureProxy(ctx context.Context, siteID int64, domain string, port int) error { _, err := c.call(ctx, http.MethodPost, "/site", url.Values{"action": {"CreateProxy"}, "sitename": {domain}, "proxyname": {"sea-vhost-runtime"}, "proxydir": {"/"}, "proxysite": {fmt.Sprintf("http://127.0.0.1:%d", port)}, "todomain": {domain}, "type": {"1"}, "cache": {"0"}, "cachetime": {"1"}, "subfilter": {"[]"}, "advanced": {"0"}}) return err } func (c *Client) RequestCertificate(ctx context.Context, id int64, path string, domains []string) error { _, err := c.IssueManagedCertificate(ctx, id, path, domains) return err } func (c *Client) IssueManagedCertificate(ctx context.Context, siteID int64, path string, domains []string) (string, error) { if siteID <= 0 || len(domains) == 0 || strings.TrimSpace(domains[0]) == "" { return "", errors.New("invalid managed site certificate request") } encoded, _ := json.Marshal(domains) raw, err := c.request(ctx, http.MethodPost, "/acme", url.Values{"action": {"apply_cert_api"}, "id": {strconv.FormatInt(siteID, 10)}, "domains": {string(encoded)}, "auth_type": {"http"}, "auth_to": {strconv.FormatInt(siteID, 10)}, "ca": {"letsencrypt"}}) if err != nil { return "", fmt.Errorf("create ACME order: %w", err) } var order apiResponse if json.Unmarshal(raw, &order) != nil { return "", errors.New("panel returned an invalid ACME response") } if failed(order.Status) { return "", errors.New("panel ACME request failed: " + safeMessage(order.Msg)) } // Current aaPanel completes issuance synchronously. Keep private material // inside this privileged adapter and install only a matching, valid leaf. var issued struct { Certificate string `json:"cert"` Root string `json:"root"` PrivateKey string `json:"private_key"` Domains []string `json:"domains"` } if json.Unmarshal(raw, &issued) == nil && (issued.Certificate != "" || issued.PrivateKey != "") { chain := strings.TrimSpace(issued.Certificate) + "\n" + strings.TrimSpace(issued.Root) + "\n" if len(chain) > 96<<10 || len(issued.PrivateKey) > 32<<10 { return "", errors.New("panel issued an oversized certificate") } pair, e := tls.X509KeyPair([]byte(chain), []byte(issued.PrivateKey)) if e != nil || len(pair.Certificate) == 0 { return "", errors.New("panel issued an invalid certificate or private key") } leaf, e := x509.ParseCertificate(pair.Certificate[0]) if e != nil || !leaf.NotAfter.After(time.Now()) || leaf.NotBefore.After(time.Now().Add(5*time.Minute)) { return "", errors.New("panel issued a certificate outside its validity period") } for _, domain := range domains { if leaf.VerifyHostname(domain) != nil { return "", errors.New("panel certificate does not cover every managed domain") } } if len(issued.Domains) == 0 { issued.Domains = domains } if !sameDomainSet(issued.Domains, domains) { return "", errors.New("panel certificate order has unexpected domains") } if e = c.InstallCertificate(ctx, siteID, strings.ToLower(strings.TrimSpace(domains[0])), issued.PrivateKey, chain); e != nil { return "", fmt.Errorf("deploy issued certificate: %w", e) } return managedACMEIndex(issued.Domains), nil } order.Index = strings.TrimSpace(order.Index) if order.Index == "" { return "", errors.New("panel ACME response did not include an order index") } status := strings.ToLower(strings.TrimSpace(fmt.Sprint(order.Status))) for attempt := 0; status != "valid"; attempt++ { if status == "expired" || status == "invalid" || status == "revoked" || status == "deactivated" { return "", fmt.Errorf("ACME order ended with status %s", status) } if attempt >= 30 { return "", errors.New("ACME order did not become valid before the timeout") } select { case <-ctx.Done(): return "", ctx.Err() case <-time.After(2 * time.Second): } detail, detailErr := c.call(ctx, http.MethodPost, "/acme", url.Values{"action": {"get_order_find"}, "index": {order.Index}}) if detailErr != nil { return "", fmt.Errorf("read ACME order: %w", detailErr) } status = strings.ToLower(strings.TrimSpace(fmt.Sprint(detail.Status))) } if _, err = c.call(ctx, http.MethodPost, "/acme", url.Values{"action": {"SetCertToSite"}, "index": {order.Index}, "siteName": {strings.ToLower(strings.TrimSpace(domains[0]))}}); err != nil { return "", fmt.Errorf("deploy ACME certificate: %w", err) } return order.Index, nil } func (c *Client) InstallCertificate(ctx context.Context, _ int64, siteName, privateKey, certificate string) error { _, err := c.call(ctx, http.MethodPost, "/site", url.Values{ "action": {"SetSSL"}, "siteName": {siteName}, "key": {privateKey}, "csr": {certificate}, }) return err } func (c *Client) DisableCertificate(ctx context.Context, _ int64, siteName string) error { _, err := c.call(ctx, http.MethodPost, "/site", url.Values{ "action": {"CloseSSLConf"}, "siteName": {siteName}, "updateOf": {"1"}, }) return err } func (c *Client) SetSiteState(ctx context.Context, siteID int64, name string, enabled bool) error { action := "SiteStop" if enabled { action = "SiteStart" } _, err := c.call(ctx, http.MethodPost, "/site", url.Values{"action": {action}, "id": {strconv.FormatInt(siteID, 10)}, "name": {name}}) return err }