package main import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/url" "os" "os/exec" "path/filepath" "regexp" "runtime" "strings" "time" "golang.org/x/crypto/ssh" ) const defaultReleaseBaseURL = "https://github.com/klipperanywhere/klipperanywhere/releases/latest/download" const rinkhalsAppRoot = "/useremain/home/rinkhals/apps/60-klipperanywhere-agent" const ( installHostTypeStandard = "standard" installHostTypeRinkhals = "rinkhals" ) type sshInstallRequest struct { Host string `json:"host"` Port int `json:"port"` Username string `json:"username"` Password string `json:"password"` HostType string `json:"host_type"` ServerURL string `json:"server_url"` PrinterID string `json:"printer_id"` MoonrakerURL string `json:"moonraker_url"` UIURL string `json:"ui_url"` UIAutoDetect *bool `json:"ui_auto_detect"` } type sshInstallResponse struct { PrinterID string `json:"printer_id"` Host string `json:"host"` Port int `json:"port"` RemoteHost string `json:"remote_host"` HostType string `json:"host_type"` Message string `json:"message"` ReleaseURL string `json:"release_url"` ServerURL string `json:"server_url"` BinarySource string `json:"binary_source"` ConfigPath string `json:"config_path"` BinaryPath string `json:"binary_path"` PostInstallConnected bool `json:"post_install_connected"` PostInstallMessage string `json:"post_install_message"` RollbackPerformed bool `json:"rollback_performed"` RollbackMessage string `json:"rollback_message"` } func (s *server) handleInstallPage(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/install" { http.NotFound(w, r) return } page, err := os.ReadFile("web/static/install.html") if err != nil { http.Error(w, "install page unavailable", http.StatusInternalServerError) return } sess, ok := s.currentSession(r) if !ok { http.Redirect(w, r, "/login", http.StatusSeeOther) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") page = []byte(strings.ReplaceAll(string(page), "{{CSRF_TOKEN}}", sess.CSRFToken)) _, _ = w.Write(page) } func (s *server) handleInstallSSHAPI(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { w.Header().Set("Allow", "POST") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } sess, ok := s.currentSession(r) if !ok { writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) return } if sess.Role != "admin" { http.Error(w, "admin access required", http.StatusForbidden) return } if !s.verifyCSRF(w, r, sess) { return } var req sshInstallRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "invalid json", http.StatusBadRequest) return } job, err := s.newInstallJob(req) if err != nil { http.Error(w, "failed to create install job", http.StatusInternalServerError) return } job.addStep("queued", "Queued installer job.") go s.runInstallSSHJob(context.Background(), requestOrigin(r), sess.Username, req, job) writeJSON(w, http.StatusAccepted, map[string]any{ "ok": true, "job_id": job.ID, "status": job.snapshot().Status, "message": job.snapshot().Message, "printer_id": job.PrinterID, }) } func (s *server) handleInstallSSHJobAPI(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { w.Header().Set("Allow", "GET") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } jobID := strings.TrimPrefix(r.URL.Path, "/api/install/ssh/jobs/") if jobID == "" || jobID == r.URL.Path { http.NotFound(w, r) return } job, ok := s.getInstallJob(jobID) if !ok { http.NotFound(w, r) return } writeJSON(w, http.StatusOK, job.snapshot()) } func (s *server) runInstallSSHJob(ctx context.Context, origin string, actor string, req sshInstallRequest, job *installJob) { job.markRunning("starting", "Starting installer job.") resp, err := s.installPrinterOverSSH(ctx, origin, actor, req, func(stage, message string) { job.addStep(stage, message) }) if err != nil { job.finish("failed", "failed", err.Error(), nil, err) s.logAudit(auditEvent{ Actor: actor, Action: actionLabel("printer_install_ssh"), PrinterID: job.PrinterID, Detail: fmt.Sprintf("failed to install printer agent on %s:%d (%s)", job.Host, job.Port, err.Error()), }) return } job.finish("succeeded", "complete", "Installer completed successfully.", &resp, nil) s.logAudit(auditEvent{ Actor: actor, Action: actionLabel("printer_install_ssh"), PrinterID: resp.PrinterID, Detail: fmt.Sprintf("installed printer agent on %s:%d (%s)", resp.Host, resp.Port, resp.PostInstallMessage), }) } func (s *server) installPrinterOverSSH(ctx context.Context, origin string, actor string, req sshInstallRequest, progress func(stage, message string)) (resp sshInstallResponse, err error) { host := strings.TrimSpace(req.Host) if host == "" { return sshInstallResponse{}, errors.New("host is required") } username := strings.TrimSpace(req.Username) if username == "" { return sshInstallResponse{}, errors.New("username is required") } password := req.Password if password == "" { return sshInstallResponse{}, errors.New("password is required") } port := req.Port if port <= 0 { port = 22 } hostType := normalizeInstallHostType(req.HostType) if progress != nil { progress("ssh", "Connecting to printer host over SSH.") } client, err := dialSSH(host, port, username, password) if err != nil { return sshInstallResponse{}, err } defer client.Close() remoteHostOut, err := sshRunRetry(client, 3, 300*time.Millisecond, func() (string, error) { return sshRun(client, "hostname") }) if err != nil { return sshInstallResponse{}, fmt.Errorf("failed to read remote hostname: %w", err) } remoteHost := strings.TrimSpace(remoteHostOut) if progress != nil { progress("ssh", fmt.Sprintf("Connected to %s. Detecting host architecture.", remoteHost)) } remoteArchOut, err := sshRunRetry(client, 3, 300*time.Millisecond, func() (string, error) { return sshRun(client, `sh -lc 'uname -m 2>/dev/null || arch 2>/dev/null || echo unknown'`) }) if err != nil { return sshInstallResponse{}, fmt.Errorf("failed to detect remote architecture: %w", err) } remoteArch := strings.TrimSpace(remoteArchOut) printerID := sanitizePrinterID(req.PrinterID) if printerID == "" { printerID = sanitizePrinterID(remoteHost) } if printerID == "" { printerID = sanitizePrinterID(host) } if printerID == "" { return sshInstallResponse{}, errors.New("printer id could not be determined") } serverURL, err := resolveInstallServerURL(origin, req.ServerURL) if err != nil { return sshInstallResponse{}, err } if progress != nil { progress("build", fmt.Sprintf("Preparing %s binary for %s.", remoteArch, printerID)) } releaseURL := defaultReleaseBaseURL installRecord := printerInstallRecord{ Host: host, Port: port, Username: username, HostType: hostType, ServerURL: serverURL, PrinterID: printerID, MoonrakerURL: strings.TrimSpace(req.MoonrakerURL), UIURL: strings.TrimSpace(req.UIURL), UIAutoDetect: true, RequestedBy: actor, RemoteHost: remoteHost, ReleaseURL: defaultReleaseBaseURL, Status: "pending", } if req.UIAutoDetect != nil { installRecord.UIAutoDetect = *req.UIAutoDetect } defer func() { if printerID == "" { return } if err != nil { installRecord.Status = "failed" installRecord.Error = err.Error() } else { installRecord.Status = "installed" installRecord.Error = "" installRecord.PostInstallConnected = resp.PostInstallConnected installRecord.PostInstallMessage = resp.PostInstallMessage installRecord.RollbackPerformed = resp.RollbackPerformed installRecord.RollbackMessage = resp.RollbackMessage if resp.ReleaseURL != "" { installRecord.ReleaseURL = resp.ReleaseURL } if resp.BinarySource != "" { installRecord.BinarySource = resp.BinarySource } if resp.ConfigPath != "" { installRecord.ConfigPath = resp.ConfigPath } if resp.BinaryPath != "" { installRecord.BinaryPath = resp.BinaryPath } if resp.Message != "" { installRecord.Message = resp.Message } } if _, saveErr := s.printerSettings.updateInstall(printerID, installRecord); saveErr != nil { fmt.Printf("failed to persist install details printer_id=%s: %v\n", printerID, saveErr) } }() if hostType == installHostTypeRinkhals { resp, err = s.installPrinterAsRinkhalsApp(ctx, client, printerID, serverURL, req, remoteArch, releaseURL, progress) if err != nil { return sshInstallResponse{}, err } resp.Host = host resp.Port = port resp.RemoteHost = remoteHost resp.HostType = hostType resp.ServerURL = requestAgentTunnelURL(serverURL) return resp, nil } remoteDirOut, err := sshRunRetry(client, 3, 300*time.Millisecond, func() (string, error) { return sshRun(client, `sh -lc ' for base in /tmp /var/tmp /data/local/tmp; do tmpdir="$base/klipperanywhere-install-$$" if mkdir -p "$tmpdir" 2>/dev/null; then printf "%s\n" "$tmpdir" exit 0 fi done exit 1 '`) }) if err != nil { return sshInstallResponse{}, fmt.Errorf("failed to create remote install directory: %w", err) } remoteDir := strings.TrimSpace(remoteDirOut) if remoteDir == "" { return sshInstallResponse{}, errors.New("remote install directory was empty") } if progress != nil { progress("prepare", fmt.Sprintf("Using remote staging directory %s.", remoteDir)) } defer func() { _, _ = sshRun(client, "rm -rf "+shellQuote(remoteDir)) }() spec, err := buildSpecForMachine(remoteArch) if err != nil { return sshInstallResponse{}, err } binary, binarySource, err := loadAgentBinary(ctx, releaseURL, spec) if err != nil { return sshInstallResponse{}, err } if progress != nil { progress("download", describeLoadedAgentBinary(binarySource, releaseURL)) } config := buildSSHInstallConfig(serverURL, printerID, s.agentToken, req) configPath := remoteDir + "/agent.json" binaryPath := remoteDir + "/klipperanywhere-agent" scriptDir := remoteDir + "/scripts" installPath := scriptDir + "/install-agent.sh" servicePath := remoteDir + "/packaging/klipperanywhere-agent.service" initdPath := remoteDir + "/packaging/klipperanywhere-agent.initd" if _, err := sshRun(client, "mkdir -p "+shellQuote(scriptDir)+" "+shellQuote(remoteDir+"/packaging")); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to prepare remote files: %w", err) } if progress != nil { progress("upload", "Uploading agent binary and installer files.") } if err := sshWriteFile(client, binaryPath, binary); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to upload agent binary: %w", err) } if progress != nil { progress("upload", "Uploaded agent binary.") } if err := sshWriteFile(client, installPath, mustReadFile("scripts/install-agent.sh")); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to upload installer script: %w", err) } if progress != nil { progress("upload", "Uploaded installer script.") } if err := sshWriteFile(client, servicePath, mustReadFile("packaging/klipperanywhere-agent.service")); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to upload service file: %w", err) } if progress != nil { progress("upload", "Uploaded service file.") } if err := sshWriteFile(client, initdPath, mustReadFile("packaging/klipperanywhere-agent.initd")); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to upload init script: %w", err) } if progress != nil { progress("upload", "Uploaded init script.") } if err := sshWriteFile(client, configPath, config); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to upload agent config: %w", err) } if progress != nil { progress("upload", "Uploaded agent config.") } if _, err := sshRun(client, "chmod 0755 "+shellQuote(binaryPath)+" "+shellQuote(installPath)); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to prepare remote scripts: %w", err) } if _, err := sshRun(client, "chmod 0644 "+shellQuote(servicePath)+" "+shellQuote(initdPath)); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to prepare remote packaging files: %w", err) } if _, err := sshRun(client, "chmod 0600 "+shellQuote(configPath)); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to secure remote config: %w", err) } if progress != nil { progress("install", "Prepared remote installer files.") } hadExistingInstall := remoteExistingInstall(client) competingInstallMessage, err := disableCompetingAgentInstall(client, installHostTypeStandard, rinkhalsAppRoot) if err != nil { return sshInstallResponse{}, err } if progress != nil && competingInstallMessage != "" { progress("install", competingInstallMessage) } if progress != nil { progress("install", "Running installer on remote host.") } command := strings.Join([]string{"sh", shellQuote(installPath), shellQuote(binaryPath), shellQuote(configPath)}, " ") output, err := sshRun(client, command) if err != nil { if strings.TrimSpace(output) != "" { return sshInstallResponse{}, fmt.Errorf("%w: %s", err, strings.TrimSpace(output)) } return sshInstallResponse{}, err } reconnectTimeout := 20 * time.Second if hostType == installHostTypeRinkhals { reconnectTimeout = 2 * time.Minute } connected, postInstallMessage, err := s.waitForPrinterConnection(ctx, printerID, reconnectTimeout) if err != nil { return sshInstallResponse{}, err } if progress != nil { if connected { progress("callback", "Agent connected back to the server.") } else { progress("callback", "Waiting for agent callback.") } } postInstallMessage = appendPostInstallNote(postInstallMessage, competingInstallMessage) rollbackPerformed := false rollbackMessage := "" if !connected && hadExistingInstall { if rollbackOutput, rollbackErr := rollbackPrinterInstall(client); rollbackErr != nil { return sshInstallResponse{}, fmt.Errorf("installed agent but rollback failed after reconnect timeout: %w", rollbackErr) } else { rollbackPerformed = true rollbackMessage = strings.TrimSpace(rollbackOutput) connected, postInstallMessage, err = s.waitForPrinterConnection(ctx, printerID, reconnectTimeout) if err != nil { return sshInstallResponse{}, err } if rollbackMessage == "" { rollbackMessage = "restored previous agent installation after reconnect timeout" } if connected { postInstallMessage = "Previous agent restored after the replacement failed to reconnect." } else { postInstallMessage = "Replacement agent did not reconnect; previous installation was restored." } } } resp = sshInstallResponse{ PrinterID: printerID, Host: host, Port: port, RemoteHost: remoteHost, HostType: hostType, Message: strings.TrimSpace(output), ReleaseURL: releaseURL, ServerURL: requestAgentTunnelURL(serverURL), BinarySource: binarySource, ConfigPath: configPath, BinaryPath: binaryPath, PostInstallConnected: connected, PostInstallMessage: postInstallMessage, RollbackPerformed: rollbackPerformed, RollbackMessage: rollbackMessage, } return resp, nil } func normalizeInstallHostType(value string) string { switch strings.ToLower(strings.TrimSpace(value)) { case "", installHostTypeStandard: return installHostTypeStandard case installHostTypeRinkhals: return installHostTypeRinkhals default: return installHostTypeStandard } } func buildSSHInstallConfig(serverURL string, printerID string, agentToken string, req sshInstallRequest) []byte { return buildSSHInstallConfigWithStateFile(serverURL, printerID, agentToken, req, "") } func buildSSHInstallConfigWithStateFile(serverURL string, printerID string, agentToken string, req sshInstallRequest, stateFile string) []byte { uiAutoDetect := true if req.UIAutoDetect != nil { uiAutoDetect = *req.UIAutoDetect } cfg := map[string]any{ "server_url": requestAgentTunnelURL(serverURL), "printer_id": printerID, "token": agentToken, "moonraker_url": strings.TrimSpace(req.MoonrakerURL), "ui_auto_detect": uiAutoDetect, } if cfg["moonraker_url"] == "" { cfg["moonraker_url"] = "http://127.0.0.1:7125" } if uiURL := strings.TrimSpace(req.UIURL); uiURL != "" { cfg["ui_url"] = uiURL } if stateFile = strings.TrimSpace(stateFile); stateFile != "" { cfg["state_file"] = stateFile } encoded, err := json.MarshalIndent(cfg, "", " ") if err != nil { return []byte("{}\n") } return append(encoded, '\n') } func (s *server) installPrinterAsRinkhalsApp(ctx context.Context, client *ssh.Client, printerID, serverURL string, req sshInstallRequest, remoteArch string, releaseURL string, progress func(stage, message string)) (sshInstallResponse, error) { appRoot := rinkhalsAppRoot appLogPath := filepath.Join(appRoot, "klipperanywhere-agent.log") stageRoot := filepath.Join(appRoot, "staging") hadExistingInstall := remoteExistingRinkhalsInstall(client, appRoot) if _, err := sshRun(client, "mkdir -p "+shellQuote(appRoot)+" "+shellQuote(filepath.Join(appRoot, "rollback"))); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to prepare rinkhals app directory: %w", err) } if progress != nil { progress("prepare", fmt.Sprintf("Preparing Rinkhals app directory at %s.", appRoot)) } spec, err := buildSpecForMachine(remoteArch) if err != nil { return sshInstallResponse{}, err } binary, binarySource, err := loadAgentBinary(ctx, releaseURL, spec) if err != nil { return sshInstallResponse{}, err } if progress != nil { progress("download", describeLoadedAgentBinary(binarySource, releaseURL)) } configPath := filepath.Join(appRoot, "agent.json") config := buildSSHInstallConfigWithStateFile(serverURL, printerID, s.agentToken, req, filepath.Join(appRoot, "agent-state.json")) binaryPath := filepath.Join(appRoot, "klipperanywhere-agent") appJSONPath := filepath.Join(appRoot, "app.json") appSHPath := filepath.Join(appRoot, "app.sh") enabledPath := filepath.Join(appRoot, ".enabled") rollbackDir := filepath.Join(appRoot, "rollback") stageConfigPath := filepath.Join(stageRoot, "agent.json") stageBinaryPath := filepath.Join(stageRoot, "klipperanywhere-agent") stageAppJSONPath := filepath.Join(stageRoot, "app.json") stageAppSHPath := filepath.Join(stageRoot, "app.sh") stageEnabledPath := filepath.Join(stageRoot, ".enabled") if hadExistingInstall { if _, err := sshRun(client, "sh "+shellQuote(appSHPath)+" stop >/dev/null 2>&1 || true"); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to stop existing rinkhals app before reinstall: %w", err) } if progress != nil { progress("install", "Stopped existing Rinkhals app before update.") } } if _, err := sshRun(client, "rm -rf "+shellQuote(stageRoot)+" && mkdir -p "+shellQuote(stageRoot)); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to prepare rinkhals staging directory: %w", err) } if progress != nil { progress("prepare", fmt.Sprintf("Using Rinkhals staging directory %s.", stageRoot)) } if hadExistingInstall { if _, err := sshRun(client, "mkdir -p "+shellQuote(rollbackDir)); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to prepare rinkhals rollback directory: %w", err) } if progress != nil { progress("prepare", "Backed up existing Rinkhals app files.") } for _, entry := range []struct { src string dst string }{ {binaryPath, filepath.Join(rollbackDir, "klipperanywhere-agent.bak")}, {configPath, filepath.Join(rollbackDir, "agent.json.bak")}, {appJSONPath, filepath.Join(rollbackDir, "app.json.bak")}, {appSHPath, filepath.Join(rollbackDir, "app.sh.bak")}, {enabledPath, filepath.Join(rollbackDir, ".enabled.bak")}, } { if _, statErr := sshRun(client, "sh -lc 'if [ -f "+entry.src+" ]; then cp "+entry.src+" "+entry.dst+"; fi'"); statErr != nil { return sshInstallResponse{}, fmt.Errorf("failed to back up %s: %w", entry.src, statErr) } } } if progress != nil { progress("upload", "Uploading Rinkhals app bundle.") } if err := sshWriteFile(client, stageBinaryPath, binary); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to upload agent binary: %w", err) } if progress != nil { progress("upload", "Uploaded Rinkhals agent binary.") } if err := sshWriteFile(client, stageAppJSONPath, mustReadFile("packaging/rinkhals/klipperanywhere-agent/app.json")); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to upload rinkhals app manifest: %w", err) } if progress != nil { progress("upload", "Uploaded Rinkhals app manifest.") } if err := sshWriteFile(client, stageAppSHPath, mustReadFile("packaging/rinkhals/klipperanywhere-agent/app.sh")); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to upload rinkhals app script: %w", err) } if progress != nil { progress("upload", "Uploaded Rinkhals app launcher.") } if err := sshWriteFile(client, stageConfigPath, config); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to upload agent config: %w", err) } if progress != nil { progress("upload", "Uploaded Rinkhals agent config.") } if _, err := sshRun(client, "chmod 0755 "+shellQuote(stageBinaryPath)+" "+shellQuote(stageAppSHPath)); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to prepare rinkhals scripts: %w", err) } if _, err := sshRun(client, "chmod 0644 "+shellQuote(stageAppJSONPath)+" "+shellQuote(stageConfigPath)); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to prepare rinkhals data files: %w", err) } if _, err := sshRun(client, "sh -lc 'touch "+stageEnabledPath+"'"); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to enable rinkhals app: %w", err) } if _, err := sshRun(client, "sh -lc 'cp -f "+shellQuote(stageBinaryPath)+" "+shellQuote(binaryPath)+" && cp -f "+shellQuote(stageAppJSONPath)+" "+shellQuote(appJSONPath)+" && cp -f "+shellQuote(stageAppSHPath)+" "+shellQuote(appSHPath)+" && cp -f "+shellQuote(stageConfigPath)+" "+shellQuote(configPath)+" && cp -f "+shellQuote(stageEnabledPath)+" "+shellQuote(enabledPath)+"'"); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to activate rinkhals app staging files: %w", err) } if progress != nil { progress("install", "Activated Rinkhals app files.") } if _, err := sshRun(client, "chmod 0755 "+shellQuote(binaryPath)+" "+shellQuote(appSHPath)); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to prepare rinkhals scripts: %w", err) } if _, err := sshRun(client, "chmod 0644 "+shellQuote(appJSONPath)+" "+shellQuote(configPath)); err != nil { return sshInstallResponse{}, fmt.Errorf("failed to prepare rinkhals data files: %w", err) } output, err := sshRun(client, "sh "+shellQuote(appSHPath)+" start") if err != nil { if strings.TrimSpace(output) != "" { return sshInstallResponse{}, fmt.Errorf("%w: %s", err, strings.TrimSpace(output)) } return sshInstallResponse{}, err } competingInstallMessage, err := disableCompetingAgentInstall(client, installHostTypeRinkhals, appRoot) if err != nil { return sshInstallResponse{}, err } if progress != nil && competingInstallMessage != "" { progress("install", competingInstallMessage) } connected, postInstallMessage, err := s.waitForPrinterConnection(ctx, printerID, 20*time.Second) if err != nil { return sshInstallResponse{}, err } if progress != nil { if connected { progress("callback", "Rinkhals app connected back to the server.") } else { progress("callback", "Waiting for Rinkhals app callback.") } } postInstallMessage = appendPostInstallNote(postInstallMessage, competingInstallMessage) rollbackPerformed := false rollbackMessage := "" if !connected && hadExistingInstall { if rollbackOutput, rollbackErr := rollbackRinkhalsInstall(client, appRoot); rollbackErr != nil { return sshInstallResponse{}, fmt.Errorf("installed rinkhals app but rollback failed after reconnect timeout: %w", rollbackErr) } else { rollbackPerformed = true rollbackMessage = strings.TrimSpace(rollbackOutput) connected, postInstallMessage, err = s.waitForPrinterConnection(ctx, printerID, 20*time.Second) if err != nil { return sshInstallResponse{}, err } if rollbackMessage == "" { rollbackMessage = "restored previous rinkhals app installation after reconnect timeout" } if connected { postInstallMessage = "Previous Rinkhals app restored after the replacement failed to reconnect." } else { postInstallMessage = "Replacement Rinkhals app did not reconnect; previous installation was restored." if logTail, tailErr := sshRun(client, "sh -lc 'tail -n 80 "+shellQuote(appLogPath)+" 2>/dev/null || true'"); tailErr == nil && strings.TrimSpace(logTail) != "" { postInstallMessage += "\n\nApp log:\n" + strings.TrimSpace(logTail) } } } } if !connected && !hadExistingInstall { if logTail, tailErr := sshRun(client, "sh -lc 'tail -n 80 "+shellQuote(appLogPath)+" 2>/dev/null || true'"); tailErr == nil && strings.TrimSpace(logTail) != "" { postInstallMessage += "\n\nApp log:\n" + strings.TrimSpace(logTail) } } return sshInstallResponse{ PrinterID: printerID, HostType: installHostTypeRinkhals, Message: strings.TrimSpace(output), ReleaseURL: releaseURL, ServerURL: requestAgentTunnelURL(serverURL), BinarySource: binarySource, ConfigPath: configPath, BinaryPath: binaryPath, PostInstallConnected: connected, PostInstallMessage: postInstallMessage, RollbackPerformed: rollbackPerformed, RollbackMessage: rollbackMessage, }, nil } func resolveInstallServerURL(origin string, raw string) (string, error) { serverURL := strings.TrimSpace(raw) if serverURL == "" { if originIsLoopback(origin) { return "", errors.New("server_url is required when the server is opened on localhost; enter the printer-reachable server URL") } serverURL = origin } parsed, err := url.Parse(serverURL) if err != nil { return "", fmt.Errorf("invalid server_url: %w", err) } if parsed.Scheme != "http" && parsed.Scheme != "https" { return "", errors.New("server_url must start with http:// or https://") } if parsed.Host == "" { return "", errors.New("server_url must include a host") } if isLoopbackHost(parsed.Hostname()) { return "", errors.New("server_url must be reachable from the printer host; use the LAN IP or hostname") } return strings.TrimRight(parsed.String(), "/"), nil } func requestAgentTunnelURL(origin string) string { origin = strings.TrimSpace(origin) origin = strings.TrimSuffix(origin, "/") if strings.HasPrefix(origin, "https://") { return "wss://" + strings.TrimPrefix(origin, "https://") + "/agent/tunnel" } if strings.HasPrefix(origin, "http://") { return "ws://" + strings.TrimPrefix(origin, "http://") + "/agent/tunnel" } return origin + "/agent/tunnel" } type agentBuildSpec struct { Asset string GOARCH string GOARM string GOMIPS string } func buildSpecForMachine(machine string) (agentBuildSpec, error) { switch strings.ToLower(strings.TrimSpace(machine)) { case "x86_64", "amd64": return agentBuildSpec{Asset: "klipperanywhere-agent-linux-amd64", GOARCH: "amd64"}, nil case "aarch64", "arm64": return agentBuildSpec{Asset: "klipperanywhere-agent-linux-arm64", GOARCH: "arm64"}, nil case "armv7l", "armv7", "armv7hf", "armv7hl": return agentBuildSpec{Asset: "klipperanywhere-agent-linux-armv7", GOARCH: "arm", GOARM: "7"}, nil case "mips64el", "mipsle", "mipsel", "mips": return agentBuildSpec{Asset: "klipperanywhere-agent-linux-mipsle", GOARCH: "mipsle", GOMIPS: "softfloat"}, nil default: return agentBuildSpec{}, fmt.Errorf("unsupported remote architecture: %s", machine) } } func releaseAssetForMachine(machine string) (string, error) { spec, err := buildSpecForMachine(machine) if err != nil { return "", err } return spec.Asset, nil } func loadAgentBinary(ctx context.Context, releaseURL string, spec agentBuildSpec) ([]byte, string, error) { if binary, err := buildAgentBinaryFromSource(ctx, spec); err == nil { return binary, "source", nil } if binary, err := loadBundledAgentBinary(spec); err == nil { return binary, "bundled", nil } binary, err := downloadReleaseAsset(ctx, releaseURL, spec.Asset) if err != nil { return nil, "", err } return binary, "release", nil } func loadBundledAgentBinary(spec agentBuildSpec) ([]byte, error) { if spec.GOARCH != runtime.GOARCH || spec.GOARM != "" || spec.GOMIPS != "" || runtime.GOOS != "linux" { return nil, fmt.Errorf("bundled agent binary is not compatible with target architecture") } return os.ReadFile("/usr/local/bin/klipperanywhere-agent") } func describeLoadedAgentBinary(source string, releaseURL string) string { switch strings.TrimSpace(source) { case "source": return "Built agent binary from the server container source." case "bundled": return "Loaded bundled agent binary from the server container." case "release": return fmt.Sprintf("Downloaded release agent binary from %s.", strings.TrimSpace(releaseURL)) default: return fmt.Sprintf("Loaded %s agent binary.", strings.TrimSpace(source)) } } func buildAgentBinaryFromSource(ctx context.Context, spec agentBuildSpec) ([]byte, error) { goPath, err := exec.LookPath("go") if err != nil { return nil, err } tmpDir, err := os.MkdirTemp("", "klipperanywhere-agent-build-*") if err != nil { return nil, err } defer os.RemoveAll(tmpDir) outputPath := filepath.Join(tmpDir, "klipperanywhere-agent") cmd := exec.CommandContext(ctx, goPath, "build", "-trimpath", "-ldflags", "-X main.agentVersion="+serverVersion, "-o", outputPath, "./cmd/agent") cmd.Env = append(os.Environ(), "CGO_ENABLED=0", "GOOS=linux", "GOARCH="+spec.GOARCH, ) if spec.GOARM != "" { cmd.Env = append(cmd.Env, "GOARM="+spec.GOARM) } if spec.GOMIPS != "" { cmd.Env = append(cmd.Env, "GOMIPS="+spec.GOMIPS) } out, err := cmd.CombinedOutput() if err != nil { if len(out) > 0 { return nil, fmt.Errorf("%w: %s", err, strings.TrimSpace(string(out))) } return nil, err } return os.ReadFile(outputPath) } func downloadReleaseAsset(ctx context.Context, baseURL string, asset string) ([]byte, error) { baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/") url := baseURL + "/" + asset req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, err } client := &http.Client{Timeout: 2 * time.Minute} resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode > 299 { snippet, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) if len(snippet) > 0 { return nil, fmt.Errorf("download failed: %s: %s", resp.Status, strings.TrimSpace(string(snippet))) } return nil, fmt.Errorf("download failed: %s", resp.Status) } body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } return body, nil } func remoteExistingInstall(client *ssh.Client) bool { output, err := sshRun(client, `sh -lc 'if [ -f /usr/local/bin/klipperanywhere-agent ] || [ -f /etc/klipperanywhere/agent.json ]; then echo yes; fi'`) return err == nil && strings.TrimSpace(output) != "" } func remoteExistingRinkhalsInstall(client *ssh.Client, appRoot string) bool { output, err := sshRun(client, `sh -lc 'if [ -f `+filepath.Join(appRoot, "klipperanywhere-agent")+` ] || [ -f `+filepath.Join(appRoot, "agent.json")+` ]; then echo yes; fi'`) return err == nil && strings.TrimSpace(output) != "" } func disableCompetingAgentInstall(client *ssh.Client, activeHostType string, appRoot string) (string, error) { switch normalizeInstallHostType(activeHostType) { case installHostTypeRinkhals: return disableLegacyAgentInstall(client) default: return disableRinkhalsAgentInstall(client, appRoot) } } func disableLegacyAgentInstall(client *ssh.Client) (string, error) { command := `sh -lc ' set +e changed=0 if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then systemctl stop klipperanywhere-agent >/dev/null 2>&1 && changed=1 systemctl disable klipperanywhere-agent >/dev/null 2>&1 && changed=1 rm -f /etc/systemd/system/klipperanywhere-agent.service systemctl daemon-reload >/dev/null 2>&1 fi if command -v rc-service >/dev/null 2>&1; then rc-service klipperanywhere-agent stop >/dev/null 2>&1 && changed=1 fi if command -v rc-update >/dev/null 2>&1; then rc-update del klipperanywhere-agent default >/dev/null 2>&1 && changed=1 fi if [ -x /etc/init.d/klipperanywhere-agent ]; then /etc/init.d/klipperanywhere-agent stop >/dev/null 2>&1 && changed=1 fi if command -v update-rc.d >/dev/null 2>&1; then update-rc.d -f klipperanywhere-agent remove >/dev/null 2>&1 && changed=1 fi if command -v chkconfig >/dev/null 2>&1; then chkconfig --del klipperanywhere-agent >/dev/null 2>&1 && changed=1 fi rm -f /etc/rcS.d/S99klipperanywhere-agent /etc/rc.d/S99klipperanywhere-agent 2>/dev/null if [ "$changed" -eq 1 ]; then echo "Disabled legacy klipperanywhere-agent service to prevent duplicate connections." fi exit 0 '` output, err := sshRun(client, command) if err != nil { return "", fmt.Errorf("failed to disable legacy agent service: %w", err) } return strings.TrimSpace(output), nil } func disableRinkhalsAgentInstall(client *ssh.Client, appRoot string) (string, error) { appSH := filepath.Join(appRoot, "app.sh") enabledPath := filepath.Join(appRoot, ".enabled") command := "sh -lc " + shellQuote(` set +e changed=0 if [ -x `+shellQuote(appSH)+` ]; then sh `+shellQuote(appSH)+` stop >/dev/null 2>&1 && changed=1 fi if [ -f `+shellQuote(enabledPath)+` ]; then rm -f `+shellQuote(enabledPath)+` changed=1 fi if [ "$changed" -eq 1 ]; then echo "Disabled Rinkhals klipperanywhere-agent app to prevent duplicate connections." fi exit 0 `) output, err := sshRun(client, command) if err != nil { return "", fmt.Errorf("failed to disable rinkhals agent app: %w", err) } return strings.TrimSpace(output), nil } func appendPostInstallNote(message string, note string) string { message = strings.TrimSpace(message) note = strings.TrimSpace(note) if note == "" { return message } if message == "" { return note } return message + " " + note } func rollbackPrinterInstall(client *ssh.Client) (string, error) { command := `sh -lc ' set -eu ROLLBACK_DIR=/var/lib/klipperanywhere/rollback if [ ! -d "$ROLLBACK_DIR" ]; then echo "no rollback backup available" exit 1 fi if [ -f "$ROLLBACK_DIR/klipperanywhere-agent.bak" ]; then install -m 0755 "$ROLLBACK_DIR/klipperanywhere-agent.bak" /usr/local/bin/klipperanywhere-agent fi if [ -f "$ROLLBACK_DIR/agent.json.bak" ]; then install -m 0600 "$ROLLBACK_DIR/agent.json.bak" /etc/klipperanywhere/agent.json fi if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then systemctl restart klipperanywhere-agent systemctl status klipperanywhere-agent --no-pager || true exit 0 fi if command -v rc-service >/dev/null 2>&1; then rc-service klipperanywhere-agent restart 2>/dev/null || rc-service klipperanywhere-agent start rc-service klipperanywhere-agent status || true exit 0 fi if [ -x /etc/init.d/klipperanywhere-agent ]; then /etc/init.d/klipperanywhere-agent restart /etc/init.d/klipperanywhere-agent status || true exit 0 fi echo "restored previous agent files" '` return sshRun(client, command) } func rollbackRinkhalsInstall(client *ssh.Client, appRoot string) (string, error) { rollbackDir := filepath.Join(appRoot, "rollback") if _, err := sshRun(client, "test -d "+shellQuote(rollbackDir)); err != nil { return "", err } for _, entry := range []struct { src string dst string }{ {filepath.Join(rollbackDir, "klipperanywhere-agent.bak"), filepath.Join(appRoot, "klipperanywhere-agent")}, {filepath.Join(rollbackDir, "agent.json.bak"), filepath.Join(appRoot, "agent.json")}, {filepath.Join(rollbackDir, "app.json.bak"), filepath.Join(appRoot, "app.json")}, {filepath.Join(rollbackDir, "app.sh.bak"), filepath.Join(appRoot, "app.sh")}, {filepath.Join(rollbackDir, ".enabled.bak"), filepath.Join(appRoot, ".enabled")}, } { if _, err := sshRun(client, "sh -lc 'if [ -f "+shellQuote(entry.src)+" ]; then cp "+shellQuote(entry.src)+" "+shellQuote(entry.dst)+"; fi'"); err != nil { return "", err } } if _, err := sshRun(client, "chmod 0755 "+shellQuote(filepath.Join(appRoot, "klipperanywhere-agent"))+" "+shellQuote(filepath.Join(appRoot, "app.sh"))+" 2>/dev/null || true"); err != nil { return "", err } if _, err := sshRun(client, "chmod 0644 "+shellQuote(filepath.Join(appRoot, "agent.json"))+" "+shellQuote(filepath.Join(appRoot, "app.json"))+" 2>/dev/null || true"); err != nil { return "", err } return sshRun(client, "sh "+shellQuote(filepath.Join(appRoot, "app.sh"))+" start") } func dialSSH(host string, port int, username string, password string) (*ssh.Client, error) { addr := net.JoinHostPort(host, fmt.Sprintf("%d", port)) conn, err := net.DialTimeout("tcp", addr, 15*time.Second) if err != nil { return nil, err } cfg := &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ssh.Password(password)}, HostKeyCallback: ssh.InsecureIgnoreHostKey(), Timeout: 15 * time.Second, } cc, chans, reqs, err := ssh.NewClientConn(conn, addr, cfg) if err != nil { _ = conn.Close() return nil, err } return ssh.NewClient(cc, chans, reqs), nil } func sshRun(client *ssh.Client, command string) (string, error) { session, err := client.NewSession() if err != nil { return "", err } defer session.Close() var out bytes.Buffer session.Stdout = &out session.Stderr = &out err = session.Run(command) return out.String(), err } func sshRunRetry(client *ssh.Client, attempts int, delay time.Duration, run func() (string, error)) (string, error) { if attempts < 1 { attempts = 1 } var lastOut string var lastErr error for i := 0; i < attempts; i++ { out, err := run() lastOut = out if err == nil && strings.TrimSpace(out) != "" { return out, nil } lastErr = err if i < attempts-1 { time.Sleep(delay) } } if lastErr != nil { return lastOut, lastErr } return lastOut, errors.New("empty response") } func sshWriteFile(client *ssh.Client, path string, contents []byte) error { session, err := client.NewSession() if err != nil { return err } defer session.Close() session.Stdin = bytes.NewReader(contents) command := "sh -c 'cat > \"$1\"' sh " + shellQuote(path) return session.Run(command) } func sanitizePrinterID(value string) string { value = strings.TrimSpace(value) if value == "" { return "" } cleaned := printerIDCleaner.ReplaceAllString(value, "-") cleaned = strings.Trim(cleaned, "-") return cleaned } var printerIDCleaner = regexp.MustCompile(`[^A-Za-z0-9._-]+`) func shellQuote(value string) string { if value == "" { return "''" } return "'" + strings.ReplaceAll(value, "'", `'"'"'`) + "'" } func mustReadFile(path string) []byte { data, err := os.ReadFile(path) if err != nil { panic(err) } return data } func firstNonEmpty(values ...string) string { for _, value := range values { if strings.TrimSpace(value) != "" { return value } } return "" } func originIsLoopback(origin string) bool { origin = strings.ToLower(strings.TrimSpace(origin)) return strings.Contains(origin, "://127.0.0.1") || strings.Contains(origin, "://localhost") || strings.Contains(origin, "://[::1]") } func isLoopbackHost(host string) bool { host = strings.ToLower(strings.TrimSpace(host)) if host == "localhost" { return true } ip := net.ParseIP(host) return ip != nil && ip.IsLoopback() } func (s *server) printerConnected(printerID string) bool { s.tunnelsMu.RLock() _, ok := s.tunnels[printerID] s.tunnelsMu.RUnlock() return ok } func (s *server) waitForPrinterConnection(ctx context.Context, printerID string, timeout time.Duration) (bool, string, error) { waitCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() ticker := time.NewTicker(500 * time.Millisecond) defer ticker.Stop() for { if s.printerConnected(printerID) { return true, "Agent appeared in /api/printers.", nil } select { case <-waitCtx.Done(): return false, "Installed, but the agent has not appeared in /api/printers yet.", nil case <-ticker.C: } } }