ls_formatting.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package sftp
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "os/user"
  7. "strconv"
  8. "time"
  9. sshfx "github.com/pkg/sftp/internal/encoding/ssh/filexfer"
  10. )
  11. func lsFormatID(id uint32) string {
  12. return strconv.FormatUint(uint64(id), 10)
  13. }
  14. type osIDLookup struct{}
  15. func (osIDLookup) Filelist(*Request) (ListerAt, error) {
  16. return nil, errors.New("unimplemented stub")
  17. }
  18. func (osIDLookup) LookupUserName(uid string) string {
  19. u, err := user.LookupId(uid)
  20. if err != nil {
  21. return uid
  22. }
  23. return u.Username
  24. }
  25. func (osIDLookup) LookupGroupName(gid string) string {
  26. g, err := user.LookupGroupId(gid)
  27. if err != nil {
  28. return gid
  29. }
  30. return g.Name
  31. }
  32. // runLs formats the FileInfo as per `ls -l` style, which is in the 'longname' field of a SSH_FXP_NAME entry.
  33. // This is a fairly simple implementation, just enough to look close to openssh in simple cases.
  34. func runLs(idLookup NameLookupFileLister, dirent os.FileInfo) string {
  35. // example from openssh sftp server:
  36. // crw-rw-rw- 1 root wheel 0 Jul 31 20:52 ttyvd
  37. // format:
  38. // {directory / char device / etc}{rwxrwxrwx} {number of links} owner group size month day [time (this year) | year (otherwise)] name
  39. symPerms := sshfx.FileMode(fromFileMode(dirent.Mode())).String()
  40. var numLinks uint64 = 1
  41. uid, gid := "0", "0"
  42. switch sys := dirent.Sys().(type) {
  43. case *sshfx.Attributes:
  44. uid = lsFormatID(sys.UID)
  45. gid = lsFormatID(sys.GID)
  46. case *FileStat:
  47. uid = lsFormatID(sys.UID)
  48. gid = lsFormatID(sys.GID)
  49. default:
  50. if fiExt, ok := dirent.(FileInfoUidGid); ok {
  51. uid = lsFormatID(fiExt.Uid())
  52. gid = lsFormatID(fiExt.Gid())
  53. break
  54. }
  55. numLinks, uid, gid = lsLinksUIDGID(dirent)
  56. }
  57. if idLookup != nil {
  58. uid, gid = idLookup.LookupUserName(uid), idLookup.LookupGroupName(gid)
  59. }
  60. mtime := dirent.ModTime()
  61. date := mtime.Format("Jan 2")
  62. var yearOrTime string
  63. if mtime.Before(time.Now().AddDate(0, -6, 0)) {
  64. yearOrTime = mtime.Format("2006")
  65. } else {
  66. yearOrTime = mtime.Format("15:04")
  67. }
  68. return fmt.Sprintf("%s %4d %-8s %-8s %8d %s %5s %s", symPerms, numLinks, uid, gid, dirent.Size(), date, yearOrTime, dirent.Name())
  69. }