Commit f635b2346d

f635b2346d3ce1b5ce6da2a4085ba6d450ab3d7a

parent: ca10f3dcff

Unsigned

Wraient <wraient.911@gmail.com> · 2026-07-22 20:35 UTC

Fix: handle cross-device update install (copy when rename fails)

os.Rename fails with EXDEV when the download is in /tmp and the binary
lives on another filesystem. Prefer same-dir download temp, then fall
back to copy-into-place, busy-binary swap, and sudo when needed.

Layout: unified · split

internal/curd.go +9 −10
@@ -447,10 +447,11 @@ func UpdateCurd(repo, fileName string) error {
447 // GitHub release URL for curd 447 // GitHub release URL for curd
448 url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, binaryName) 448 url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, binaryName)
449 449
450 // Temporary path for the downloaded curd executable (prefer same dir when writable) 450 // Prefer a temp file next to the executable (same filesystem → atomic rename).
451 tmpPath := executablePath + ".tmp" 451 // Fall back to OS temp dir when the install dir is not writable (e.g. /usr/bin).
452 if tmpDir := os.TempDir(); tmpDir != "" { 452 tmpPath, out, err := createUpdateTempFile(executablePath, binaryName)
453 tmpPath = filepath.Join(tmpDir, "curd-update-"+binaryName) 453 if err != nil {
454 return fmt.Errorf("failed to create temporary file: %v", err)
454 } 455 }
455 456
456 // Download the curd executable 457 // Download the curd executable
@@ -460,21 +461,19 @@ func UpdateCurd(repo, fileName string) error {
460 } 461 }
461 resp, err := client.Get(url) 462 resp, err := client.Get(url)
462 if err != nil { 463 if err != nil {
464 out.Close()
465 _ = os.Remove(tmpPath)
463 return fmt.Errorf("failed to download file: %v", err) 466 return fmt.Errorf("failed to download file: %v", err)
464 } 467 }
465 defer resp.Body.Close() 468 defer resp.Body.Close()
466 469
467 // Check if the download was successful 470 // Check if the download was successful
468 if resp.StatusCode != http.StatusOK { 471 if resp.StatusCode != http.StatusOK {
472 out.Close()
473 _ = os.Remove(tmpPath)
469 return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode) 474 return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
470 } 475 }
471 476
472 // Create a new temporary file
473 out, err := os.Create(tmpPath)
474 if err != nil {
475 return fmt.Errorf("failed to create temporary file: %v", err)
476 }
477
478 // Copy the downloaded content to the temporary file 477 // Copy the downloaded content to the temporary file
479 if _, err := io.Copy(out, resp.Body); err != nil { 478 if _, err := io.Copy(out, resp.Body); err != nil {
480 out.Close() 479 out.Close()
internal/update.go +124 −17
@@ -425,6 +425,23 @@ func isPermissionError(err error) bool {
425 strings.Contains(msg, "operation not permitted") 425 strings.Contains(msg, "operation not permitted")
426} 426}
427 427
428// isCrossDeviceError reports rename/link failures when src and dest are on
429// different filesystems (e.g. /tmp tmpfs → ~/.local/bin on disk).
430func isCrossDeviceError(err error) bool {
431 if err == nil {
432 return false
433 }
434 var linkErr *os.LinkError
435 if errors.As(err, &linkErr) {
436 err = linkErr.Err
437 }
438 msg := strings.ToLower(err.Error())
439 return strings.Contains(msg, "cross-device") ||
440 strings.Contains(msg, "cross device") ||
441 strings.Contains(msg, "exdev") ||
442 strings.Contains(msg, "invalid cross-device link")
443}
444
428func promptSudoPassword(prompt string) (string, error) { 445func promptSudoPassword(prompt string) (string, error) {
429 if prompt == "" { 446 if prompt == "" {
430 prompt = "Sudo password: " 447 prompt = "Sudo password: "
@@ -469,31 +486,121 @@ func installExecutableWithSudo(src, dest string) error {
469 return nil 486 return nil
470} 487}
471 488
472func replaceExecutable(tmpPath, executablePath string) error { 489// createUpdateTempFile prefers a sibling of the executable (same FS as install
473 if runtime.GOOS == "windows" { 490// path). Falls back to os.TempDir when the install directory is not writable.
474 oldPath := executablePath + ".old" 491func createUpdateTempFile(executablePath, binaryName string) (string, *os.File, error) {
475 if err := os.Rename(executablePath, oldPath); err != nil { 492 dir := filepath.Dir(executablePath)
476 return fmt.Errorf("failed to rename old executable: %w", err) 493 // Try same directory first for atomic rename.
494 if f, err := os.CreateTemp(dir, ".curd-download-*"); err == nil {
495 return f.Name(), f, nil
496 }
497 // Fall back to system temp (may be cross-device; replaceExecutable handles that).
498 name := "curd-update-" + binaryName
499 if binaryName == "" {
500 name = "curd-update-bin"
501 }
502 path := filepath.Join(os.TempDir(), name)
503 f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
504 if err != nil {
505 return "", nil, err
506 }
507 return path, f, nil
508}
509
510func copyFileReplace(src, dst string) error {
511 in, err := os.Open(src)
512 if err != nil {
513 return err
514 }
515 defer in.Close()
516
517 // Write to a sibling temp on the destination filesystem, then rename into place.
518 dir := filepath.Dir(dst)
519 tmp, err := os.CreateTemp(dir, ".curd-update-*")
520 if err != nil {
521 return err
522 }
523 tmpName := tmp.Name()
524 cleanup := true
525 defer func() {
526 if cleanup {
527 _ = os.Remove(tmpName)
477 } 528 }
478 if err := os.Rename(tmpPath, executablePath); err != nil { 529 }()
479 _ = os.Rename(oldPath, executablePath) 530
480 return fmt.Errorf("failed to rename new executable: %w", err) 531 if err := tmp.Chmod(0755); err != nil {
532 _ = tmp.Close()
533 return err
534 }
535 if _, err := io.Copy(tmp, in); err != nil {
536 _ = tmp.Close()
537 return err
538 }
539 if err := tmp.Sync(); err != nil {
540 _ = tmp.Close()
541 return err
542 }
543 if err := tmp.Close(); err != nil {
544 return err
545 }
546
547 // Atomic replace when possible (same directory = same filesystem).
548 if err := os.Rename(tmpName, dst); err != nil {
549 // Windows / busy binary: move dest aside first.
550 oldPath := dst + ".old"
551 _ = os.Remove(oldPath)
552 if renOld := os.Rename(dst, oldPath); renOld != nil && !os.IsNotExist(renOld) {
553 return renOld
554 }
555 if renNew := os.Rename(tmpName, dst); renNew != nil {
556 _ = os.Rename(oldPath, dst)
557 return renNew
481 } 558 }
482 _ = os.Remove(oldPath) 559 _ = os.Remove(oldPath)
483 return nil
484 } 560 }
561 cleanup = false
562 return nil
563}
485 564
565// replaceExecutable installs the downloaded binary over the running executable.
566// Handles: same-FS rename, cross-device copy, busy binary swap, and sudo when needed.
567func replaceExecutable(tmpPath, executablePath string) error {
568 // 1) Fast path: rename when both paths share a filesystem.
486 if err := os.Rename(tmpPath, executablePath); err == nil { 569 if err := os.Rename(tmpPath, executablePath); err == nil {
487 return nil 570 return nil
488 } else if !isPermissionError(err) { 571 } else if isPermissionError(err) {
489 return fmt.Errorf("failed to replace executable: %w", err) 572 updateUserMessage(GetGlobalConfig(), "Update needs elevated permissions to replace the installed binary.")
573 if sudoErr := installExecutableWithSudo(tmpPath, executablePath); sudoErr != nil {
574 return sudoErr
575 }
576 _ = os.Remove(tmpPath)
577 return nil
578 } else if !isCrossDeviceError(err) {
579 // Unexpected rename failure — still try copy-into-place before giving up.
580 Log(fmt.Sprintf("rename to %s failed (%v); trying copy replace", executablePath, err))
490 } 581 }
491 582
492 // Permission denied — e.g. installed to /usr/local/bin. Ask for sudo. 583 // 2) Cross-device (or other rename failure): copy onto dest filesystem then swap.
493 updateUserMessage(GetGlobalConfig(), "Update needs elevated permissions to replace the installed binary.") 584 if err := copyFileReplace(tmpPath, executablePath); err == nil {
494 if err := installExecutableWithSudo(tmpPath, executablePath); err != nil { 585 _ = os.Remove(tmpPath)
495 return err 586 return nil
587 } else if isPermissionError(err) {
588 updateUserMessage(GetGlobalConfig(), "Update needs elevated permissions to replace the installed binary.")
589 if sudoErr := installExecutableWithSudo(tmpPath, executablePath); sudoErr != nil {
590 return fmt.Errorf("failed to replace executable: %w", sudoErr)
591 }
592 _ = os.Remove(tmpPath)
593 return nil
594 } else {
595 // Last resort: sudo install from original temp (covers weird FS layouts).
596 if isCrossDeviceError(err) || runtime.GOOS != "windows" {
597 Log(fmt.Sprintf("copy replace failed (%v); trying sudo", err))
598 updateUserMessage(GetGlobalConfig(), "Update needs elevated permissions to replace the installed binary.")
599 if sudoErr := installExecutableWithSudo(tmpPath, executablePath); sudoErr == nil {
600 _ = os.Remove(tmpPath)
601 return nil
602 }
603 }
604 return fmt.Errorf("failed to replace executable: %w", err)
496 } 605 }
497 _ = os.Remove(tmpPath)
498 return nil
499} 606}
internal/update_test.go +57
@@ -2,6 +2,7 @@ package internal
2 2
3import ( 3import (
4 "encoding/json" 4 "encoding/json"
5 "errors"
5 "net/http" 6 "net/http"
6 "net/http/httptest" 7 "net/http/httptest"
7 "os" 8 "os"
@@ -137,6 +138,62 @@ func TestFormatLocalTimeUsesLocalZone(t *testing.T) {
137 } 138 }
138} 139}
139 140
141func TestIsCrossDeviceError(t *testing.T) {
142 if !isCrossDeviceError(errors.New("rename /tmp/a /home/b: invalid cross-device link")) {
143 t.Fatal("expected cross-device detection")
144 }
145 if isCrossDeviceError(os.ErrPermission) {
146 t.Fatal("permission is not cross-device")
147 }
148}
149
150func TestCopyFileReplaceCrossDeviceStyle(t *testing.T) {
151 srcDir := t.TempDir()
152 dstDir := t.TempDir()
153 src := filepath.Join(srcDir, "newbin")
154 dst := filepath.Join(dstDir, "curd")
155 if err := os.WriteFile(src, []byte("#!/bin/sh\necho new\n"), 0755); err != nil {
156 t.Fatal(err)
157 }
158 if err := os.WriteFile(dst, []byte("#!/bin/sh\necho old\n"), 0755); err != nil {
159 t.Fatal(err)
160 }
161 if err := copyFileReplace(src, dst); err != nil {
162 t.Fatalf("copyFileReplace: %v", err)
163 }
164 data, err := os.ReadFile(dst)
165 if err != nil {
166 t.Fatal(err)
167 }
168 if !strings.Contains(string(data), "new") {
169 t.Fatalf("dest not replaced: %q", data)
170 }
171}
172
173func TestReplaceExecutableHandlesCrossDevice(t *testing.T) {
174 srcDir := t.TempDir()
175 dstDir := t.TempDir()
176 src := filepath.Join(srcDir, "downloaded")
177 dst := filepath.Join(dstDir, "curd")
178 if err := os.WriteFile(src, []byte("new-binary-content"), 0755); err != nil {
179 t.Fatal(err)
180 }
181 if err := os.WriteFile(dst, []byte("old-binary-content"), 0755); err != nil {
182 t.Fatal(err)
183 }
184 // src and dst are different temp dirs — rename often fails with EXDEV on Linux.
185 if err := replaceExecutable(src, dst); err != nil {
186 t.Fatalf("replaceExecutable: %v", err)
187 }
188 data, err := os.ReadFile(dst)
189 if err != nil {
190 t.Fatal(err)
191 }
192 if string(data) != "new-binary-content" {
193 t.Fatalf("got %q", data)
194 }
195}
196
140func TestBuildUpdatePromptMessage(t *testing.T) { 197func TestBuildUpdatePromptMessage(t *testing.T) {
141 prompt, msg := buildUpdatePromptMessage("2.0.1", updatePendingState{ 198 prompt, msg := buildUpdatePromptMessage("2.0.1", updatePendingState{
142 LatestVersion: "2.0.2", 199 LatestVersion: "2.0.2",