Repository navigation
Description
With WithServerWorkingDirectory(dir), Server passes the target of a SYMLINK request through toLocalPath (server.go:276, the same in v1.13.12 and on master):
err := os.Symlink(s.toLocalPath(p.Targetpath), s.toLocalPath(p.Linkpath))toLocalPath joins a relative path with the working directory, so a relative target is stored as an absolute path under the working directory. A link sub/link created with the target file (that is sub/file, since a link's target is resolved from the link's own folder) is stored as <dir>/file, a different file, and following it fails. Without a working directory the same target is stored as given. OpenSSH's sftp-server stores a link's target as given.
Reproduction (pkg/sftp v1.13.12; v1.13.10 does the same):
package main
import (
"fmt"
"io"
"log"
"os"
"path/filepath"
"github.com/pkg/sftp"
)
// serve starts a Server over a pair of pipes and returns a client on it.
func serve(options ...sftp.ServerOption) *sftp.Client {
clientReads, serverWrites := io.Pipe()
serverReads, clientWrites := io.Pipe()
server, err := sftp.NewServer(struct {
io.Reader
io.WriteCloser
}{serverReads, serverWrites}, options...)
if err != nil {
log.Fatal(err)
}
go server.Serve()
client, err := sftp.NewClientPipe(clientReads, clientWrites)
if err != nil {
log.Fatal(err)
}
return client
}
func main() {
dir, err := os.MkdirTemp("", "sftp-symlink-")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
if err := os.MkdirAll(filepath.Join(dir, "sub"), 0o755); err != nil {
log.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "sub", "file"), []byte("contents\n"), 0o644); err != nil {
log.Fatal(err)
}
// With a working directory: the link sub/link -> "file" (relative).
client := serve(sftp.WithServerWorkingDirectory(dir))
if err := client.Symlink("file", "sub/link"); err != nil {
log.Fatal(err)
}
target, err := os.Readlink(filepath.Join(dir, "sub", "link"))
fmt.Printf("with WithServerWorkingDirectory: sub/link -> %q (err %v)\n", target, err)
_, err = client.Stat("sub/link")
fmt.Printf(" stat through the link: %v\n", err)
// Without one, the same request by absolute link path: the target is kept.
client = serve()
if err := client.Symlink("file", filepath.ToSlash(filepath.Join(dir, "sub", "link2"))); err != nil {
log.Fatal(err)
}
target, err = os.Readlink(filepath.Join(dir, "sub", "link2"))
fmt.Printf("without a working directory: sub/link2 -> %q (err %v)\n", target, err)
}Output on Linux (Go 1.27.3):
with WithServerWorkingDirectory: sub/link -> "/tmp/sftp-symlink-2453118473/file" (err <nil>)
stat through the link: file does not exist
without a working directory: sub/link2 -> "file" (err <nil>)
A fix could store the target as given (converting its separators where that matters) and resolve only the link path through toLocalPath.
Activity