protocol_test.go 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511
  1. package smbserver
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "errors"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "testing"
  10. "time"
  11. "imuslab.com/arozos/mod/storage/smbserver/wire"
  12. )
  13. var (
  14. shareAll = wire.ShareRead | wire.ShareWrite | wire.ShareDelete
  15. openRW = createOpts{access: wire.FileReadData | wire.FileWriteData, share: shareAll, disposition: wire.DispositionOpenIf}
  16. )
  17. func mustCreate(t *testing.T, c *rawClient, name string, o createOpts) wire.FileID {
  18. t.Helper()
  19. id, st := c.create(name, o)
  20. if st != 0 {
  21. t.Fatalf("create %s: %x", name, st)
  22. }
  23. return id
  24. }
  25. func TestDispositions(t *testing.T) {
  26. cases := []struct {
  27. name string
  28. exists bool
  29. disposition uint32
  30. wantStatus uint32
  31. wantAction uint32
  32. wantSize int
  33. }{
  34. {"open existing", true, wire.DispositionOpen, 0, wire.ActionOpened, 5},
  35. {"open missing", false, wire.DispositionOpen, wire.StatusObjectNameNotFound, 0, 0},
  36. {"create new", false, wire.DispositionCreate, 0, wire.ActionCreated, 0},
  37. {"create existing", true, wire.DispositionCreate, wire.StatusObjectNameCollision, 0, 0},
  38. {"open if existing", true, wire.DispositionOpenIf, 0, wire.ActionOpened, 5},
  39. {"open if missing", false, wire.DispositionOpenIf, 0, wire.ActionCreated, 0},
  40. {"overwrite existing", true, wire.DispositionOverwrite, 0, wire.ActionOverwritten, 0},
  41. {"overwrite missing", false, wire.DispositionOverwrite, wire.StatusObjectNameNotFound, 0, 0},
  42. {"overwrite if existing", true, wire.DispositionOverwriteIf, 0, wire.ActionOverwritten, 0},
  43. {"overwrite if missing", false, wire.DispositionOverwriteIf, 0, wire.ActionCreated, 0},
  44. {"supersede existing", true, wire.DispositionSupersede, 0, wire.ActionSuperseded, 0},
  45. {"supersede missing", false, wire.DispositionSupersede, 0, wire.ActionCreated, 0},
  46. }
  47. for _, tc := range cases {
  48. t.Run(tc.name, func(t *testing.T) {
  49. h := newHarness(t)
  50. c := newRawClient(t, h)
  51. target := filepath.Join(h.share.root, "f.txt")
  52. if tc.exists {
  53. os.WriteFile(target, []byte("hello"), 0644)
  54. }
  55. r := c.call(wire.CmdCreate, createBody("f.txt", createOpts{access: wire.FileReadData | wire.FileWriteData, share: shareAll, disposition: tc.disposition}))
  56. if r.hdr.Status != tc.wantStatus {
  57. t.Fatalf("status %x want %x", r.hdr.Status, tc.wantStatus)
  58. }
  59. if tc.wantStatus != 0 {
  60. return
  61. }
  62. if got := binary.LittleEndian.Uint32(r.body[4:]); got != tc.wantAction {
  63. t.Errorf("action %d want %d", got, tc.wantAction)
  64. }
  65. info, err := os.Stat(target)
  66. if err != nil {
  67. t.Fatal(err)
  68. }
  69. if int(info.Size()) != tc.wantSize {
  70. t.Errorf("size %d want %d", info.Size(), tc.wantSize)
  71. }
  72. })
  73. }
  74. }
  75. func TestDirectoryVersusFileOptions(t *testing.T) {
  76. h := newHarness(t)
  77. os.Mkdir(filepath.Join(h.share.root, "d"), 0755)
  78. os.WriteFile(filepath.Join(h.share.root, "f"), nil, 0644)
  79. c := newRawClient(t, h)
  80. if _, st := c.create("d", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen, options: wire.OptionNonDirectory}); st != wire.StatusFileIsADirectory {
  81. t.Errorf("folder opened as a file: %x", st)
  82. }
  83. if _, st := c.create("f", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen, options: wire.OptionDirectory}); st != wire.StatusNotADirectory {
  84. t.Errorf("file opened as a folder: %x", st)
  85. }
  86. if _, st := c.create(`missing\x`, createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionCreate}); st != wire.StatusObjectPathNotFound {
  87. t.Errorf("create under a missing folder: %x", st)
  88. }
  89. if _, st := c.create(`f\x`, createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen}); st != wire.StatusObjectPathNotFound {
  90. t.Errorf("path through a file: %x", st)
  91. }
  92. }
  93. func TestShareModeConflict(t *testing.T) {
  94. h := newHarness(t)
  95. a := newRawClient(t, h)
  96. b := newRawClient(t, h)
  97. id := mustCreate(t, a, "f.txt", createOpts{access: wire.FileWriteData, share: 0, disposition: wire.DispositionOpenIf})
  98. if _, st := b.create("f.txt", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen}); st != wire.StatusSharingViolation {
  99. t.Errorf("second open: %x", st)
  100. }
  101. if _, st := b.create("F.TXT", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen}); st != wire.StatusSharingViolation {
  102. t.Errorf("another spelling of the same file: %x", st)
  103. }
  104. a.close(id)
  105. if _, st := b.create("f.txt", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen}); st != 0 {
  106. t.Errorf("after close: %x", st)
  107. }
  108. }
  109. func TestDeleteOnClose(t *testing.T) {
  110. h := newHarness(t)
  111. target := filepath.Join(h.share.root, "f.txt")
  112. os.WriteFile(target, []byte("x"), 0644)
  113. c := newRawClient(t, h)
  114. id := mustCreate(t, c, "f.txt", createOpts{access: wire.AccessDelete | wire.FileReadAttributes, share: shareAll, disposition: wire.DispositionOpen, options: wire.OptionDeleteOnCLS})
  115. if _, err := os.Stat(target); err != nil {
  116. t.Fatal("the file must stay until the close")
  117. }
  118. c.close(id)
  119. if _, err := os.Stat(target); !os.IsNotExist(err) {
  120. t.Errorf("after close: %v", err)
  121. }
  122. }
  123. func TestDispositionInfoAndPendingDelete(t *testing.T) {
  124. h := newHarness(t)
  125. target := filepath.Join(h.share.root, "f.txt")
  126. os.WriteFile(target, []byte("x"), 0644)
  127. a := newRawClient(t, h)
  128. b := newRawClient(t, h)
  129. id := mustCreate(t, a, "f.txt", createOpts{access: wire.AccessDelete, share: shareAll, disposition: wire.DispositionOpen})
  130. if r := a.call(wire.CmdSetInfo, setInfoBody(id, wire.FileDispositionInformation, []byte{1})); r.hdr.Status != 0 {
  131. t.Fatalf("set info: %x", r.hdr.Status)
  132. }
  133. if _, st := b.create("f.txt", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen}); st != wire.StatusDeletePending {
  134. t.Errorf("open during delete: %x", st)
  135. }
  136. a.close(id)
  137. if _, err := os.Stat(target); !os.IsNotExist(err) {
  138. t.Errorf("after close: %v", err)
  139. }
  140. }
  141. func TestDeleteRefusedForNonEmptyFolder(t *testing.T) {
  142. h := newHarness(t)
  143. os.MkdirAll(filepath.Join(h.share.root, "d", "sub"), 0755)
  144. c := newRawClient(t, h)
  145. id := mustCreate(t, c, "d", createOpts{access: wire.AccessDelete, share: shareAll, disposition: wire.DispositionOpen, options: wire.OptionDirectory})
  146. if r := c.call(wire.CmdSetInfo, setInfoBody(id, wire.FileDispositionInformation, []byte{1})); r.hdr.Status != wire.StatusDirectoryNotEmpty {
  147. t.Errorf("status %x", r.hdr.Status)
  148. }
  149. }
  150. func renameData(name string, replace bool) []byte {
  151. encoded := wire.EncodeUTF16(name)
  152. w := wire.NewWriter(20 + len(encoded))
  153. if replace {
  154. w.U8(1)
  155. } else {
  156. w.U8(0)
  157. }
  158. w.Zero(7)
  159. w.U64(0)
  160. w.U32(uint32(len(encoded)))
  161. w.Bytes(encoded)
  162. return w.B
  163. }
  164. func TestRenameKeepsTheHandle(t *testing.T) {
  165. h := newHarness(t)
  166. c := newRawClient(t, h)
  167. id := mustCreate(t, c, "old.txt", createOpts{access: wire.FileWriteData | wire.AccessDelete, share: shareAll, disposition: wire.DispositionCreate})
  168. if r := c.call(wire.CmdSetInfo, setInfoBody(id, wire.FileRenameInformation, renameData("new.txt", false))); r.hdr.Status != 0 {
  169. t.Fatalf("rename: %x", r.hdr.Status)
  170. }
  171. if r := c.call(wire.CmdWrite, writeBodyOf(id, 0, []byte("after"))); r.hdr.Status != 0 {
  172. t.Fatalf("write: %x", r.hdr.Status)
  173. }
  174. c.close(id)
  175. got, err := os.ReadFile(filepath.Join(h.share.root, "new.txt"))
  176. if err != nil || string(got) != "after" {
  177. t.Errorf("new.txt = %q, %v", got, err)
  178. }
  179. }
  180. func TestRenameChangingOnlyCase(t *testing.T) {
  181. h := newHarness(t)
  182. os.WriteFile(filepath.Join(h.share.root, "name.txt"), []byte("x"), 0644)
  183. c := newRawClient(t, h)
  184. id := mustCreate(t, c, "name.txt", createOpts{access: wire.AccessDelete, share: shareAll, disposition: wire.DispositionOpen})
  185. if r := c.call(wire.CmdSetInfo, setInfoBody(id, wire.FileRenameInformation, renameData("NAME.TXT", false))); r.hdr.Status != 0 {
  186. t.Fatalf("rename: %x", r.hdr.Status)
  187. }
  188. c.close(id)
  189. entries, _ := os.ReadDir(h.share.root)
  190. if len(entries) != 1 || entries[0].Name() != "NAME.TXT" {
  191. t.Errorf("entries = %v", entries)
  192. }
  193. }
  194. func TestRenameReplaceAndCollision(t *testing.T) {
  195. h := newHarness(t)
  196. os.WriteFile(filepath.Join(h.share.root, "a"), []byte("a"), 0644)
  197. os.WriteFile(filepath.Join(h.share.root, "b"), []byte("b"), 0644)
  198. c := newRawClient(t, h)
  199. id := mustCreate(t, c, "a", createOpts{access: wire.AccessDelete, share: shareAll, disposition: wire.DispositionOpen})
  200. if r := c.call(wire.CmdSetInfo, setInfoBody(id, wire.FileRenameInformation, renameData("b", false))); r.hdr.Status != wire.StatusObjectNameCollision {
  201. t.Errorf("without replace: %x", r.hdr.Status)
  202. }
  203. if r := c.call(wire.CmdSetInfo, setInfoBody(id, wire.FileRenameInformation, renameData("b", true))); r.hdr.Status != 0 {
  204. t.Errorf("with replace: %x", r.hdr.Status)
  205. }
  206. c.close(id)
  207. if got, _ := os.ReadFile(filepath.Join(h.share.root, "b")); string(got) != "a" {
  208. t.Errorf("b = %q", got)
  209. }
  210. }
  211. func TestRenameNeedsDeleteAccess(t *testing.T) {
  212. h := newHarness(t)
  213. os.WriteFile(filepath.Join(h.share.root, "a"), []byte("a"), 0644)
  214. c := newRawClient(t, h)
  215. id := mustCreate(t, c, "a", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen})
  216. if r := c.call(wire.CmdSetInfo, setInfoBody(id, wire.FileRenameInformation, renameData("b", false))); r.hdr.Status != wire.StatusAccessDenied {
  217. t.Errorf("status %x", r.hdr.Status)
  218. }
  219. }
  220. func TestLocksBetweenClients(t *testing.T) {
  221. h := newHarness(t)
  222. a := newRawClient(t, h)
  223. b := newRawClient(t, h)
  224. ida := mustCreate(t, a, "f", openRW)
  225. idb := mustCreate(t, b, "f", openRW)
  226. a.call(wire.CmdWrite, writeBodyOf(ida, 0, make([]byte, 100)))
  227. if r := a.call(wire.CmdLock, lockBody(ida, 0, 10, wire.LockExclusive|wire.LockFailImmediately)); r.hdr.Status != 0 {
  228. t.Fatalf("lock: %x", r.hdr.Status)
  229. }
  230. if r := b.call(wire.CmdLock, lockBody(idb, 5, 2, wire.LockExclusive|wire.LockFailImmediately)); r.hdr.Status != wire.StatusLockNotGranted {
  231. t.Errorf("conflicting lock: %x", r.hdr.Status)
  232. }
  233. if r := b.call(wire.CmdRead, readBodyOf(idb, 0, 4)); r.hdr.Status != wire.StatusFileLockConflict {
  234. t.Errorf("read under a lock: %x", r.hdr.Status)
  235. }
  236. if r := b.call(wire.CmdWrite, writeBodyOf(idb, 0, []byte{1})); r.hdr.Status != wire.StatusFileLockConflict {
  237. t.Errorf("write under a lock: %x", r.hdr.Status)
  238. }
  239. if r := a.call(wire.CmdRead, readBodyOf(ida, 0, 4)); r.hdr.Status != 0 {
  240. t.Errorf("the owner must still read: %x", r.hdr.Status)
  241. }
  242. if r := b.call(wire.CmdRead, readBodyOf(idb, 50, 4)); r.hdr.Status != 0 {
  243. t.Errorf("outside the range: %x", r.hdr.Status)
  244. }
  245. if r := a.call(wire.CmdLock, lockBody(ida, 0, 10, wire.LockUnlock)); r.hdr.Status != 0 {
  246. t.Fatalf("unlock: %x", r.hdr.Status)
  247. }
  248. if r := b.call(wire.CmdRead, readBodyOf(idb, 0, 4)); r.hdr.Status != 0 {
  249. t.Errorf("after unlock: %x", r.hdr.Status)
  250. }
  251. }
  252. func TestBlockingLockWaitsForTheHolder(t *testing.T) {
  253. h := newHarness(t)
  254. a := newRawClient(t, h)
  255. b := newRawClient(t, h)
  256. ida := mustCreate(t, a, "f", openRW)
  257. idb := mustCreate(t, b, "f", openRW)
  258. a.call(wire.CmdLock, lockBody(ida, 0, 10, wire.LockExclusive|wire.LockFailImmediately))
  259. msg := b.message(wire.CmdLock, lockBody(idb, 0, 10, wire.LockExclusive), 0)
  260. b.signer.Sign(msg)
  261. b.writeFrame(msg)
  262. interim := parseReplies(t, b.readFrame())[0]
  263. if interim.hdr.Status != wire.StatusPending || interim.hdr.Flags&wire.FlagAsync == 0 {
  264. t.Fatalf("interim: %+v", interim.hdr)
  265. }
  266. a.call(wire.CmdLock, lockBody(ida, 0, 10, wire.LockUnlock))
  267. final := parseReplies(t, b.readFrame())[0]
  268. if final.hdr.Status != 0 {
  269. t.Errorf("final: %x", final.hdr.Status)
  270. }
  271. if final.hdr.AsyncID != interim.hdr.AsyncID {
  272. t.Error("the final reply must carry the async id")
  273. }
  274. b.verify(final)
  275. }
  276. func TestChangeNotifyPendsAndCancels(t *testing.T) {
  277. h := newHarness(t)
  278. c := newRawClient(t, h)
  279. id := mustCreate(t, c, "", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen, options: wire.OptionDirectory})
  280. msg := c.message(wire.CmdChangeNotify, notifyBody(id), 0)
  281. mid := binary.LittleEndian.Uint64(msg[24:])
  282. c.signer.Sign(msg)
  283. c.writeFrame(msg)
  284. interim := parseReplies(t, c.readFrame())[0]
  285. if interim.hdr.Status != wire.StatusPending {
  286. t.Fatalf("interim: %x", interim.hdr.Status)
  287. }
  288. if interim.hdr.Flags&wire.FlagSigned != 0 {
  289. t.Error("an interim response is not signed, as Samba and Windows do")
  290. }
  291. //CANCEL reuses the message id and takes no credit
  292. h2 := wire.Header{Command: wire.CmdCancel, MessageID: mid, SessionID: c.session, Flags: wire.FlagAsync, AsyncID: interim.hdr.AsyncID}
  293. cancel := make([]byte, wire.HeaderSize+4)
  294. h2.Put(cancel)
  295. cancel[wire.HeaderSize] = 4
  296. c.signer.Sign(cancel)
  297. c.writeFrame(cancel)
  298. final := parseReplies(t, c.readFrame())[0]
  299. if final.hdr.Status != wire.StatusCancelled {
  300. t.Errorf("final: %x", final.hdr.Status)
  301. }
  302. c.verify(final)
  303. }
  304. func TestClosingAFolderEndsItsNotify(t *testing.T) {
  305. h := newHarness(t)
  306. c := newRawClient(t, h)
  307. id := mustCreate(t, c, "", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen, options: wire.OptionDirectory})
  308. msg := c.message(wire.CmdChangeNotify, notifyBody(id), 0)
  309. c.signer.Sign(msg)
  310. c.writeFrame(msg)
  311. parseReplies(t, c.readFrame())
  312. closeMsg := c.message(wire.CmdClose, closeBody(id), 0)
  313. c.signer.Sign(closeMsg)
  314. c.writeFrame(closeMsg)
  315. seen := map[uint32]bool{}
  316. for i := 0; i < 2; i++ {
  317. r := parseReplies(t, c.readFrame())[0]
  318. seen[r.hdr.Status] = true
  319. c.verify(r)
  320. }
  321. if !seen[wire.StatusNotifyCleanup] || !seen[0] {
  322. t.Errorf("statuses = %v", seen)
  323. }
  324. }
  325. // compound links messages the way Windows does.
  326. func (c *rawClient) compound(related bool, parts ...struct {
  327. cmd uint16
  328. body []byte
  329. }) []rawReply {
  330. c.t.Helper()
  331. msgs := [][]byte{}
  332. for i, p := range parts {
  333. flags := uint32(0)
  334. if related && i > 0 {
  335. flags = wire.FlagRelated
  336. }
  337. m := c.message(p.cmd, p.body, flags)
  338. if related && i > 0 {
  339. binary.LittleEndian.PutUint64(m[40:], ^uint64(0))
  340. binary.LittleEndian.PutUint32(m[36:], ^uint32(0))
  341. }
  342. if i < len(parts)-1 {
  343. for len(m)%8 != 0 {
  344. m = append(m, 0)
  345. }
  346. binary.LittleEndian.PutUint32(m[20:], uint32(len(m)))
  347. }
  348. msgs = append(msgs, m)
  349. }
  350. frame := []byte{}
  351. for _, m := range msgs {
  352. c.signer.Sign(m)
  353. frame = append(frame, m...)
  354. }
  355. c.writeFrame(frame)
  356. return parseReplies(c.t, c.readFrame())
  357. }
  358. func previous() wire.FileID {
  359. var id wire.FileID
  360. for i := range id {
  361. id[i] = 0xFF
  362. }
  363. return id
  364. }
  365. type compoundPart = struct {
  366. cmd uint16
  367. body []byte
  368. }
  369. func TestCompoundCreateQueryClose(t *testing.T) {
  370. h := newHarness(t)
  371. os.WriteFile(filepath.Join(h.share.root, "f.txt"), []byte("hello"), 0644)
  372. c := newRawClient(t, h)
  373. replies := c.compound(true,
  374. compoundPart{wire.CmdCreate, createBody("f.txt", createOpts{access: wire.FileReadAttributes | wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen})},
  375. compoundPart{wire.CmdQueryInfo, queryInfoBody(previous(), wire.InfoFile, wire.FileStandardInformation, 0)},
  376. compoundPart{wire.CmdClose, closeBody(previous())},
  377. )
  378. if len(replies) != 3 {
  379. t.Fatalf("%d replies", len(replies))
  380. }
  381. for i, r := range replies {
  382. if r.hdr.Status != 0 {
  383. t.Errorf("part %d: %x", i, r.hdr.Status)
  384. }
  385. c.verify(r)
  386. if i > 0 && r.hdr.Flags&wire.FlagRelated == 0 {
  387. t.Errorf("part %d: the related flag must come back", i)
  388. }
  389. }
  390. if got := binary.LittleEndian.Uint64(replies[1].body[8+8:]); got != 5 {
  391. t.Errorf("size = %d", got)
  392. }
  393. }
  394. func TestCompoundFailedCreatePassesItsErrorOn(t *testing.T) {
  395. h := newHarness(t)
  396. c := newRawClient(t, h)
  397. replies := c.compound(true,
  398. compoundPart{wire.CmdCreate, createBody("missing.txt", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen})},
  399. compoundPart{wire.CmdQueryInfo, queryInfoBody(previous(), wire.InfoFile, wire.FileStandardInformation, 0)},
  400. compoundPart{wire.CmdClose, closeBody(previous())},
  401. )
  402. for i, r := range replies {
  403. if r.hdr.Status != wire.StatusObjectNameNotFound {
  404. t.Errorf("part %d: %x", i, r.hdr.Status)
  405. }
  406. }
  407. }
  408. // Windows 11 asks for directory class 81 twice in one compound, and falls back
  409. // to class 37 when both are refused. Seen in a real session.
  410. func TestWindows11DirectoryFallback(t *testing.T) {
  411. h := newHarness(t)
  412. os.WriteFile(filepath.Join(h.share.root, "f.txt"), nil, 0644)
  413. c := newRawClient(t, h)
  414. id := mustCreate(t, c, "", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen, options: wire.OptionDirectory})
  415. const class81 = 81
  416. replies := c.compound(false,
  417. compoundPart{wire.CmdQueryDirectory, queryDirBody(id, class81, 0, "*")},
  418. compoundPart{wire.CmdQueryDirectory, queryDirBody(id, class81, 0, "*")},
  419. )
  420. for i, r := range replies {
  421. if r.hdr.Status != wire.StatusInvalidInfoClass {
  422. t.Errorf("class 81 part %d: %x", i, r.hdr.Status)
  423. }
  424. }
  425. replies = c.compound(false,
  426. compoundPart{wire.CmdQueryDirectory, queryDirBody(id, wire.FileIdBothDirectoryInformation, 0, "*")},
  427. compoundPart{wire.CmdQueryDirectory, queryDirBody(id, wire.FileIdBothDirectoryInformation, 0, "*")},
  428. )
  429. if replies[0].hdr.Status != 0 || replies[1].hdr.Status != wire.StatusNoMoreFiles {
  430. t.Errorf("class 37: %x %x", replies[0].hdr.Status, replies[1].hdr.Status)
  431. }
  432. if !bytes.Contains(replies[0].body, wire.EncodeUTF16("f.txt")) {
  433. t.Error("the listing must hold the file")
  434. }
  435. }
  436. func TestDirectoryStatuses(t *testing.T) {
  437. h := newHarness(t)
  438. os.WriteFile(filepath.Join(h.share.root, "a.txt"), nil, 0644)
  439. c := newRawClient(t, h)
  440. id := mustCreate(t, c, "", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen, options: wire.OptionDirectory})
  441. cls := wire.FileBothDirectoryInformation
  442. if r := c.call(wire.CmdQueryDirectory, queryDirBody(id, cls, wire.RestartScans, "nothing-matches")); r.hdr.Status != wire.StatusNoSuchFile {
  443. t.Errorf("no match: %x", r.hdr.Status)
  444. }
  445. if r := c.call(wire.CmdQueryDirectory, queryDirBody(id, cls, wire.RestartScans, "A.TXT")); r.hdr.Status != 0 {
  446. t.Errorf("exact name in another case: %x", r.hdr.Status)
  447. }
  448. if r := c.call(wire.CmdQueryDirectory, queryDirBody(id, cls, 0, "")); r.hdr.Status != wire.StatusNoMoreFiles {
  449. t.Errorf("end of listing: %x", r.hdr.Status)
  450. }
  451. if r := c.call(wire.CmdQueryDirectory, queryDirBody(id, cls, wire.RestartScans, "*.txt")); r.hdr.Status != 0 {
  452. t.Errorf("after restart: %x", r.hdr.Status)
  453. }
  454. }
  455. func TestEveryDirectoryClassLists(t *testing.T) {
  456. h := newHarness(t)
  457. os.WriteFile(filepath.Join(h.share.root, "abc.txt"), nil, 0644)
  458. c := newRawClient(t, h)
  459. id := mustCreate(t, c, "", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen, options: wire.OptionDirectory})
  460. for _, class := range []uint8{
  461. wire.FileDirectoryInformation, wire.FileFullDirectoryInformation, wire.FileBothDirectoryInformation,
  462. wire.FileNamesInformation, wire.FileIdBothDirectoryInformation, wire.FileIdFullDirectoryInformation,
  463. } {
  464. r := c.call(wire.CmdQueryDirectory, queryDirBody(id, class, wire.RestartScans, "abc.txt"))
  465. if r.hdr.Status != 0 {
  466. t.Errorf("class %d: %x", class, r.hdr.Status)
  467. continue
  468. }
  469. data := r.body[8:]
  470. fixed := entrySize(class)
  471. want := wire.EncodeUTF16("abc.txt")
  472. if len(data) != fixed+len(want) || !bytes.Equal(data[fixed:], want) {
  473. t.Errorf("class %d: the name is not where the layout says, %d bytes", class, len(data))
  474. }
  475. }
  476. }
  477. // plainShare hides every optional ability of a share, such as streams.
  478. type plainShare struct{ Share }
  479. func TestStreamOpensAreRefusedCleanly(t *testing.T) {
  480. h := newHarness(t)
  481. os.WriteFile(filepath.Join(h.share.root, "sample.bin"), []byte("x"), 0644)
  482. //A drive without streams; refusing the name tells Windows to drop the
  483. //stream from a copy
  484. h.backend.shares = []Share{plainShare{h.share}}
  485. c := newRawClient(t, h)
  486. o := createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen}
  487. if _, st := c.create("sample.bin:Zone.Identifier", o); st != wire.StatusObjectNameInvalid {
  488. t.Errorf("named stream: %x", st)
  489. }
  490. id, st := c.create("sample.bin::$DATA", o)
  491. if st != 0 {
  492. t.Fatalf("default stream: %x", st)
  493. }
  494. c.close(id)
  495. }
  496. func TestInfoClassLayouts(t *testing.T) {
  497. h := newHarness(t)
  498. os.WriteFile(filepath.Join(h.share.root, "f.txt"), []byte("12345"), 0644)
  499. c := newRawClient(t, h)
  500. id := mustCreate(t, c, "f.txt", createOpts{access: wire.FileReadData | wire.FileReadAttributes | wire.ReadControl, share: shareAll, disposition: wire.DispositionOpen})
  501. cases := []struct {
  502. name string
  503. class uint8
  504. size int
  505. }{
  506. {"basic", wire.FileBasicInformation, 40},
  507. {"standard", wire.FileStandardInformation, 24},
  508. {"internal", wire.FileInternalInformation, 8},
  509. {"ea", wire.FileEaInformation, 4},
  510. {"access", wire.FileAccessInformation, 4},
  511. {"network open", wire.FileNetworkOpenInformation, 56},
  512. {"attribute tag", wire.FileAttributeTagInformation, 8},
  513. {"position", wire.FilePositionInformation, 8},
  514. {"mode", wire.FileModeInformation, 4},
  515. {"alignment", wire.FileAlignmentInformation, 4},
  516. }
  517. for _, tc := range cases {
  518. t.Run(tc.name, func(t *testing.T) {
  519. r := c.call(wire.CmdQueryInfo, queryInfoBody(id, wire.InfoFile, tc.class, 0))
  520. if r.hdr.Status != 0 {
  521. t.Fatalf("status %x", r.hdr.Status)
  522. }
  523. if got := int(binary.LittleEndian.Uint32(r.body[4:])); got != tc.size {
  524. t.Errorf("size %d want %d", got, tc.size)
  525. }
  526. })
  527. }
  528. r := c.call(wire.CmdQueryInfo, queryInfoBody(id, wire.InfoFile, wire.FileAllInformation, 0))
  529. data := r.body[8:]
  530. nameLen := binary.LittleEndian.Uint32(data[96:])
  531. if got, _ := wire.DecodeUTF16(data[100 : 100+nameLen]); got != `\f.txt` {
  532. t.Errorf("all information name = %q", got)
  533. }
  534. r = c.call(wire.CmdQueryInfo, queryInfoBody(id, wire.InfoFile, wire.FileStreamInformation, 0))
  535. if !bytes.Contains(r.body, wire.EncodeUTF16("::$DATA")) {
  536. t.Error("a file has a default stream")
  537. }
  538. r = c.call(wire.CmdQueryInfo, queryInfoBody(id, wire.InfoFile, 200, 0))
  539. if r.hdr.Status != wire.StatusInvalidInfoClass {
  540. t.Errorf("unknown class: %x", r.hdr.Status)
  541. }
  542. }
  543. func TestCreditsLetAClientGrow(t *testing.T) {
  544. w := creditWindow{high: 1, used: map[uint64]struct{}{}}
  545. cases := []struct {
  546. name string
  547. requested, charge uint16
  548. loggedIn bool
  549. want uint16
  550. }{
  551. //What Windows sent during a copy, and what Samba answered
  552. {"1 MiB read", 16, 16, false, 31},
  553. {"small request", 1, 1, false, 1},
  554. {"asks for nothing", 0, 1, false, 1},
  555. {"asks for a little more", 8, 1, false, 8},
  556. {"a request is capped", 500, 1, false, 33},
  557. {"end of a login", 512, 1, true, 512},
  558. }
  559. for _, c := range cases {
  560. t.Run(c.name, func(t *testing.T) {
  561. if got := w.grant(c.requested, c.charge, c.loggedIn); got != c.want {
  562. t.Errorf("got %d want %d", got, c.want)
  563. }
  564. })
  565. }
  566. }
  567. // A copy must be able to reach many reads in flight. With a balance that only
  568. // repays what was spent, Windows has one read on the wire at a time.
  569. func TestCreditBalanceGrowsDuringACopy(t *testing.T) {
  570. w := creditWindow{high: 1, used: map[uint64]struct{}{}}
  571. balance := func() uint64 { return w.high - w.low - uint64(len(w.used)) }
  572. w.grant(1, 1, true)
  573. mid := w.low
  574. reachedPipeline := false
  575. for i := 0; i < 400; i++ {
  576. if balance() < 16 {
  577. w.grant(16, 1, false) //Not yet enough for a large read
  578. continue
  579. }
  580. if !w.consume(mid, 16) {
  581. t.Fatalf("read %d refused at balance %d", i, balance())
  582. }
  583. mid += 16
  584. w.grant(16, 16, false)
  585. if balance() >= 16*8 {
  586. reachedPipeline = true
  587. }
  588. }
  589. if !reachedPipeline {
  590. t.Errorf("the balance stopped at %d, under 8 reads in flight", balance())
  591. }
  592. if balance() > maxCredits {
  593. t.Errorf("the balance %d passed the limit", balance())
  594. }
  595. }
  596. func TestCreditLimitIsHeld(t *testing.T) {
  597. w := creditWindow{high: maxCredits, used: map[uint64]struct{}{}}
  598. if got := w.grant(100, 1, false); got != 0 {
  599. t.Errorf("granted %d past the limit", got)
  600. }
  601. }
  602. // A client that behaves like Windows during a copy: 1 MiB reads, asking for
  603. // exactly the 16 credits each one costs, with as many in flight as its balance
  604. // allows. Before the credit fix this stayed at one read in flight, which held a
  605. // real copy to 20 MiB/s on a link with a 33 ms round trip.
  606. func TestWindowsStyleCopyPipelines(t *testing.T) {
  607. h := newHarness(t)
  608. const fileSize = 64 << 20
  609. f, err := os.Create(filepath.Join(h.share.root, "big.bin"))
  610. if err != nil {
  611. t.Fatal(err)
  612. }
  613. f.Truncate(fileSize)
  614. f.Close()
  615. c := newRawClient(t, h)
  616. id := mustCreate(t, c, "big.bin", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen})
  617. const (
  618. readSize = 1 << 20
  619. cost = 16
  620. reads = 300
  621. )
  622. balance := 8 //What the last reply in newRawClient granted
  623. inFlight, peak, sent, done := 0, 0, 0, 0
  624. for done < reads {
  625. for balance >= cost && sent < reads {
  626. hdr := wire.Header{Command: wire.CmdRead, Credits: cost, CreditCharge: cost, MessageID: c.mid, SessionID: c.session, TreeID: c.tree}
  627. c.mid += cost
  628. body := readBodyOf(id, uint64(sent%64)*readSize, readSize)
  629. msg := make([]byte, wire.HeaderSize+len(body))
  630. hdr.Put(msg)
  631. copy(msg[wire.HeaderSize:], body)
  632. c.signer.Sign(msg)
  633. c.writeFrame(msg)
  634. balance -= cost
  635. sent++
  636. inFlight++
  637. }
  638. if inFlight > peak {
  639. peak = inFlight
  640. }
  641. if inFlight == 0 {
  642. //Too poor for one read: a small request tops the balance up
  643. r := c.call(wire.CmdEcho, []byte{4, 0, 0, 0})
  644. balance += int(r.hdr.Credits) - 1
  645. continue
  646. }
  647. r := parseReplies(t, c.readFrame())[0]
  648. if r.hdr.Status != 0 {
  649. t.Fatalf("read %d: %x", done, r.hdr.Status)
  650. }
  651. balance += int(r.hdr.Credits)
  652. inFlight--
  653. done++
  654. }
  655. if peak < 16 {
  656. t.Errorf("only %d reads in flight, a copy would be held to a few per round trip", peak)
  657. }
  658. t.Logf("peak %d reads in flight, final balance %d", peak, balance)
  659. }
  660. func TestRenameThroughOneHandleReachesTheOther(t *testing.T) {
  661. h := newHarness(t)
  662. c := newRawClient(t, h)
  663. writer := mustCreate(t, c, "a.tmp", createOpts{access: wire.FileWriteData | wire.FileReadAttributes, share: shareAll, disposition: wire.DispositionCreate})
  664. mover := mustCreate(t, c, "a.tmp", createOpts{access: wire.AccessDelete, share: shareAll, disposition: wire.DispositionOpen})
  665. if r := c.call(wire.CmdSetInfo, setInfoBody(mover, wire.FileRenameInformation, renameData("doc.docx", false))); r.hdr.Status != 0 {
  666. t.Fatalf("rename: %x", r.hdr.Status)
  667. }
  668. if r := c.call(wire.CmdQueryInfo, queryInfoBody(writer, wire.InfoFile, wire.FileStandardInformation, 0)); r.hdr.Status != 0 {
  669. t.Errorf("the first handle lost its file: %x", r.hdr.Status)
  670. }
  671. if r := c.call(wire.CmdWrite, writeBodyOf(writer, 0, []byte("still here"))); r.hdr.Status != 0 {
  672. t.Errorf("write after rename: %x", r.hdr.Status)
  673. }
  674. c.close(mover)
  675. c.close(writer)
  676. if got, _ := os.ReadFile(filepath.Join(h.share.root, "doc.docx")); string(got) != "still here" {
  677. t.Errorf("doc.docx = %q", got)
  678. }
  679. }
  680. func ioctlBody(id wire.FileID, code uint32, maxOut uint32) []byte {
  681. w := wire.NewWriter(56)
  682. w.U16(57)
  683. w.U16(0)
  684. w.U32(code)
  685. w.Bytes(id[:])
  686. w.U32(wire.HeaderSize + 56)
  687. w.U32(0)
  688. w.U32(0)
  689. w.U32(wire.HeaderSize + 56)
  690. w.U32(0)
  691. w.U32(maxOut)
  692. w.U32(wire.IoctlIsFsctl)
  693. w.U32(0)
  694. return w.B
  695. }
  696. func TestObjectIDs(t *testing.T) {
  697. h := newHarness(t)
  698. os.WriteFile(filepath.Join(h.share.root, "a.txt"), nil, 0644)
  699. os.WriteFile(filepath.Join(h.share.root, "b.txt"), nil, 0644)
  700. c := newRawClient(t, h)
  701. id := mustCreate(t, c, "a.txt", createOpts{access: wire.FileReadAttributes, share: shareAll, disposition: wire.DispositionOpen})
  702. other := mustCreate(t, c, "b.txt", createOpts{access: wire.FileReadAttributes, share: shareAll, disposition: wire.DispositionOpen})
  703. object := func(f wire.FileID) []byte {
  704. t.Helper()
  705. r := c.call(wire.CmdIoctl, ioctlBody(f, wire.FsctlCreateOrGetObjectID, 64))
  706. if r.hdr.Status != 0 {
  707. t.Fatalf("status %x", r.hdr.Status)
  708. }
  709. if got := binary.LittleEndian.Uint32(r.body[36:]); got != 64 {
  710. t.Fatalf("output %d bytes", got)
  711. }
  712. return r.body[48:]
  713. }
  714. first := object(id)
  715. if !bytes.Equal(first, object(id)) {
  716. t.Error("an object id must be stable")
  717. }
  718. if bytes.Equal(first[:16], object(other)[:16]) {
  719. t.Error("two files must differ")
  720. }
  721. if !bytes.Equal(first[:16], first[32:48]) {
  722. t.Error("the birth id starts as the object id")
  723. }
  724. root := mustCreate(t, c, "", createOpts{access: wire.FileReadAttributes, share: shareAll, disposition: wire.DispositionOpen, options: wire.OptionDirectory})
  725. r := c.call(wire.CmdQueryInfo, queryInfoBody(root, wire.InfoFilesystem, wire.FileFsObjectIdInformation, 0))
  726. if r.hdr.Status != 0 || binary.LittleEndian.Uint32(r.body[4:]) != 64 {
  727. t.Errorf("volume id: %x", r.hdr.Status)
  728. }
  729. if !bytes.Equal(first[16:32], r.body[8:24]) {
  730. t.Error("the volume ids must agree")
  731. }
  732. }
  733. func TestFilesystemInfo(t *testing.T) {
  734. h := newHarness(t)
  735. c := newRawClient(t, h)
  736. id := mustCreate(t, c, "", createOpts{access: wire.FileReadData | wire.FileReadAttributes, share: shareAll, disposition: wire.DispositionOpen, options: wire.OptionDirectory})
  737. r := c.call(wire.CmdQueryInfo, queryInfoBody(id, wire.InfoFilesystem, wire.FileFsFullSizeInformation, 0))
  738. if r.hdr.Status != 0 {
  739. t.Fatalf("full size: %x", r.hdr.Status)
  740. }
  741. data := r.body[8:]
  742. if got := binary.LittleEndian.Uint64(data) * clusterSize; got != 1<<40 {
  743. t.Errorf("total = %d", got)
  744. }
  745. if got := binary.LittleEndian.Uint64(data[8:]) * clusterSize; got != 1<<39 {
  746. t.Errorf("free = %d", got)
  747. }
  748. r = c.call(wire.CmdQueryInfo, queryInfoBody(id, wire.InfoFilesystem, wire.FileFsAttributeInformation, 0))
  749. data = r.body[8:]
  750. flags := binary.LittleEndian.Uint32(data)
  751. const namedStreams = 0x00040000
  752. if flags&namedStreams == 0 {
  753. t.Errorf("flags %x: the test drive keeps streams, so it must say so", flags)
  754. }
  755. if flags&fsObjectIDs == 0 {
  756. t.Error("link tracking needs object ids")
  757. }
  758. if flags&fsPersistentACLs == 0 {
  759. t.Error("without persistent ACLs Explorer hides the Security tab")
  760. }
  761. for _, class := range []uint8{wire.FileFsVolumeInformation, wire.FileFsSizeInformation, wire.FileFsDeviceInformation, wire.FileFsSectorSizeInformation} {
  762. if r := c.call(wire.CmdQueryInfo, queryInfoBody(id, wire.InfoFilesystem, class, 0)); r.hdr.Status != 0 {
  763. t.Errorf("class %d: %x", class, r.hdr.Status)
  764. }
  765. }
  766. }
  767. func TestSecurityDescriptor(t *testing.T) {
  768. h := newHarness(t)
  769. os.WriteFile(filepath.Join(h.share.root, "f.txt"), nil, 0644)
  770. c := newRawClient(t, h)
  771. id := mustCreate(t, c, "f.txt", createOpts{access: wire.ReadControl, share: shareAll, disposition: wire.DispositionOpen})
  772. r := c.call(wire.CmdQueryInfo, queryInfoBody(id, wire.InfoSecurity, 0, secOwner|secGroup|secDACL))
  773. if r.hdr.Status != 0 {
  774. t.Fatalf("status %x", r.hdr.Status)
  775. }
  776. sd := r.body[8:]
  777. owner := wire.UserSID(h.srv.machineSID, testUserName).Bytes()
  778. ownerAt := binary.LittleEndian.Uint32(sd[4:])
  779. if !bytes.Equal(sd[ownerAt:int(ownerAt)+len(owner)], owner) {
  780. t.Error("the owner must be the connected user")
  781. }
  782. daclAt := binary.LittleEndian.Uint32(sd[16:])
  783. if mask := binary.LittleEndian.Uint32(sd[daclAt+8+4:]); mask != wire.FileAllAccess {
  784. t.Errorf("mask = %x", mask)
  785. }
  786. //Windows reads the DACL alone too, and then there is no owner
  787. r = c.call(wire.CmdQueryInfo, queryInfoBody(id, wire.InfoSecurity, 0, secDACL))
  788. sd = r.body[8:]
  789. if binary.LittleEndian.Uint32(sd[4:]) != 0 {
  790. t.Error("an owner that was not asked for")
  791. }
  792. }
  793. func TestMaximalAccessContext(t *testing.T) {
  794. h := newHarness(t)
  795. os.WriteFile(filepath.Join(h.share.root, "f.txt"), nil, 0644)
  796. c := newRawClient(t, h)
  797. ctx := wire.NewWriter(32)
  798. ctx.U32(0)
  799. ctx.U16(16)
  800. ctx.U16(4)
  801. ctx.U16(0)
  802. ctx.U16(0)
  803. ctx.U32(0)
  804. ctx.Bytes([]byte("MxAc"))
  805. ctx.Zero(4)
  806. build := func() []byte {
  807. body := createBody("f.txt", createOpts{access: wire.FileReadAttributes, share: shareAll, disposition: wire.DispositionOpen})
  808. for len(body)%8 != 0 {
  809. body = append(body, 0)
  810. }
  811. binary.LittleEndian.PutUint32(body[48:], uint32(wire.HeaderSize+len(body)))
  812. binary.LittleEndian.PutUint32(body[52:], uint32(ctx.Len()))
  813. return append(body, ctx.B...)
  814. }
  815. maximal := func() uint32 {
  816. t.Helper()
  817. r := c.call(wire.CmdCreate, build())
  818. if r.hdr.Status != 0 {
  819. t.Fatalf("create: %x", r.hdr.Status)
  820. }
  821. return binary.LittleEndian.Uint32(r.body[88+24+4:])
  822. }
  823. if got := maximal(); got != wire.FileAllAccess {
  824. t.Errorf("writable: %x", got)
  825. }
  826. h.share.mu.Lock()
  827. h.share.denyWrite["f.txt"] = true
  828. h.share.mu.Unlock()
  829. if got := maximal(); got != wire.ReadOnlyAccess {
  830. t.Errorf("read only: %x", got)
  831. }
  832. }
  833. func TestSystemSecurityIsRefused(t *testing.T) {
  834. h := newHarness(t)
  835. os.WriteFile(filepath.Join(h.share.root, "f.txt"), nil, 0644)
  836. c := newRawClient(t, h)
  837. if _, st := c.create("f.txt", createOpts{access: wire.AccessSystemSec, share: shareAll, disposition: wire.DispositionOpen}); st != wire.StatusPrivilegeNotHeld {
  838. t.Errorf("status %x", st)
  839. }
  840. }
  841. func TestReadAtEndOfFile(t *testing.T) {
  842. h := newHarness(t)
  843. os.WriteFile(filepath.Join(h.share.root, "f.txt"), []byte("abc"), 0644)
  844. c := newRawClient(t, h)
  845. id := mustCreate(t, c, "f.txt", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen})
  846. if r := c.call(wire.CmdRead, readBodyOf(id, 3, 10)); r.hdr.Status != wire.StatusEndOfFile {
  847. t.Errorf("at the end: %x", r.hdr.Status)
  848. }
  849. r := c.call(wire.CmdRead, readBodyOf(id, 1, 10))
  850. if r.hdr.Status != 0 {
  851. t.Fatalf("short read: %x", r.hdr.Status)
  852. }
  853. if got := binary.LittleEndian.Uint32(r.body[4:]); got != 2 {
  854. t.Errorf("length %d", got)
  855. }
  856. if !bytes.Equal(r.body[16:], []byte("bc")) {
  857. t.Errorf("data %q", r.body[16:])
  858. }
  859. }
  860. func TestReadWithoutReadAccess(t *testing.T) {
  861. h := newHarness(t)
  862. c := newRawClient(t, h)
  863. id := mustCreate(t, c, "f.txt", createOpts{access: wire.FileWriteData, share: shareAll, disposition: wire.DispositionCreate})
  864. if r := c.call(wire.CmdRead, readBodyOf(id, 0, 1)); r.hdr.Status != wire.StatusAccessDenied {
  865. t.Errorf("status %x", r.hdr.Status)
  866. }
  867. }
  868. func TestSetTimeSurvivesClose(t *testing.T) {
  869. h := newHarness(t)
  870. c := newRawClient(t, h)
  871. id := mustCreate(t, c, "f.txt", createOpts{access: wire.FileWriteData | wire.FileWriteAttributes, share: shareAll, disposition: wire.DispositionCreate})
  872. when := time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC)
  873. basic := wire.NewWriter(40)
  874. basic.U64(0)
  875. basic.U64(0)
  876. basic.U64(wire.Filetime(when))
  877. basic.U64(0)
  878. basic.U32(0)
  879. basic.U32(0)
  880. if r := c.call(wire.CmdSetInfo, setInfoBody(id, wire.FileBasicInformation, basic.B)); r.hdr.Status != 0 {
  881. t.Fatalf("set info: %x", r.hdr.Status)
  882. }
  883. c.call(wire.CmdWrite, writeBodyOf(id, 0, []byte("later write")))
  884. c.close(id)
  885. info, err := os.Stat(filepath.Join(h.share.root, "f.txt"))
  886. if err != nil {
  887. t.Fatal(err)
  888. }
  889. if !info.ModTime().Equal(when) {
  890. t.Errorf("mod time = %v, a copy must keep the source's date", info.ModTime())
  891. }
  892. }
  893. func TestChangedFilesAreReported(t *testing.T) {
  894. h := newHarness(t)
  895. c := newRawClient(t, h)
  896. id := mustCreate(t, c, "f.txt", openRW)
  897. c.call(wire.CmdWrite, writeBodyOf(id, 0, []byte("x")))
  898. c.close(id)
  899. h.share.mu.Lock()
  900. defer h.share.mu.Unlock()
  901. if len(h.share.changed) != 1 || h.share.changed[0] != "f.txt" {
  902. t.Errorf("changed = %v", h.share.changed)
  903. }
  904. }
  905. func TestDeletedFileAccountsBeforeItGoes(t *testing.T) {
  906. h := newHarness(t)
  907. c := newRawClient(t, h)
  908. id := mustCreate(t, c, "temp.tmp", createOpts{access: wire.FileWriteData | wire.AccessDelete, share: shareAll, disposition: wire.DispositionCreate, options: wire.OptionDeleteOnCLS})
  909. c.call(wire.CmdWrite, writeBodyOf(id, 0, []byte("x")))
  910. c.close(id)
  911. h.share.mu.Lock()
  912. defer h.share.mu.Unlock()
  913. if len(h.share.changed) != 1 {
  914. t.Errorf("a temp file must be accounted for, or removing it gives back space it never took: %v", h.share.changed)
  915. }
  916. }
  917. func TestDeleteOnlyHandleCanQueryStandardInfo(t *testing.T) {
  918. h := newHarness(t)
  919. os.WriteFile(filepath.Join(h.share.root, "f.txt"), []byte("x"), 0644)
  920. c := newRawClient(t, h)
  921. id := mustCreate(t, c, "f.txt", createOpts{access: wire.AccessDelete, share: shareAll, disposition: wire.DispositionOpen})
  922. if r := c.call(wire.CmdQueryInfo, queryInfoBody(id, wire.InfoFile, wire.FileStandardInformation, 0)); r.hdr.Status != 0 {
  923. t.Errorf("standard: %x", r.hdr.Status)
  924. }
  925. if r := c.call(wire.CmdQueryInfo, queryInfoBody(id, wire.InfoFile, wire.FileBasicInformation, 0)); r.hdr.Status != wire.StatusAccessDenied {
  926. t.Errorf("basic needs read attributes: %x", r.hdr.Status)
  927. }
  928. }
  929. // countingShare counts folder reads, to prove the cache is doing its job.
  930. type countingShare struct {
  931. *testShare
  932. reads int
  933. }
  934. func (s *countingShare) ReadDir(p string) ([]FileInfo, error) {
  935. s.reads++
  936. return s.testShare.ReadDir(p)
  937. }
  938. func TestNameCache(t *testing.T) {
  939. root := t.TempDir()
  940. os.WriteFile(filepath.Join(root, "Real.txt"), []byte("x"), 0644)
  941. s := &countingShare{testShare: &testShare{name: "d", root: root, denyRead: map[string]bool{}, denyWrite: map[string]bool{}}}
  942. names := newNameCache()
  943. res, err := resolve(s, names, "missing.txt")
  944. if err != nil || res.exists || !res.parentExists {
  945. t.Fatalf("missing: %+v %v", res, err)
  946. }
  947. reads := s.reads
  948. for i := 0; i < 50; i++ {
  949. resolve(s, names, "desktop.ini")
  950. }
  951. if s.reads != reads {
  952. t.Errorf("repeated misses read the folder %d more times", s.reads-reads)
  953. }
  954. //A stale spelling must never produce a file that is gone
  955. names.forget(s, "")
  956. res, _ = resolve(s, names, "NOT-THERE")
  957. os.Remove(filepath.Join(root, "Real.txt"))
  958. res, err = resolve(s, names, "REAL.TXT")
  959. if err != nil || res.exists {
  960. t.Errorf("a removed file resolved: %+v %v", res, err)
  961. }
  962. }
  963. func TestNameCacheForgetsWhatTheServerChanges(t *testing.T) {
  964. h := newHarness(t)
  965. c := newRawClient(t, h)
  966. //Fill the cache with a miss, then create the file in another case
  967. if _, st := c.create("New.TXT", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen}); st != wire.StatusObjectNameNotFound {
  968. t.Fatalf("expected a miss: %x", st)
  969. }
  970. id := mustCreate(t, c, "new.txt", createOpts{access: wire.FileWriteData, share: shareAll, disposition: wire.DispositionCreate})
  971. c.close(id)
  972. got, st := c.create("NEW.txt", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen})
  973. if st != 0 {
  974. t.Fatalf("a file just created must be found in any case: %x", st)
  975. }
  976. c.close(got)
  977. }
  978. func TestRevokedDriveStopsAnsweringQueries(t *testing.T) {
  979. h := newHarness(t)
  980. os.WriteFile(filepath.Join(h.share.root, "f.txt"), []byte("x"), 0644)
  981. c := newRawClient(t, h)
  982. id := mustCreate(t, c, "f.txt", createOpts{access: wire.FileReadData | wire.FileReadAttributes, share: shareAll, disposition: wire.DispositionOpen})
  983. h.share.mu.Lock()
  984. h.share.denyRead["f.txt"] = true
  985. h.share.mu.Unlock()
  986. if r := c.call(wire.CmdQueryInfo, queryInfoBody(id, wire.InfoFile, wire.FileStandardInformation, 0)); r.hdr.Status != wire.StatusAccessDenied {
  987. t.Errorf("query: %x", r.hdr.Status)
  988. }
  989. if r := c.call(wire.CmdRead, readBodyOf(id, 0, 1)); r.hdr.Status != wire.StatusAccessDenied {
  990. t.Errorf("read: %x", r.hdr.Status)
  991. }
  992. }
  993. func TestUnsignedRequestDropsTheConnection(t *testing.T) {
  994. h := newHarness(t)
  995. c := newRawClient(t, h)
  996. msg := c.message(wire.CmdEcho, []byte{4, 0, 0, 0}, 0)
  997. c.writeFrame(msg)
  998. c.nc.SetReadDeadline(time.Now().Add(3 * time.Second))
  999. if _, err := c.nc.Read(make([]byte, 1)); err == nil {
  1000. t.Error("an unsigned request on a signed session must end the connection")
  1001. }
  1002. }
  1003. func TestForgedSignatureDropsTheConnection(t *testing.T) {
  1004. h := newHarness(t)
  1005. c := newRawClient(t, h)
  1006. msg := c.message(wire.CmdEcho, []byte{4, 0, 0, 0}, 0)
  1007. c.signer.Sign(msg)
  1008. msg[wire.SignatureAt] ^= 1
  1009. c.writeFrame(msg)
  1010. c.nc.SetReadDeadline(time.Now().Add(3 * time.Second))
  1011. if _, err := c.nc.Read(make([]byte, 1)); err == nil {
  1012. t.Error("a forged signature must end the connection")
  1013. }
  1014. }
  1015. func TestReusedMessageIDDropsTheConnection(t *testing.T) {
  1016. h := newHarness(t)
  1017. c := newRawClient(t, h)
  1018. if r := c.call(wire.CmdEcho, []byte{4, 0, 0, 0}); r.hdr.Status != 0 {
  1019. t.Fatal(r.hdr.Status)
  1020. }
  1021. c.mid--
  1022. msg := c.message(wire.CmdEcho, []byte{4, 0, 0, 0}, 0)
  1023. c.signer.Sign(msg)
  1024. c.writeFrame(msg)
  1025. c.nc.SetReadDeadline(time.Now().Add(3 * time.Second))
  1026. if _, err := c.nc.Read(make([]byte, 1)); err == nil {
  1027. t.Error("a replayed message id must end the connection")
  1028. }
  1029. }
  1030. func TestUnderchargedReadIsRefused(t *testing.T) {
  1031. h := newHarness(t)
  1032. os.WriteFile(filepath.Join(h.share.root, "f"), make([]byte, 1<<20), 0644)
  1033. c := newRawClient(t, h)
  1034. id := mustCreate(t, c, "f", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen})
  1035. //message() charges one credit, which covers 64 KiB
  1036. if r := c.call(wire.CmdRead, readBodyOf(id, 0, 1<<20)); r.hdr.Status != wire.StatusInvalidParameter {
  1037. t.Errorf("status %x", r.hdr.Status)
  1038. }
  1039. }
  1040. func TestSMB1OpeningMovesToSMB2(t *testing.T) {
  1041. h := newHarness(t)
  1042. nc, err := netDial(h)
  1043. if err != nil {
  1044. t.Fatal(err)
  1045. }
  1046. defer nc.Close()
  1047. c := &rawClient{t: t, nc: nc}
  1048. smb1 := make([]byte, 32)
  1049. copy(smb1, []byte{0xFF, 'S', 'M', 'B', 0x72})
  1050. data := []byte("\x02NT LM 0.12\x00\x02SMB 2.002\x00\x02SMB 2.???\x00")
  1051. smb1 = append(smb1, 0, byte(len(data)), 0)
  1052. smb1 = append(smb1, data...)
  1053. c.writeFrame(smb1)
  1054. r := parseReplies(t, c.readFrame())[0]
  1055. if got := binary.LittleEndian.Uint16(r.body[4:]); got != wire.DialectWildcard {
  1056. t.Fatalf("dialect %x", got)
  1057. }
  1058. c.mid = 1
  1059. c.writeFrame(c.message(wire.CmdNegotiate, negotiateBody(wire.Dialect311), 0))
  1060. r = parseReplies(t, c.readFrame())[0]
  1061. if got := binary.LittleEndian.Uint16(r.body[4:]); got != wire.Dialect311 {
  1062. t.Errorf("dialect %x", got)
  1063. }
  1064. }
  1065. func TestSMB1WithoutSMB2IsDropped(t *testing.T) {
  1066. h := newHarness(t)
  1067. nc, err := netDial(h)
  1068. if err != nil {
  1069. t.Fatal(err)
  1070. }
  1071. defer nc.Close()
  1072. c := &rawClient{t: t, nc: nc}
  1073. smb1 := make([]byte, 32)
  1074. copy(smb1, []byte{0xFF, 'S', 'M', 'B', 0x72})
  1075. data := []byte("\x02NT LM 0.12\x00")
  1076. smb1 = append(smb1, 0, byte(len(data)), 0)
  1077. smb1 = append(smb1, data...)
  1078. c.writeFrame(smb1)
  1079. c.nc.SetReadDeadline(time.Now().Add(3 * time.Second))
  1080. if _, err := c.nc.Read(make([]byte, 1)); err == nil {
  1081. t.Error("an SMB1 only client gets no session")
  1082. }
  1083. }
  1084. func TestDialectSelection(t *testing.T) {
  1085. cases := []struct {
  1086. offered []uint16
  1087. want uint16
  1088. }{
  1089. {[]uint16{wire.Dialect202, wire.Dialect210, wire.Dialect300, wire.Dialect302, wire.Dialect311}, wire.Dialect311},
  1090. {[]uint16{wire.Dialect210, wire.Dialect302}, wire.Dialect302},
  1091. {[]uint16{wire.Dialect210}, wire.Dialect210},
  1092. {[]uint16{wire.Dialect202}, 0},
  1093. }
  1094. for _, tc := range cases {
  1095. if got := pickDialect(tc.offered); got != tc.want {
  1096. t.Errorf("%x: got %x want %x", tc.offered, got, tc.want)
  1097. }
  1098. }
  1099. }
  1100. func TestParsePath(t *testing.T) {
  1101. cases := []struct {
  1102. in string
  1103. want string
  1104. status uint32
  1105. }{
  1106. {"", "", 0},
  1107. {`folder\file.txt`, "folder/file.txt", 0},
  1108. {`\leading`, "leading", 0},
  1109. {`trailing\`, "trailing", 0},
  1110. {`file.txt::$DATA`, "file.txt", 0},
  1111. {`FILE.TXT::$data`, "FILE.TXT", 0},
  1112. {`file.txt:Zone.Identifier`, "", wire.StatusObjectNameInvalid},
  1113. {`file.txt:Zone.Identifier:$DATA`, "", wire.StatusObjectNameInvalid},
  1114. {`a:b\c`, "", wire.StatusObjectNameInvalid},
  1115. {`..\etc\passwd`, "", wire.StatusObjectPathSyntaxBad},
  1116. {`a\..\..\b`, "", wire.StatusObjectPathSyntaxBad},
  1117. {`.`, "", wire.StatusObjectPathSyntaxBad},
  1118. {`a\\b`, "", wire.StatusObjectNameInvalid},
  1119. {`wild*card`, "", wire.StatusObjectNameInvalid},
  1120. {`qu?ry`, "", wire.StatusObjectNameInvalid},
  1121. {"nul\x00byte", "", wire.StatusObjectNameInvalid},
  1122. {"tab\tname", "", wire.StatusObjectNameInvalid},
  1123. {`a/b`, "", wire.StatusObjectNameInvalid},
  1124. {strings.Repeat("x", 256), "", wire.StatusObjectNameInvalid},
  1125. {strings.Repeat("x", 255), strings.Repeat("x", 255), 0},
  1126. {"name", ":name", 0},
  1127. }
  1128. for _, tc := range cases {
  1129. got, st := parsePath(tc.in)
  1130. if st != tc.status || got != tc.want {
  1131. t.Errorf("%q: got %q %x, want %q %x", tc.in, got, st, tc.want, tc.status)
  1132. }
  1133. }
  1134. }
  1135. func TestNameMapping(t *testing.T) {
  1136. cases := []string{"plain.txt", "colon:name", `what?.txt`, "star*", "trailing.", "trailing ", `a"b<c>d|e`, ".", ".."}
  1137. for _, name := range cases {
  1138. wireName := toWireName(name)
  1139. if name != "." && name != ".." && strings.ContainsAny(wireName, `:?*"<>|`) {
  1140. t.Errorf("%q still has a forbidden character: %q", name, wireName)
  1141. }
  1142. if got := fromWireName(wireName); got != name {
  1143. t.Errorf("%q round trip gave %q", name, got)
  1144. }
  1145. }
  1146. if got := toWireName("."); got != "." {
  1147. t.Errorf("the current folder entry changed: %q", got)
  1148. }
  1149. }
  1150. func TestMappedNamesAreReachable(t *testing.T) {
  1151. h := newHarness(t)
  1152. os.WriteFile(filepath.Join(h.share.root, "a:b.txt"), []byte("mapped"), 0644)
  1153. c := newRawClient(t, h)
  1154. id := mustCreate(t, c, "", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen, options: wire.OptionDirectory})
  1155. r := c.call(wire.CmdQueryDirectory, queryDirBody(id, wire.FileNamesInformation, 0, "*"))
  1156. listed := toWireName("a:b.txt")
  1157. if !bytes.Contains(r.body, wire.EncodeUTF16(listed)) {
  1158. t.Fatal("the mapped name must be listed")
  1159. }
  1160. f := mustCreate(t, c, listed, createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen})
  1161. rr := c.call(wire.CmdRead, readBodyOf(f, 0, 6))
  1162. if rr.hdr.Status != 0 || string(rr.body[16:]) != "mapped" {
  1163. t.Errorf("read: %x %q", rr.hdr.Status, rr.body)
  1164. }
  1165. }
  1166. func TestMatchPattern(t *testing.T) {
  1167. cases := []struct {
  1168. pattern, name string
  1169. want bool
  1170. }{
  1171. {"*", "anything", true},
  1172. {"*.*", "noext", true},
  1173. {"*.txt", "a.TXT", true},
  1174. {"*.txt", "a.txt.bak", false},
  1175. {"a?c", "abc", true},
  1176. {"a?c", "ac", false},
  1177. {"A.TXT", "a.txt", true},
  1178. {"<.txt", "a.b.txt", true},
  1179. {"<.TXT", "a.doc", false},
  1180. {`DESKTOP.INI`, "desktop.ini", true},
  1181. {`file"txt`, "file.txt", true},
  1182. {`file>`, "file1", true},
  1183. {`file>`, "file", true},
  1184. }
  1185. for _, tc := range cases {
  1186. if got := matchPattern(tc.pattern, tc.name); got != tc.want {
  1187. t.Errorf("%q vs %q: %v", tc.pattern, tc.name, got)
  1188. }
  1189. }
  1190. }
  1191. func TestCapture(t *testing.T) {
  1192. dir := t.TempDir()
  1193. h := newHarness(t, func(c *Config) { c.CaptureDir = dir })
  1194. c := newRawClient(t, h)
  1195. id := mustCreate(t, c, "f.txt", openRW)
  1196. secret := bytes.Repeat([]byte("SECRETCONTENT"), 1000)
  1197. c.call(wire.CmdWrite, writeBodyOf(id, 0, secret))
  1198. c.close(id)
  1199. h.srv.Close()
  1200. pcaps, _ := filepath.Glob(filepath.Join(dir, "*.pcap"))
  1201. logs, _ := filepath.Glob(filepath.Join(dir, "*.log"))
  1202. if len(pcaps) != 1 || len(logs) != 1 {
  1203. t.Fatalf("files: %v %v", pcaps, logs)
  1204. }
  1205. data, _ := os.ReadFile(pcaps[0])
  1206. if !bytes.Equal(data[:4], []byte{0xd4, 0xc3, 0xb2, 0xa1}) {
  1207. t.Error("not a pcap")
  1208. }
  1209. if bytes.Contains(data, secret[:4000]) {
  1210. t.Error("file contents must be cut unless asked for")
  1211. }
  1212. trace, _ := os.ReadFile(logs[0])
  1213. for _, want := range []string{"CREATE", "WRITE", `"f.txt"`, "SESSION_SETUP"} {
  1214. if !strings.Contains(string(trace), want) {
  1215. t.Errorf("trace lacks %s", want)
  1216. }
  1217. }
  1218. }
  1219. func TestCaptureRedactsLogins(t *testing.T) {
  1220. dir := t.TempDir()
  1221. h := newHarness(t, func(c *Config) { c.CaptureDir = dir })
  1222. c := newRawClient(t, h)
  1223. c.nc.Close()
  1224. h.srv.Close()
  1225. pcaps, _ := filepath.Glob(filepath.Join(dir, "*.pcap"))
  1226. data, _ := os.ReadFile(pcaps[0])
  1227. at := bytes.Index(data, []byte("NTLMSSP\x00\x03\x00\x00\x00"))
  1228. if at < 0 {
  1229. t.Fatal("the capture has no AUTHENTICATE")
  1230. }
  1231. msg := data[at:]
  1232. length := binary.LittleEndian.Uint16(msg[20:])
  1233. offset := binary.LittleEndian.Uint32(msg[24:])
  1234. if !bytes.Equal(msg[offset:offset+uint32(length)], make([]byte, length)) {
  1235. t.Error("the NT response must never reach a capture")
  1236. }
  1237. }
  1238. // slowHarness answers anything slower than 50 ms with an interim response.
  1239. func slowHarness(t *testing.T) *harness {
  1240. return newHarness(t, func(c *Config) { c.PendingAfter = 50 * time.Millisecond })
  1241. }
  1242. func TestSlowReadGoesAsync(t *testing.T) {
  1243. h := slowHarness(t)
  1244. os.WriteFile(filepath.Join(h.share.root, "f.txt"), []byte("hello world"), 0644)
  1245. c := newRawClient(t, h)
  1246. id := mustCreate(t, c, "f.txt", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen})
  1247. h.share.mu.Lock()
  1248. h.share.readDelay = 300 * time.Millisecond
  1249. h.share.mu.Unlock()
  1250. msg := c.message(wire.CmdRead, readBodyOf(id, 0, 5), 0)
  1251. c.signer.Sign(msg)
  1252. c.writeFrame(msg)
  1253. interim := parseReplies(t, c.readFrame())[0]
  1254. if interim.hdr.Status != wire.StatusPending || interim.hdr.Flags&wire.FlagAsync == 0 {
  1255. t.Fatalf("interim: %+v", interim.hdr)
  1256. }
  1257. if interim.hdr.Flags&wire.FlagSigned != 0 {
  1258. t.Error("an interim response must not be signed")
  1259. }
  1260. if interim.hdr.Credits == 0 {
  1261. t.Error("the interim response grants the credits, the final one may not")
  1262. }
  1263. final := parseReplies(t, c.readFrame())[0]
  1264. if final.hdr.Status != 0 || final.hdr.AsyncID != interim.hdr.AsyncID {
  1265. t.Fatalf("final: %+v", final.hdr)
  1266. }
  1267. c.verify(final)
  1268. if got := string(final.body[16:21]); got != "hello" {
  1269. t.Errorf("data %q", got)
  1270. }
  1271. }
  1272. func TestFastRequestsStaySync(t *testing.T) {
  1273. h := slowHarness(t)
  1274. c := newRawClient(t, h)
  1275. msg := c.message(wire.CmdCreate, createBody("quick.txt", openRW), 0)
  1276. c.signer.Sign(msg)
  1277. c.writeFrame(msg)
  1278. r := parseReplies(t, c.readFrame())[0]
  1279. if r.hdr.Status != 0 || r.hdr.Flags&wire.FlagAsync != 0 {
  1280. t.Errorf("a quick create must be answered at once: %+v", r.hdr)
  1281. }
  1282. }
  1283. func TestOtherRequestsRunBesideASlowOne(t *testing.T) {
  1284. h := slowHarness(t)
  1285. os.WriteFile(filepath.Join(h.share.root, "f.txt"), []byte("x"), 0644)
  1286. c := newRawClient(t, h)
  1287. id := mustCreate(t, c, "f.txt", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen})
  1288. h.share.mu.Lock()
  1289. h.share.readDelay = 500 * time.Millisecond
  1290. h.share.mu.Unlock()
  1291. slow := c.message(wire.CmdRead, readBodyOf(id, 0, 1), 0)
  1292. c.signer.Sign(slow)
  1293. c.writeFrame(slow)
  1294. if r := parseReplies(t, c.readFrame())[0]; r.hdr.Status != wire.StatusPending {
  1295. t.Fatalf("interim: %x", r.hdr.Status)
  1296. }
  1297. started := time.Now()
  1298. echo := c.message(wire.CmdEcho, []byte{4, 0, 0, 0}, 0)
  1299. c.signer.Sign(echo)
  1300. c.writeFrame(echo)
  1301. r := parseReplies(t, c.readFrame())[0]
  1302. if r.hdr.Command != wire.CmdEcho {
  1303. t.Fatalf("got command %d first", r.hdr.Command)
  1304. }
  1305. if took := time.Since(started); took > 300*time.Millisecond {
  1306. t.Errorf("echo waited %v behind a slow read", took)
  1307. }
  1308. if final := parseReplies(t, c.readFrame())[0]; final.hdr.Command != wire.CmdRead || final.hdr.Status != 0 {
  1309. t.Errorf("final: %+v", final.hdr)
  1310. }
  1311. }
  1312. func TestCancelledSlowCreateLeavesNoOpenFile(t *testing.T) {
  1313. h := slowHarness(t)
  1314. c := newRawClient(t, h)
  1315. h.share.mu.Lock()
  1316. h.share.openDelay = 300 * time.Millisecond
  1317. h.share.mu.Unlock()
  1318. msg := c.message(wire.CmdCreate, createBody("late.txt", openRW), 0)
  1319. mid := binary.LittleEndian.Uint64(msg[24:])
  1320. c.signer.Sign(msg)
  1321. c.writeFrame(msg)
  1322. interim := parseReplies(t, c.readFrame())[0]
  1323. if interim.hdr.Status != wire.StatusPending {
  1324. t.Fatalf("interim: %x", interim.hdr.Status)
  1325. }
  1326. h2 := wire.Header{Command: wire.CmdCancel, MessageID: mid, SessionID: c.session, Flags: wire.FlagAsync, AsyncID: interim.hdr.AsyncID}
  1327. cancel := make([]byte, wire.HeaderSize+4)
  1328. h2.Put(cancel)
  1329. cancel[wire.HeaderSize] = 4
  1330. c.signer.Sign(cancel)
  1331. c.writeFrame(cancel)
  1332. if final := parseReplies(t, c.readFrame())[0]; final.hdr.Status != wire.StatusCancelled {
  1333. t.Fatalf("final: %x", final.hdr.Status)
  1334. }
  1335. //The create goes on after the cancel, and the file appears
  1336. deadline := time.Now().Add(2 * time.Second)
  1337. for time.Now().Before(deadline) {
  1338. if _, err := os.Stat(filepath.Join(h.share.root, "late.txt")); err == nil {
  1339. break
  1340. }
  1341. time.Sleep(20 * time.Millisecond)
  1342. }
  1343. for h.share.openCount() != 0 && time.Now().Before(deadline) {
  1344. time.Sleep(20 * time.Millisecond)
  1345. }
  1346. if n := h.share.openCount(); n != 0 {
  1347. t.Errorf("%d files still open after the cancelled create", n)
  1348. }
  1349. //The session still works, and nothing about the open lingers
  1350. if _, st := c.create("late.txt", createOpts{access: wire.FileReadData | wire.FileWriteData, share: 0, disposition: wire.DispositionOpen}); st != 0 {
  1351. t.Errorf("an exclusive open after the cancel: %x", st)
  1352. }
  1353. }
  1354. func TestCloseReportsAFailedUpload(t *testing.T) {
  1355. h := newHarness(t)
  1356. c := newRawClient(t, h)
  1357. id := mustCreate(t, c, "doc.txt", openRW)
  1358. h.share.mu.Lock()
  1359. h.share.closeErr = errors.New("the remote refused the upload")
  1360. h.share.mu.Unlock()
  1361. if st := c.close(id); st == 0 {
  1362. t.Error("a close whose upload failed must not succeed")
  1363. }
  1364. h.share.mu.Lock()
  1365. h.share.closeErr = nil
  1366. h.share.mu.Unlock()
  1367. if st := c.close(id); st != wire.StatusFileClosed {
  1368. t.Errorf("the handle must be gone after the failed close: %x", st)
  1369. }
  1370. }
  1371. func TestAPendingFileReportsItsOwnSize(t *testing.T) {
  1372. h := newHarness(t)
  1373. c := newRawClient(t, h)
  1374. id := mustCreate(t, c, "staged.txt", openRW)
  1375. h.share.mu.Lock()
  1376. h.share.pending = 12345
  1377. h.share.mu.Unlock()
  1378. r := c.call(wire.CmdQueryInfo, queryInfoBody(id, wire.InfoFile, wire.FileStandardInformation, 0))
  1379. if r.hdr.Status != 0 {
  1380. t.Fatalf("query: %x", r.hdr.Status)
  1381. }
  1382. if eof := binary.LittleEndian.Uint64(r.body[8+8:]); eof != 12345 {
  1383. t.Errorf("end of file = %d, the handle must see what it wrote", eof)
  1384. }
  1385. }