copy.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package smbserver
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "errors"
  6. "io"
  7. "strconv"
  8. "sync"
  9. "imuslab.com/arozos/mod/storage/smbserver/wire"
  10. )
  11. /*
  12. copy.go
  13. Server side copy. File Explorer asks for a resume key on the source file,
  14. then sends FSCTL_SRV_COPYCHUNK on the target with the ranges to copy, so
  15. a copy within this server never sends the data over the network.
  16. Each chunk is a read and a write that go through the same checks as
  17. READ and WRITE: access on both opens, byte range locks, the drive's
  18. access list and the target's quota.
  19. */
  20. // Limits of one request, the ones Windows servers use. A request over them
  21. // is refused with the limits, and the client splits its copy to fit.
  22. const (
  23. copyMaxChunks = 256
  24. copyMaxChunkSize = 1 << 20
  25. copyMaxTotal = 16 << 20
  26. )
  27. type resumeKey [24]byte
  28. // resumeKeys finds the source open of a copy. Keys are random, so knowing a
  29. // file is open does not let anyone copy from it.
  30. type resumeKeys struct {
  31. mu sync.Mutex
  32. opens map[resumeKey]*open
  33. }
  34. func (k *resumeKeys) keyFor(o *open) resumeKey {
  35. k.mu.Lock()
  36. defer k.mu.Unlock()
  37. if o.hasResumeKey {
  38. return o.resumeKey
  39. }
  40. if k.opens == nil {
  41. k.opens = map[resumeKey]*open{}
  42. }
  43. var key resumeKey
  44. for {
  45. rand.Read(key[:])
  46. if _, taken := k.opens[key]; !taken {
  47. break
  48. }
  49. }
  50. k.opens[key] = o
  51. o.resumeKey, o.hasResumeKey = key, true
  52. return key
  53. }
  54. func (k *resumeKeys) find(key resumeKey) *open {
  55. k.mu.Lock()
  56. defer k.mu.Unlock()
  57. return k.opens[key]
  58. }
  59. func (k *resumeKeys) drop(o *open) {
  60. k.mu.Lock()
  61. defer k.mu.Unlock()
  62. if o.hasResumeKey {
  63. delete(k.opens, o.resumeKey)
  64. o.hasResumeKey = false
  65. }
  66. }
  67. func (c *conn) requestResumeKey(r *request, q *wire.IoctlRequest) *response {
  68. o, status := r.open(q.FileID)
  69. if status != wire.StatusOK {
  70. return errorResponse(status)
  71. }
  72. //Any handle gets a key: macOS asks on the share root to learn whether
  73. //the server copies at all. Copying from a folder fails later.
  74. if o.pipe != nil {
  75. return errorResponse(wire.StatusInvalidParameter)
  76. }
  77. if q.MaxOutputResponse < 32 {
  78. return errorResponse(wire.StatusInvalidParameter)
  79. }
  80. key := c.srv.resume.keyFor(o)
  81. w := wire.NewWriter(32)
  82. w.Bytes(key[:])
  83. w.U32(0) //No context
  84. w.Zero(4)
  85. return ioctlResponse(q, w.B, wire.StatusOK)
  86. }
  87. type copyChunk struct {
  88. source, target uint64
  89. length uint32
  90. }
  91. // copyResult is SRV_COPYCHUNK_RESPONSE. On a refusal for size it carries
  92. // the limits instead.
  93. func copyResult(q *wire.IoctlRequest, status uint32, chunks, chunkBytes, total uint32) *response {
  94. w := wire.NewWriter(12)
  95. w.U32(chunks)
  96. w.U32(chunkBytes)
  97. w.U32(total)
  98. return ioctlResponse(q, w.B, status)
  99. }
  100. func parseCopyChunks(input []byte) (resumeKey, []copyChunk, bool) {
  101. var key resumeKey
  102. in := wire.NewReader(input)
  103. copy(key[:], in.Bytes(24))
  104. count := in.U32()
  105. in.Skip(4)
  106. if in.Bad() || uint64(count)*24 > uint64(len(input)) {
  107. return key, nil, false
  108. }
  109. chunks := make([]copyChunk, 0, count)
  110. for i := uint32(0); i < count; i++ {
  111. ch := copyChunk{source: in.U64(), target: in.U64(), length: in.U32()}
  112. in.Skip(4)
  113. chunks = append(chunks, ch)
  114. }
  115. return key, chunks, !in.Bad()
  116. }
  117. // copyChunks is FSCTL_SRV_COPYCHUNK, and with needRead false the _WRITE
  118. // form, which lets a target opened for writing alone receive the copy.
  119. func (c *conn) copyChunks(r *request, q *wire.IoctlRequest, needRead bool) *response {
  120. target, status := r.open(q.FileID)
  121. if status != wire.StatusOK {
  122. return errorResponse(status)
  123. }
  124. if target.pipe != nil || target.isDir || target.file == nil {
  125. return errorResponse(wire.StatusInvalidParameter)
  126. }
  127. if q.MaxOutputResponse < 12 {
  128. return errorResponse(wire.StatusInvalidParameter)
  129. }
  130. if target.access&(wire.FileWriteData|wire.FileAppendData) == 0 || needRead && target.access&wire.FileReadData == 0 {
  131. return errorResponse(wire.StatusAccessDenied)
  132. }
  133. key, chunks, ok := parseCopyChunks(q.Input)
  134. if !ok {
  135. return errorResponse(wire.StatusInvalidParameter)
  136. }
  137. var total uint64
  138. tooBig := len(chunks) > copyMaxChunks
  139. for _, ch := range chunks {
  140. if ch.length == 0 || ch.length > copyMaxChunkSize {
  141. tooBig = true
  142. }
  143. total += uint64(ch.length)
  144. }
  145. if tooBig || total > copyMaxTotal {
  146. return copyResult(q, wire.StatusInvalidParameter, copyMaxChunks, copyMaxChunkSize, copyMaxTotal)
  147. }
  148. source := c.srv.resume.find(key)
  149. if source == nil {
  150. return errorResponse(wire.StatusObjectNameNotFound)
  151. }
  152. //The session is read under the durable table's lock: the source may be
  153. //on another connection that is being detached right now
  154. if _, owner := c.srv.connOf(source); owner == nil || owner.username != r.sess.username {
  155. //Another user's key, or one whose handle waits for a lost client, is
  156. //treated as no key at all
  157. return errorResponse(wire.StatusObjectNameNotFound)
  158. }
  159. if source.access&wire.FileReadData == 0 {
  160. return errorResponse(wire.StatusAccessDenied)
  161. }
  162. if source.isDir || source.file == nil {
  163. return errorResponse(wire.StatusInvalidDeviceRequest)
  164. }
  165. var written, copied uint32
  166. buf := make([]byte, copyMaxChunkSize)
  167. for _, ch := range chunks {
  168. if st := c.copyOne(source, target, ch, buf); st != wire.StatusOK {
  169. return copyResult(q, st, written, 0, copied)
  170. }
  171. written++
  172. copied += ch.length
  173. }
  174. r.detail += "copied=" + strconv.FormatUint(uint64(copied), 10) + " "
  175. return copyResult(q, wire.StatusOK, written, 0, copied)
  176. }
  177. // lockPair takes the I/O side of both opens in one fixed order, so that two
  178. // copies running opposite ways cannot hold one each while a close waits.
  179. func lockPair(a, b *open) func() {
  180. if a == b {
  181. a.io.RLock()
  182. return a.io.RUnlock
  183. }
  184. if bytes.Compare(a.id[:], b.id[:]) > 0 {
  185. a, b = b, a
  186. }
  187. a.io.RLock()
  188. b.io.RLock()
  189. return func() {
  190. b.io.RUnlock()
  191. a.io.RUnlock()
  192. }
  193. }
  194. func (c *conn) copyOne(source, target *open, ch copyChunk, buf []byte) uint32 {
  195. unlock := lockPair(source, target)
  196. defer unlock()
  197. if source.closed || target.closed {
  198. return wire.StatusFileClosed
  199. }
  200. sourceShare, targetShare := source.tree.share, target.tree.share
  201. sp, tp := source.getPath(), target.getPath()
  202. if !sourceShare.CanRead(sp) || !writable(targetShare, tp) {
  203. return wire.StatusAccessDenied
  204. }
  205. length := uint64(ch.length)
  206. if st := source.handle.CheckIO(ch.source, length, false); st != wire.StatusOK {
  207. return st
  208. }
  209. if st := target.handle.CheckIO(ch.target, length, true); st != wire.StatusOK {
  210. return st
  211. }
  212. end := int64(ch.target) + int64(length)
  213. target.metaMu.Lock()
  214. growth := end - target.size
  215. target.metaMu.Unlock()
  216. if growth > 0 && !targetShare.HaveSpace(growth) {
  217. return wire.StatusDiskFull
  218. }
  219. data := buf[:ch.length]
  220. n, err := source.file.ReadAt(data, int64(ch.source))
  221. if err != nil && !errors.Is(err, io.EOF) {
  222. return statusOf(err)
  223. }
  224. if n < len(data) {
  225. //The range runs past the end of the source
  226. return wire.StatusInvalidViewSize
  227. }
  228. c.srv.leases.breakForWrite(target.handle.Key(), target.lease)
  229. if _, err := target.file.WriteAt(data, int64(ch.target)); err != nil {
  230. return statusOf(err)
  231. }
  232. target.metaMu.Lock()
  233. if end > target.size {
  234. target.size = end
  235. }
  236. target.dirty = true
  237. target.metaMu.Unlock()
  238. return wire.StatusOK
  239. }