streams.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package smbserver
  2. import (
  3. "strings"
  4. "imuslab.com/arozos/mod/storage/smbserver/wire"
  5. )
  6. /*
  7. streams.go
  8. Named streams: data beside a file under a name of its own, written as
  9. file:name in a path. Windows keeps where a download came from in
  10. Zone.Identifier, and macOS stores extended attributes, Finder info and
  11. resource forks this way instead of the ._ files it writes everywhere
  12. else. Where a stream is kept is the backend's business.
  13. A stream is passed to the Share as its file's path, StreamSeparator and
  14. the stream name. The separator is a NUL, which no file name can hold,
  15. because a colon can: Windows sends one for a Linux name in the private
  16. range, and macOS one inside an attribute name.
  17. */
  18. // StreamSeparator joins a file's path and a stream name in a share path.
  19. const StreamSeparator = "\x00"
  20. // StreamShare is a Share that keeps named streams.
  21. type StreamShare interface {
  22. //Streams lists the named streams of a file or folder, by name
  23. Streams(p string) []FileInfo
  24. }
  25. func streamPath(base, stream string) string { return base + StreamSeparator + stream }
  26. // splitStreamPath is the inverse of streamPath. ok is false for a path
  27. // without a stream.
  28. func splitStreamPath(p string) (base, stream string, ok bool) {
  29. i := strings.Index(p, StreamSeparator)
  30. if i < 0 {
  31. return p, "", false
  32. }
  33. return p[:i], p[i+1:], true
  34. }
  35. func isStreamPath(p string) bool { return strings.Contains(p, StreamSeparator) }
  36. // streamInfo is FILE_STREAM_INFORMATION: the file's own data first, then
  37. // every named stream, each entry on 8 bytes.
  38. func streamInfo(share Share, base string, info FileInfo) []byte {
  39. type entry struct {
  40. name string
  41. size int64
  42. }
  43. entries := []entry{}
  44. if !info.IsDir {
  45. entries = append(entries, entry{"::$DATA", info.Size})
  46. }
  47. if ss, ok := share.(StreamShare); ok {
  48. for _, s := range ss.Streams(base) {
  49. entries = append(entries, entry{":" + toWireName(s.Name) + ":$DATA", s.Size})
  50. }
  51. }
  52. w := wire.NewWriter(64 * len(entries))
  53. for i, e := range entries {
  54. start := w.Len()
  55. name := wire.EncodeUTF16(e.name)
  56. w.U32(0)
  57. w.U32(uint32(len(name)))
  58. w.U64(uint64(e.size))
  59. w.U64(allocationOf(e.size))
  60. w.Bytes(name)
  61. if i < len(entries)-1 {
  62. w.Align(8)
  63. next := w.Len() - start
  64. w.B[start] = byte(next)
  65. w.B[start+1] = byte(next >> 8)
  66. w.B[start+2] = byte(next >> 16)
  67. w.B[start+3] = byte(next >> 24)
  68. }
  69. }
  70. return w.B
  71. }