package isolation import ( "context" "crypto/tls" "encoding/json" "io" "net" "net/http" "net/url" "os" "path/filepath" "regexp" "sea-vhost/internal/hosting" "strconv" "strings" "time" ) type ScheduleExecutionSpec struct { Project ProjectSpec `json:"project"` SiteName string `json:"siteName"` Kind string `json:"kind"` Version string `json:"version"` Target string `json:"target"` Arguments []string `json:"arguments"` Environment map[string]string `json:"environment"` Domain string `json:"domain"` Port int `json:"port"` UseHTTPS bool `json:"useHTTPS"` } type ScheduleOutput struct { ExitCode int `json:"exitCode"` Output string `json:"output"` Truncated bool `json:"truncated"` } type ScheduleExecutor interface { ExecuteSchedule(context.Context, ScheduleExecutionSpec) (ScheduleOutput, error) } func (c *Client) ExecuteSchedule(ctx context.Context, v ScheduleExecutionSpec) (ScheduleOutput, error) { var out ScheduleOutput e := c.requestLong(ctx, "/v1/schedule/execute", v, &out) return out, e } func (Mock) ExecuteSchedule(context.Context, ScheduleExecutionSpec) (ScheduleOutput, error) { return ScheduleOutput{Output: "test task completed"}, nil } func (a Agent) executeSchedule(w http.ResponseWriter, r *http.Request) { var v ScheduleExecutionSpec d := json.NewDecoder(r.Body) d.DisallowUnknownFields() check := hosting.Startup{} if d.Decode(&v) != nil || d.Decode(&struct{}{}) != io.EOF || !managedWebHostPattern.MatchString(v.Project.HostName) || !phpSiteNamePattern.MatchString(v.SiteName) || !(v.SiteName == v.Project.HostName || strings.HasPrefix(v.SiteName, v.Project.HostName+"_")) || !validUsageSpec(ResourceUsageSpec{Project: v.Project}) { http.Error(w, "invalid scheduled task", 400) return } check.Arguments = v.Arguments check.Environment = v.Environment delete(check.Environment, "PORT") if check.Validate() != nil { http.Error(w, "invalid task parameters", 400) return } root, e := a.projectPath(v.Project) if e != nil { http.Error(w, "invalid host root", 412) return } working, e := physicalRunDirectory(root, v.Project.RunPath) if e != nil { http.Error(w, "website directory unavailable", 412) return } ctx, cancel := context.WithTimeout(r.Context(), 300*time.Second) defer cancel() var out ScheduleOutput if v.Kind == "url" { uri, e := url.ParseRequestURI(v.Target) if e != nil || uri.IsAbs() || uri.Host != "" || !strings.HasPrefix(v.Target, "/") || strings.HasPrefix(v.Target, "//") || !webDomainPattern.MatchString(v.Domain) || v.Port < 1 || v.Port > 65535 { http.Error(w, "only this website URL is allowed", 400) return } scheme := "http" if v.UseHTTPS { scheme = "https" } transport := &http.Transport{Proxy: nil, DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { return (&net.Dialer{Timeout: 10 * time.Second}).DialContext(ctx, "tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(v.Port))) }, TLSClientConfig: &tls.Config{ServerName: v.Domain, MinVersion: tls.VersionTLS12}} defer transport.CloseIdleConnections() client := &http.Client{Transport: transport, Timeout: 300 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} request, e := http.NewRequestWithContext(ctx, "GET", scheme+"://"+v.Domain+v.Target, nil) if e != nil { http.Error(w, "invalid task URL", 400) return } response, e := client.Do(request) if e != nil { out.ExitCode = 1 out.Output = "请求本站失败" } else { body, e := io.ReadAll(io.LimitReader(response.Body, 65537)) response.Body.Close() out.ExitCode = 0 if e != nil || response.StatusCode < 200 || response.StatusCode >= 300 { out.ExitCode = 1 } out.Truncated = len(body) > 65536 if out.Truncated { body = body[:65536] } out.Output = "HTTP " + strconv.Itoa(response.StatusCode) + "\n" + strings.ToValidUTF8(string(body), "�") } } else { if !hosting.ValidRelative(v.Target) || !validScheduleVersion(v.Kind, v.Version) { http.Error(w, "invalid task script", 400) return } binary := "" switch v.Kind { case "php": binary = filepath.Join("/www/server/php", strings.ReplaceAll(v.Version, ".", ""), "bin/php") case "python": binary = filepath.Join("/www/server/python_manager/versions", v.Version, "bin/python3") case "node": binary = filepath.Join("/www/server/nodejs", v.Version, "bin/node") default: http.Error(w, "unsupported task kind", 400) return } guard, e := os.OpenRoot(working) if e != nil { http.Error(w, "task directory unavailable", 412) return } i, e := guard.Lstat(v.Target) guard.Close() if e != nil || !i.Mode().IsRegular() || i.Mode()&os.ModeSymlink != 0 { http.Error(w, "script must be a regular website file", 412) return } args := append([]string{filepath.Join(working, v.Target)}, v.Arguments...) if v.Kind == "php" { args = append([]string{"-d", "pcre.jit=0", "-d", "opcache.jit=0"}, args...) } else if v.Kind == "node" { args = append([]string{"--jitless"}, args...) } out, e = runScheduledIdentity(ctx, v.Project.HostName, binary, args, working, v.Environment) if e != nil { http.Error(w, "cannot start isolated task", 422) return } } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(out) } func validScheduleVersion(kind, version string) bool { pattern := `^v?[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,4}$` if kind == "php" { pattern = `^[0-9]{1,2}\.[0-9]{1,2}$` } return regexp.MustCompile(pattern).MatchString(version) }