package main import ( "archive/tar" "context" "encoding/json" "errors" "fmt" "io" "net/http" "os" "path/filepath" "strings" "time" ) const ( transferImportOwnerKey = "__transferImportId" transferBackupsDir = ".adpanel_backups" transferMetadataDir = ".adpanel_meta" transferExportHoldTTL = 45 * time.Minute ) var errUnownedTransferImport = errors.New("no matching transfer import") var errTransferExportInProgress = errors.New("server files are read-only during transfer") type transferExportHold struct { ID string `json:"id"` ExpiresAt time.Time `json:"expiresAt"` } func (a *Agent) transferExportHoldPath(name string) string { return a.metaPath(name) + ".export-hold" } func (a *Agent) readTransferExportHold(name string) (transferExportHold, error) { var hold transferExportHold data, err := os.ReadFile(a.transferExportHoldPath(name)) if errors.Is(err, os.ErrNotExist) { return hold, nil } if err != nil { return hold, err } if err := json.Unmarshal(data, &hold); err != nil || !validReinstallOperationID(hold.ID) || hold.ExpiresAt.IsZero() { return transferExportHold{}, errors.New("invalid source transfer hold") } return hold, nil } func (hold transferExportHold) active() bool { return hold.ID != "" && time.Now().Before(hold.ExpiresAt) } func (a *Agent) checkTransferSourceWritable(name string) error { hold, err := a.readTransferExportHold(name) if err != nil { return err } if hold.active() { return errTransferExportInProgress } return nil } // adpanel:transfer-source-hold - source writes after the snapshot cannot be acknowledged and then discarded at commit. func (a *Agent) reserveTransferExport(ctx context.Context, name, serverDir, transferID string) (int, error) { unlock, err := a.acquireUploadScope(ctx, serverDir) if err != nil { return http.StatusRequestTimeout, err } defer unlock() if err := a.checkTransferSourceWritable(name); err != nil { status, _ := fileMutationAdmissionFailure(err) return status, err } inspectCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() container, _, exists, err := a.inspectContainerForStats(inspectCtx, name) if err != nil { return http.StatusServiceUnavailable, errors.New("could not verify source container state") } if exists && (container.State.Running || (container.State.Status != "exited" && container.State.Status != "created" && container.State.Status != "dead")) { return http.StatusConflict, errors.New("source container is not confirmed stopped") } data, err := json.Marshal(transferExportHold{ID: transferID, ExpiresAt: time.Now().Add(transferExportHoldTTL)}) if err != nil { return http.StatusInternalServerError, err } if err := writeServerMetadata(a.transferExportHoldPath(name), data); err != nil { return http.StatusInternalServerError, err } return http.StatusOK, nil } func (a *Agent) handleFinishTransferExport(w http.ResponseWriter, r *http.Request, name string) { transferID := r.URL.Query().Get("transferId") if !validReinstallOperationID(transferID) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid transfer ID"}) return } opMu := a.tryLockServerOp(name) if opMu == nil { a.writeServerOpConflictResponse(w, name) return } defer opMu.Unlock() unlock, err := a.acquireUploadScope(r.Context(), a.serverDir(name)) if err != nil { jsonWrite(w, http.StatusRequestTimeout, uploadScopeRequestEnded()) return } defer unlock() hold, err := a.readTransferExportHold(name) if err != nil { jsonWrite(w, 500, map[string]any{"ok": false, "error": "could not verify source transfer hold"}) return } cleanup := r.URL.Query().Get("cleanup") == "true" if cleanup { if hold.ID != "" && (hold.ID != transferID || !hold.active()) { jsonWrite(w, http.StatusConflict, map[string]any{"ok": false, "error": "source transfer hold does not match or has expired"}) return } if hold.ID == transferID { if _, err := a.deleteServerLocked(name, false, getClientIP(r)); err != nil { a.logf("[transfer] source cleanup failed for %q: %v", name, err) jsonWrite(w, 500, map[string]any{"ok": false, "error": "source cleanup failed"}) return } } if status, err := a.checkTransferDestinationVacant(r.Context(), name); err != nil { jsonWrite(w, status, map[string]any{"ok": false, "error": "could not confirm the source copy is gone"}) return } } if hold.ID == transferID { if err := os.Remove(a.transferExportHoldPath(name)); err != nil && !errors.Is(err, os.ErrNotExist) { jsonWrite(w, 500, map[string]any{"ok": false, "error": "could not release source transfer hold"}) return } } jsonWrite(w, 200, map[string]any{"ok": true, "transferId": transferID}) } func (a *Agent) serverStoragePaths(name string) (volumes, backups []string) { volumes = []string{filepath.Join(a.volumesDir, name)} backups = []string{filepath.Join(a.backupsDir(), name)} for _, disk := range a.registeredDisks() { volumes = append(volumes, filepath.Join(a.diskLayoutVolumes(disk.MountPath), name)) backups = append(backups, filepath.Join(a.diskLayoutBackups(disk.MountPath), name)) } return volumes, backups } func anyServerStoragePathExists(paths []string) (bool, error) { for _, path := range paths { if _, err := os.Lstat(path); err == nil { return true, nil } else if !errors.Is(err, os.ErrNotExist) { return false, err } } return false, nil } // adpanel:transfer-import-no-clobber - the panel index cannot prove node storage is vacant. func (a *Agent) checkTransferDestinationVacant(ctx context.Context, name string) (int, error) { volumes, backups := a.serverStoragePaths(name) if exists, err := anyServerStoragePathExists(append(append(volumes, backups...), a.metaPath(name))); err != nil { return http.StatusServiceUnavailable, errors.New("could not verify destination storage") } else if exists { return http.StatusConflict, errors.New("destination already contains server data") } inspectCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() _, _, exists, err := a.inspectContainerForStats(inspectCtx, name) if err != nil { return http.StatusServiceUnavailable, errors.New("could not verify destination container state") } if exists { return http.StatusConflict, errors.New("destination already contains a server container") } return http.StatusOK, nil } func stampTransferImportMetadata(meta map[string]any, disk NodeDisk, transferID string) { delete(meta, "__diskId") delete(meta, transferImportOwnerKey) if !(disk.Primary || disk.ID == primaryDiskID) { meta["__diskId"] = disk.ID } if transferID != "" { meta[transferImportOwnerKey] = transferID } } func (a *Agent) reserveTransferImport(serverDir string, disk NodeDisk, transferID string) error { meta := make(map[string]any) stampTransferImportMetadata(meta, disk, transferID) return a.saveMeta(serverDir, meta) } func (a *Agent) requireTransferImportOwner(name, transferID string) error { root, err := safeOpenRoot(a.metaDir()) if errors.Is(err, os.ErrNotExist) { return errUnownedTransferImport } if err != nil { return err } defer root.Close() file, info, err := safeOpenRegularAt(root, filepath.Base(a.metaPath(name)), os.O_RDONLY|openNoFollow, 0) if errors.Is(err, os.ErrNotExist) { return errUnownedTransferImport } if err != nil { return err } defer file.Close() if info.Size() > maxLegacyServerMetaBytes { return errors.New("transfer metadata is too large") } data, err := io.ReadAll(io.LimitReader(file, maxLegacyServerMetaBytes+1)) if err != nil { return err } var meta map[string]any if len(data) > maxLegacyServerMetaBytes || json.Unmarshal(data, &meta) != nil { return errors.New("invalid transfer metadata") } if owner, _ := meta[transferImportOwnerKey].(string); owner != transferID { return errUnownedTransferImport } return nil } func (a *Agent) handleDeleteTransferImport(w http.ResponseWriter, r *http.Request, name string) { transferID := r.URL.Query().Get("transferId") if !validReinstallOperationID(transferID) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid transfer ID"}) return } _, err := a.deleteTransferImport(name, getClientIP(r), transferID) switch { case errors.Is(err, errUnownedTransferImport): jsonWrite(w, 404, map[string]any{"ok": false, "error": errUnownedTransferImport.Error()}) case errors.Is(err, errServerOpInProgress): a.writeServerOpConflictResponse(w, name) case err != nil: a.logf("[transfer] destination cleanup failed for %q: %v", name, err) jsonWrite(w, 500, map[string]any{"ok": false, "error": "destination cleanup failed"}) default: jsonWrite(w, 200, map[string]any{"ok": true}) } } func (a *Agent) deleteTransferImport(name, clientIP, transferID string) (deleteServerResult, error) { opMu := a.tryLockServerOp(name) if opMu == nil { return deleteServerResult{}, errServerOpInProgress } defer opMu.Unlock() if err := a.requireTransferImportOwner(name, transferID); err != nil { return deleteServerResult{}, err } return a.deleteServerLocked(name, false, clientIP) } func (a *Agent) handleExportServer(w http.ResponseWriter, r *http.Request, name string) { transferID := r.URL.Query().Get("transferId") if transferID != "" && !validReinstallOperationID(transferID) { jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid transfer ID"}) return } // adpanel:reinstall-export-lock - a snapshot must not race a rebuild, // even if the panel restarted and lost the request owning its claim. opMu := a.tryLockServerOp(name) if opMu == nil { a.writeServerOpConflictResponse(w, name) return } defer opMu.Unlock() serverDir := a.serverDir(name) if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { jsonWrite(w, 404, map[string]any{"error": "server not found"}) return } // adpanel:transfer-export-namespace - the importer routes these names outside the server directory. for _, reserved := range []string{transferBackupsDir, transferMetadataDir} { if _, err := os.Lstat(filepath.Join(serverDir, reserved)); err == nil { jsonWrite(w, http.StatusConflict, map[string]any{"error": fmt.Sprintf("Rename the server's top-level %q entry before transferring.", reserved)}) return } else if !errors.Is(err, os.ErrNotExist) { jsonWrite(w, http.StatusInternalServerError, map[string]any{"error": "could not verify server archive paths"}) return } } if transferID != "" { w.Header().Set("Cache-Control", "no-store") if status, err := a.reserveTransferExport(r.Context(), name, serverDir, transferID); err != nil { a.logf("[transfer] source export refused for %q: %v", name, err) detail := "could not protect source files for transfer" if status == http.StatusConflict { detail = err.Error() } jsonWrite(w, status, map[string]any{"ok": false, "error": detail}) return } w.Header().Set("X-ADPanel-Transfer-Id", transferID) } rc := http.NewResponseController(w) _ = rc.SetWriteDeadline(time.Time{}) backupsDir := a.serverBackupsDir(name) sizeBytes, _ := getDirSizeBytes(serverDir) if st, err := os.Stat(backupsDir); err == nil && st.IsDir() { if bsz, err := getDirSizeBytes(backupsDir); err == nil { sizeBytes += bsz } } if sizeBytes > 0 { w.Header().Set("X-ADPanel-Server-Bytes", fmt.Sprint(sizeBytes)) } w.Header().Set("Content-Type", "application/x-tar") w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s.tar", name)) // adpanel:export-toctou - the walk observes names only; content is // opened relative to a pinned root with no-follow and regular-file gates. serverRoot, rootErr := safeOpenRoot(serverDir) if rootErr != nil { jsonWrite(w, 500, map[string]any{"error": "failed to walk directory"}) return } defer serverRoot.Close() tw := tar.NewWriter(w) // adpanel:transfer-export-integrity - never finish a tar or a successful HTTP body after a source read fails. abortExport := func(err error) { a.logf("[export] incomplete archive for %q: %v", name, err) panic(http.ErrAbortHandler) } err := filepath.Walk(serverDir, func(p string, info os.FileInfo, err error) error { if err != nil { return err } rel, relErr := filepath.Rel(serverDir, p) if relErr != nil { return relErr } if rel == "." { return nil } if rel == transferBackupsDir || rel == transferMetadataDir { return fmt.Errorf("reserved transfer archive path: %s", rel) } if info.Mode()&(os.ModeSymlink|os.ModeSocket) != 0 { return nil } if !info.Mode().IsRegular() { hdr, hdrErr := tar.FileInfoHeader(info, "") if hdrErr != nil { return hdrErr } hdr.Name = filepath.ToSlash(rel) if info.IsDir() && !strings.HasSuffix(hdr.Name, "/") { hdr.Name += "/" } if err := tw.WriteHeader(hdr); err != nil { return err } return nil } f, fStat, openErr := safeOpenRegularAt(serverRoot, rel, os.O_RDONLY|openNoFollow, 0) if openErr != nil { return openErr } defer f.Close() hdr, hdrErr := tar.FileInfoHeader(fStat, "") if hdrErr != nil { return hdrErr } hdr.Name = filepath.ToSlash(rel) if err := tw.WriteHeader(hdr); err != nil { return err } // adpanel:tar-body-size-race - bound bytes to the opened file's size // so concurrent growth cannot overflow the tar entry. _, copyErr := io.CopyN(tw, f, fStat.Size()) return copyErr }) if err != nil { abortExport(err) } if st, err := os.Stat(backupsDir); err != nil && !os.IsNotExist(err) { abortExport(err) } else if err == nil && st.IsDir() { // adpanel:export-toctou - backups use the same pinned-root reads. backupsRoot, backupsRootErr := safeOpenRoot(backupsDir) if backupsRootErr != nil { abortExport(backupsRootErr) } defer backupsRoot.Close() err := filepath.Walk(backupsDir, func(p string, info os.FileInfo, err error) error { if err != nil { return err } rel, relErr := filepath.Rel(backupsDir, p) if relErr != nil { return relErr } if rel == "." || info.Mode()&(os.ModeSymlink|os.ModeSocket) != 0 { return nil } if !info.Mode().IsRegular() { hdr, hdrErr := tar.FileInfoHeader(info, "") if hdrErr != nil { return hdrErr } hdr.Name = transferBackupsDir + "/" + filepath.ToSlash(rel) if info.IsDir() && !strings.HasSuffix(hdr.Name, "/") { hdr.Name += "/" } return tw.WriteHeader(hdr) } f, fStat, openErr := safeOpenRegularAt(backupsRoot, rel, os.O_RDONLY|openNoFollow, 0) if openErr != nil { return openErr } defer f.Close() hdr, hdrErr := tar.FileInfoHeader(fStat, "") if hdrErr != nil { return hdrErr } hdr.Name = transferBackupsDir + "/" + filepath.ToSlash(rel) if err := tw.WriteHeader(hdr); err != nil { return err } // adpanel:tar-body-size-race - use the same opened-file size as the tar header. _, copyErr := io.CopyN(tw, f, fStat.Size()) return copyErr }) if err != nil { abortExport(err) } } metaPath := a.metaPath(name) if metaRoot, rootErr := safeOpenRoot(filepath.Dir(metaPath)); rootErr == nil { defer metaRoot.Close() f, metaInfo, openErr := safeOpenRegularAt(metaRoot, filepath.Base(metaPath), os.O_RDONLY|openNoFollow, 0) if openErr == nil { defer f.Close() hdr, hdrErr := tar.FileInfoHeader(metaInfo, "") if hdrErr != nil { abortExport(hdrErr) } hdr.Name = transferMetadataDir + "/" + sanitizeName(name) + ".json" if err := tw.WriteHeader(hdr); err != nil { abortExport(err) } if _, err := io.CopyN(tw, f, metaInfo.Size()); err != nil { abortExport(err) } } else if !os.IsNotExist(openErr) { abortExport(openErr) } } else if !os.IsNotExist(rootErr) { abortExport(rootErr) } if err := tw.Close(); err != nil { abortExport(err) } }