FileInfo.IsDir() returns wrong, on windows
I have a AIX ssh server, and the client is windows.
infos, err := client.ReadDir(dirname) for _, info := range infos { println(info.IsDir()) }
here, info.IsDir() always return false on windows. However if I use a linux or mac client, IsDir() returns correctly.
What ssh/sftp server are you using on windows?
Sorry, maybe I did not describe my problem clearly. sshd is running on AIX, with version OpenSSH_5.0p1, OpenSSL 0.9.8h 28 May 2008
$ uname -a AIX ibm550_a 3 5 00CFC14E4C00
$ sshd -v sshd: illegal option -- v OpenSSH_5.0p1, OpenSSL 0.9.8h 28 May 2008 usage: sshd [-46Ddeiqt] [-b bits] [-f config_file] [-g login_grace_time] [-h host_key_file] [-k key_gen_time] [-o option] [-p port] [-u len]
I use the latest pkg/sftp library, develop on mac and cross compiled for linux and windows. On mac and linux, the pkg/sftp FileInfo.IsDir method worked as expected, but on windows it always returns false.
Thanks for confirming, i'm sorry I wasn't faster in understanding the problem. This is the old '/' vs '' problem.
I think the output of client.ReadDir() is documented to always use '/' as a separator, but I hope that I can do better. Let me think on this tonight.
Any updates on windows support?
I am using it to serve on windows, and '\'s are sent which confuses clients. I just added f = strings.Replace(f, "\\", "/", -1) after f = filepath.Clean(f) in server.go. Which mostly works for me with WinSCP as client.
I'm sorry I'm not able to provide an ETA on when this will be fixed. If you are able to propose a fix, with a test, this would be much appreciated.
Server:
Currently sends os dependent path. There is a quick one liner fix with filepath.ToSlash(path string). A more complete fix need to translate C: into /C and be able to list drive letters under /
Client: I have not examined this client implementation. From the bug report it looks like path handling is also using os dependent code, the path package uses '/' as path separator irrespective of the OS, might be of help.
Testing: Not sure how to do that other than limited testing on string manipulation.
Next steps: I would like to see filepath.ToSlash applied to paths send from servers. ToSlash replaces os depend path separators with "/" and is a no-op on systems with native "/", so it is very safe to use. (Can I make a pull request with a single line of ToSlash added?)
For handling of drive letters, it is more involved, I would need more discussion before working on it.
Can anyone give me some snippets that could go in a test to reproduce this issue? I don't have easy access to a windows system and am not sure about the details of the issue (ie. the formatting of the paths).
@eikenb The issue is only reproducible on windows because it is a problem with windows using a different path format. This includes Go os dependent path handling code, so even a code snippet with windows path strings included can behave differently depending on the os you test it on.
Behaviorally, the problem only manifest when communicating with a sftp client that does path manipulation but does not understand windows paths, or a server that tries to open a local path that have been manipulated remotely as a windows path.
I was thinking that if it was just string path representations in question that a test could be put together to check some of this but looking at the client code and standard lib it doesn't look like it will possible. Without that I'm sorry to say that unless someone with Windows wants to fix these issues and put together a pull request there is not much I can do.
I am actually interest, but not certain of the scope.
For the server, fix slash easy, fix drive letter hard.
For the client, fix the use of os depend path handling to use os independ Unix path handing for path strings from the network. (I assume, I have not looked at it in detail)
For testing, currently windows pass all unit tests (obviously the right tests are missing). But all integration tests fail because Unix only devices and processes are used. A Windows automated testing environment is also needed to avoid regressions from non-Windows developers.
What do you think are necessary, good to have, and don't dos?
First step is proper unit tests so we can reproduce the issue. Then I think fixing the slash issues in the server and the client. Once all that is done then we can come back and look at the drive letter.
If you'd like to work on this please do a pull request. I'd like either separate pull requests for each thing or separate commits for each thing in one pull request. By each thing I mean one for the unit tests, one for the server code and one for the client code.
Thanks.
First step is proper unit tests so we can reproduce the issue.
I don't know what you mean by this. The issue is one of integration, and the most obvious way to reproduce the issue is to run it on windows. I hope you don't mean adding windows mocking to tests.
I get your point and I guess the first thing to do is get things into a form that we can write unit tests that will test things in a way that the underlying OS doesn't matter. That means starting with something like what #160 is trying to do by eliminating path manipulation done with the filepath module. Then I think figuring out places where we'd get windows formatted paths and be sure they are converted to standard paths on the way in.
I am used to TDD and so think of everything in terms of writing a test for it first. But I guess that you have to sometimes fix some thing before you can get to that point. I hope this helps as I'd love for you to be able to contribute. Maybe you could consider just fixing something specific, like the one-liner server fix you mention, in a pull requests to get started.
I have created the pull request for the one liner fix.
It seems the recent troubles with compiling on windows have brought a few windows developer out of the woodworks. I hope we can work together on windows support.
I've created a small application named "graft" for my personal golang experiments and i think i ran exactly into this bug. If someone needs a simple way to reproduce, you could try it with my code.
- As already pointed out, you will need a windows machine, everything works as expected on *nix
- Perform the following steps on the windows command line:
go get -u github.com/sandreas/graft
md graft-test && md graft-test\subdirectory
cd graft-test
graft * --serve=2022 --debug
This should serve * in graft-test on port 2022 via sftp (port is currently hardcoded, changes to params have no effect!). Now you can login with your favorite sftp client (the server part causes the problem, doesn't matter wether you use a windows or *nix client, i personally use filezilla):
Username: graft Password: graft
Output (server side) will be something like this:
Listening on [::]:2022
2017/07/23 17:07:33 Login: graft
2017/07/23 17:07:33 login detected: graft
2017/07/23 17:07:33 Request: [email protected]
2017/07/23 17:07:33 - accepted: false
2017/07/23 17:07:33 Request: subsystem
2017/07/23 17:07:33 Subsystem: sftp
2017/07/23 17:07:33 - accepted: true
2017/07/23 17:07:33 Fileinfo: Filepath: \ , Target: , Method: List
2017/07/23 17:07:33 requestedPath: /
2017/07/23 17:07:33 pathMapping for / contains: 2
2017/07/23 17:07:33 Stat for file .: isDir=> true size=> 0
2017/07/23 17:07:33 Stat for file subdirectory: isDir=> true size=> 0
Now expected file listing would be to see a directory "subdirectory", but it is represented as file.
graft SFTP-Code is mostly in sftpd-Folder: https://github.com/sandreas/graft/tree/master/sftpd To start a server, you could use:
// matchingPaths contain all files and directories as string, that should be served via sftp, in this case, only "subdirectory"
var matchingPaths []string
append(matchingPaths, "subdirectory")
// `key-directory` must exist, public and private key for server will be generated and stored there
sftpd.NewSimpleServer("key-directory", "0.0.0.0", 2022, "graft", "graft", matchingPaths)
Hope it helps.
Hello,
i investigated the bug further. Unfortunately i did not get very far, because i'm really new to golang. But i at least created a fork, so i hope that anyone could reproduce the bug easily.
Steps for windows command line (Note: A directory .graft is created in HOME-directory to store the server keys):
git clone https://github.com/sandreas/sftp
cd sftp
git checkout fix-windows-errors
go run .\examples\sftpd\main.go
Then connect to sftp://localhost:2022 user graft password graft
Server should serve following files in the sftp directory (hardcoded): examples (directory) LICENSE (file)
I tried to fix the Windows-Backslash-Slash problem (basically i filepath.ToSlash'ed) every path that i found with filepath.Clean - see git history for details). It works so far (no Backslashes any more :-), although it is a hacky solution without tests, which i'm working on atm.
Although slashes work, it seems that files and directories are still not handled correctly. Something seems to be wrong already with "List" command, because neither the filesize nor the status as directory is working for the items.
Strange is: LICENSE file can be downloaded as file and contains valid content, accessing examples directory gives an error.
Since i am beginner in golang, i added some very simple logging without really knowing about the code. So my trace (see whole trace below) shows that the vfshandler.go i wrote returns the right Stats / FileInfo for the files:
2017/07/25 20:46:06 List => stat.Name()=LICENSE, stat.IsDir()=false 2017/07/25 20:46:06 List => stat.Name()=examples, stat.IsDir()=true
- I think that there is something wrong with the fileinfo() in request.go or the attribute marshalling
- I did not find unit tests for directories in the attr_test.go (only file tests)
- Could the marshalling / unmarshalling be the reason for the problem?
- I would really appreciate help, i'm not sure i can fix it, seems to be a too complex problem for me...
My "trace":
2017/07/25 20:46:03 request-server.go->packetWorker: pkt.(type) sshFxInitPacket
2017/07/25 20:46:03 request-server.go->packetWorker: sendPacket {Version:3 Extensions:[]}
2017/07/25 20:46:03 request-server.go->packetWorker: pkt.(type) sshFxpRealpathPacket
2017/07/25 20:46:03 request-server.go->packetWorker: sendPacket &{ID:256 NameAttrs:[{Name:/ LongName:/ Attrs:[0]}]}
2017/07/25 20:46:06 request-server.go->packetWorker: pkt.(type) sshFxpRealpathPacket
2017/07/25 20:46:06 request-server.go->packetWorker: sendPacket &{ID:256 NameAttrs:[{Name:/ LongName:/ Attrs:[0]}]}
2017/07/25 20:46:06 request-server.go->packetWorker: pkt.(type) isOpener
2017/07/25 20:46:06 === request.go->NewRequest: Method Open for path /
2017/07/25 20:46:06 request-server.go->packetWorker: sendPacket {ID:256 Handle:1}
2017/07/25 20:46:06 request-server.go->packetWorker: Type hasHandle (handle 1)
2017/07/25 20:46:06 => request after update: {Method:List Filepath:/ Flags:0 Attrs:[] Target: pkt_id:256 packets:0xc0420377a0 stateLock:0xc0420ae360 state:0xc042040d80}
2017/07/25 20:46:06 request.go->handle - r.Method: List, r: {Method:List Filepath:/ Flags:0 Attrs:[] Target: pkt_id:256 packets:0xc0420377a0 stateLock:0xc0420ae360 state:0xc042040d80}
2017/07/25 20:46:06 vfshandler.go->FileInfo: r={Method:List Filepath:/ Flags:0 Attrs:[] Target: pkt_id:256 packets:0xc0420377a0 stateLock:0xc0420ae360 state:0xc042040d80}
2017/07/25 20:46:06 List => stat.Name()=LICENSE, stat.IsDir()=false
2017/07/25 20:46:06 List => stat.Name()=examples, stat.IsDir()=true
2017/07/25 20:46:06 request.go->fileinfo - Method List
2017/07/25 20:46:06 => fi: &{name:LICENSE sys:{FileAttributes:32 CreationTime:{LowDateTime:29930021 HighDateTime:30606710} LastAccessTime:{LowDateTime:29930021 HighDateTime:30606710} LastWriteTime:{LowDateTime:29930021 HighDateTime:30606710} FileSizeHigh:0 FileSizeLow:1289} pipe:false Mutex:{state:0 sema:0} path:C:\Users\mediacenter\Temp\sftp\LICENSE vol:0 idxhi:0 idxlo:0}
2017/07/25 20:46:06 => fi: &{name:examples sys:{FileAttributes:16 CreationTime:{LowDateTime:30040016 HighDateTime:30606710} LastAccessTime:{LowDateTime:145396448 HighDateTime:30606710} LastWriteTime:{LowDateTime:145396448 HighDateTime:30606710} FileSizeHigh:0 FileSizeLow:4096} pipe:false Mutex:{state:0 sema:0} path:C:\Users\mediacenter\Temp\sftp\examples vol:0 idxhi:0 idxlo:0}
2017/07/25 20:46:06 => Attrs-items:
2017/07/25 20:46:06 => item 0: {Name:LICENSE LongName:/LICENSE Attrs:[0xc042124000]}:
2017/07/25 20:46:06 => item 1: {Name:examples LongName:/examples Attrs:[0xc042124060]}:
2017/07/25 20:46:06 request.go->handle: r={Method:List Filepath:/ Flags:0 Attrs:[] Target: pkt_id:256 packets:0xc0420377a0 stateLock:0xc0420ae360 state:0xc042040d80}
2017/07/25 20:46:06 => rpkt: &{ID:256 NameAttrs:[{Name:LICENSE LongName:/LICENSE Attrs:[0xc042124000]} {Name:examples LongName:/examples Attrs:[0xc042124060]}]}
2017/07/25 20:46:07 => err: <nil>
2017/07/25 20:46:07 => pkt: &{ID:256 Handle:1}. rpkt: &{ID:256 NameAttrs:[{Name:LICENSE LongName:/LICENSE Attrs:[0xc042124000]} {Name:examples LongName:/examples Attrs:[0xc042124060]}]}
2017/07/25 20:46:07 request-server.go->packetWorker: sendPacket &{ID:256 NameAttrs:[{Name:LICENSE LongName:/LICENSE Attrs:[0xc042124000]} {Name:examples LongName:/examples Attrs:[0xc042124060]}]}
2017/07/25 20:46:07 request-server.go->packetWorker: Type hasHandle (handle 1)
2017/07/25 20:46:07 => request after update: {Method:List Filepath:/ Flags:0 Attrs:[] Target: pkt_id:256 packets:0xc0420377a0 stateLock:0xc0420ae360 state:0xc042040d80}
2017/07/25 20:46:07 request.go->handle - r.Method: List, r: {Method:List Filepath:/ Flags:0 Attrs:[] Target: pkt_id:256 packets:0xc0420377a0 stateLock:0xc0420ae360 state:0xc042040d80}
2017/07/25 20:46:07 vfshandler.go->FileInfo: r={Method:List Filepath:/ Flags:0 Attrs:[] Target: pkt_id:256 packets:0xc0420377a0 stateLock:0xc0420ae360 state:0xc042040d80}
2017/07/25 20:46:07 List => stat.Name()=LICENSE, stat.IsDir()=false
2017/07/25 20:46:07 List => stat.Name()=examples, stat.IsDir()=true
2017/07/25 20:46:07 request.go->fileinfo - Method List
2017/07/25 20:46:07 => Attrs-items:
2017/07/25 20:46:07 request.go->handle: r={Method:List Filepath:/ Flags:0 Attrs:[] Target: pkt_id:256 packets:0xc0420377a0 stateLock:0xc0420ae360 state:0xc042040d80}
2017/07/25 20:46:07 => rpkt: <nil>
2017/07/25 20:46:07 => err: EOF
2017/07/25 20:46:07 => pkt: &{ID:256 Handle:1}. rpkt: {ID:256 StatusError:{Code:1 msg:EOF lang:}}
2017/07/25 20:46:07 request-server.go->packetWorker: sendPacket {ID:256 StatusError:{Code:1 msg:EOF lang:}}
2017/07/25 20:46:07 request-server.go->packetWorker: pkt.(type) sshFxpClosePacket
2017/07/25 20:46:07 request-server.go->packetWorker: sendPacket {ID:256 StatusError:{Code:0 msg: lang:}}
@davecheney
Status-Update: Since i fixed the Slash-Backslash-Problem in my repo, i took a look at the "directories are shown as files" problem. I traced it to a small piece of code, but i do not have the knowledge to fix it yet (new to golang;).
Something seems to be wrong with the marshal function for FileInfo or its call.
If a fixed byte dump from macos of the same response for directory examples is returned instead of the generated one, everything works as expected (see if v.Name() == "examples" { below).
My current guess is, that one of these three methods could contain an error: attrs.go
- fileStatFromInfo
- fromFileMode
- fileStatFromInfoOs ==> OS Specific conversion of FileInfo to fileStat
BUT: If i override resulting fileStat with the working macOS-Values, example is represented as file, which is wrong. So perhaps the func marshal already gets the wrong byte parameter before marshaling FileInfo or my vfshandler.go is not functional.
My focus currently is on: request.go, func fileinfo: something could be wrong with the sshFxpNameAttr.Attrs or the FileInfo itself packet.go: func MarshalBinary: wrong parameters, damaged FileInfo or Attrs processing? packet.go: func marshal packet.go: func marshalFileInfo: wrong parameters already or fileStatFromInfo gives wrong result (fi.IsDir() is true)
// ***packet.go***
func marshal(b []byte, v interface{}) []byte {
if v == nil {
return b
}
switch v := v.(type) {
case uint8:
return append(b, v)
case uint32:
return marshalUint32(b, v)
case uint64:
return marshalUint64(b, v)
case string:
return marshalString(b, v)
case os.FileInfo:
if v.Name() == "examples" {
log.Printf("------before: %+v", b)
marshalledFileInfo := marshalFileInfo(b, v)
log.Printf("------after : %+v", marshalledFileInfo)
macOSDump := []byte{
0, 0, 0, 8, 101, 120, 97, 109, 112, 108, 101, 115, 0, 0, 0,
64, 100, 114, 119, 120, 114, 45, 120, 114, 45, 120, 32, 32,
32, 32, 57, 32, 53, 48, 49, 32, 32, 32, 32, 32, 32, 50, 48,
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 51, 48, 54,
32, 65, 117, 103, 32, 32, 54, 32, 50, 51, 58, 51, 51, 32,
101, 120, 97, 109, 112, 108, 101, 115, 0, 0, 0, 15, 0, 0, 0,
0, 0, 0, 1, 50, 0, 0, 1, 245, 0, 0, 0, 20, 0, 0, 65, 237,
89, 135, 139, 55, 89, 135, 139, 55,
}
return macOSDump
} else {
return marshalFileInfo(b, v)
}
default:
switch d := reflect.ValueOf(v); d.Kind() {
case reflect.Struct:
for i, n := 0, d.NumField(); i < n; i++ {
b = append(marshal(b, d.Field(i).Interface()))
}
return b
case reflect.Slice:
for i, n := 0, d.Len(); i < n; i++ {
b = append(marshal(b, d.Index(i).Interface()))
}
return b
default:
panic(fmt.Sprintf("marshal(%#v): cannot handle type %T", v, v))
}
}
}
Ok, i finally got it. There is a bug in Filezilla FTP Client. It reads the "directory" status out of the longname attribute, not as recommended in the rfc from the attrs field. (https://trac.filezilla-project.org/ticket/9921#comment:3)
So, filezilla cannot show a directory on windows systems when using pkg/sftp, because pkg/sftp does not provide a "unix-like" longname attribute - instead of drwxr-xr-x 8 501 20 272 Aug 9 19:46 examples it shows only examples on windows which does not contain a "d" as first letter, resulting in wrong type for filezilla ftp client.
So, in the next days i will write some tests and make a pull request for the slash-backslash-problem including a new runLs function for windows as workaround / general improvement (also fixes "Filezilla problems").
“It reads the "directory" status out of the longname attribute, not as recommended in the rfc from the attrs field.” 🤢
Pull request with a potential fix: https://github.com/pkg/sftp/pull/191 Why does travis fail here?