lease_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. package smbserver
  2. import (
  3. "encoding/binary"
  4. "os"
  5. "path/filepath"
  6. "testing"
  7. "time"
  8. "imuslab.com/arozos/mod/storage/smbserver/wire"
  9. )
  10. type createCtx struct {
  11. name string
  12. data []byte
  13. }
  14. // createWithContexts is a CREATE with create contexts and an oplock level.
  15. func createWithContexts(name string, o createOpts, oplock uint8, contexts []createCtx) []byte {
  16. encoded := wire.EncodeUTF16(name)
  17. if len(encoded) == 0 {
  18. encoded = []byte{0, 0}
  19. }
  20. ctx := wire.NewWriter(64)
  21. for i, cc := range contexts {
  22. start := ctx.Len()
  23. ctx.U32(0)
  24. ctx.U16(16)
  25. ctx.U16(uint16(len(cc.name)))
  26. ctx.U16(0)
  27. ctx.U16(24)
  28. ctx.U32(uint32(len(cc.data)))
  29. ctx.Bytes([]byte(cc.name))
  30. ctx.Zero(4)
  31. ctx.Bytes(cc.data)
  32. if i < len(contexts)-1 {
  33. ctx.Align(8)
  34. binary.LittleEndian.PutUint32(ctx.B[start:], uint32(ctx.Len()-start))
  35. }
  36. }
  37. w := wire.NewWriter(56 + len(encoded) + 8 + ctx.Len())
  38. w.U16(57)
  39. w.U8(0)
  40. w.U8(oplock)
  41. w.U32(2)
  42. w.Zero(16)
  43. w.U32(o.access)
  44. w.U32(0)
  45. w.U32(o.share)
  46. w.U32(o.disposition)
  47. w.U32(o.options)
  48. w.U16(wire.HeaderSize + 56)
  49. nameLen := len(wire.EncodeUTF16(name))
  50. w.U16(uint16(nameLen))
  51. ctxAt := w.Len()
  52. w.U32(0)
  53. w.U32(0)
  54. w.Bytes(encoded)
  55. if len(contexts) > 0 {
  56. for (wire.HeaderSize+w.Len())%8 != 0 {
  57. w.U8(0)
  58. }
  59. binary.LittleEndian.PutUint32(w.B[ctxAt:], uint32(wire.HeaderSize+w.Len()))
  60. binary.LittleEndian.PutUint32(w.B[ctxAt+4:], uint32(ctx.Len()))
  61. w.Bytes(ctx.B)
  62. }
  63. return w.B
  64. }
  65. func leaseV2(key byte, state uint32, epoch uint16) createCtx {
  66. w := wire.NewWriter(52)
  67. k := [16]byte{key}
  68. w.Bytes(k[:])
  69. w.U32(state)
  70. w.U32(0)
  71. w.U64(0)
  72. w.Zero(16)
  73. w.U16(epoch)
  74. w.U16(0)
  75. return createCtx{wire.ContextLease, w.B}
  76. }
  77. func durableV2(guid byte, timeoutMs uint32) createCtx {
  78. w := wire.NewWriter(32)
  79. w.U32(timeoutMs)
  80. w.U32(0)
  81. w.U64(0)
  82. g := [16]byte{guid}
  83. w.Bytes(g[:])
  84. return createCtx{wire.ContextDurableReqV2, w.B}
  85. }
  86. func durableReconnect(id wire.FileID, guid byte) createCtx {
  87. w := wire.NewWriter(36)
  88. w.Bytes(id[:])
  89. g := [16]byte{guid}
  90. w.Bytes(g[:])
  91. w.U32(0)
  92. return createCtx{wire.ContextDurableRecon2, w.B}
  93. }
  94. // createReply is what tests check of a CREATE response.
  95. type createReply struct {
  96. status uint32
  97. id wire.FileID
  98. oplock uint8
  99. lease uint32
  100. epoch uint16
  101. durable bool
  102. hasCtx map[string]bool
  103. }
  104. func parseCreateReply(r rawReply) createReply {
  105. out := createReply{status: r.hdr.Status, hasCtx: map[string]bool{}}
  106. if r.hdr.Status != 0 || len(r.body) < 88 {
  107. return out
  108. }
  109. out.oplock = r.body[2]
  110. copy(out.id[:], r.body[64:80])
  111. off := int(binary.LittleEndian.Uint32(r.body[80:]))
  112. n := int(binary.LittleEndian.Uint32(r.body[84:]))
  113. if n == 0 {
  114. return out
  115. }
  116. chain := r.body[off-wire.HeaderSize : off-wire.HeaderSize+n]
  117. for {
  118. next := binary.LittleEndian.Uint32(chain)
  119. nameOff := binary.LittleEndian.Uint16(chain[4:])
  120. nameLen := binary.LittleEndian.Uint16(chain[6:])
  121. dataOff := binary.LittleEndian.Uint16(chain[10:])
  122. dataLen := binary.LittleEndian.Uint32(chain[12:])
  123. name := string(chain[nameOff : nameOff+nameLen])
  124. data := chain[dataOff : uint32(dataOff)+dataLen]
  125. out.hasCtx[name] = true
  126. switch name {
  127. case wire.ContextLease:
  128. out.lease = binary.LittleEndian.Uint32(data[16:])
  129. if len(data) >= 52 {
  130. out.epoch = binary.LittleEndian.Uint16(data[48:])
  131. }
  132. case wire.ContextDurableReqV2:
  133. out.durable = true
  134. }
  135. if next == 0 {
  136. return out
  137. }
  138. chain = chain[next:]
  139. }
  140. }
  141. // leaseBreak is a Lease Break Notification as a client sees it.
  142. type leaseBreak struct {
  143. key byte
  144. current, next uint32
  145. ack bool
  146. epoch uint16
  147. }
  148. func isBreak(r rawReply) bool {
  149. return r.hdr.Command == wire.CmdOplockBreak && r.hdr.MessageID == ^uint64(0)
  150. }
  151. func parseBreak(t *testing.T, r rawReply) leaseBreak {
  152. t.Helper()
  153. if len(r.body) < 44 || binary.LittleEndian.Uint16(r.body) != 44 {
  154. t.Fatalf("not a lease break: %x", r.body)
  155. }
  156. if r.hdr.SessionID != 0 || r.hdr.Flags&wire.FlagSigned != 0 {
  157. t.Error("a lease break has no session and no signature")
  158. }
  159. return leaseBreak{
  160. key: r.body[8],
  161. current: binary.LittleEndian.Uint32(r.body[24:]),
  162. next: binary.LittleEndian.Uint32(r.body[28:]),
  163. ack: binary.LittleEndian.Uint32(r.body[4:])&leaseBreakAckRequired != 0,
  164. epoch: binary.LittleEndian.Uint16(r.body[2:]),
  165. }
  166. }
  167. // send writes a signed request without waiting, and returns its message id.
  168. func (c *rawClient) send(cmd uint16, body []byte) uint64 {
  169. msg := c.message(cmd, body, 0)
  170. mid := binary.LittleEndian.Uint64(msg[24:])
  171. c.signer.Sign(msg)
  172. c.writeFrame(msg)
  173. return mid
  174. }
  175. // next reads the next message that is not an interim response.
  176. func (c *rawClient) next() rawReply {
  177. c.t.Helper()
  178. for {
  179. r := parseReplies(c.t, c.readFrame())[0]
  180. if r.hdr.Status == wire.StatusPending && !isBreak(r) {
  181. continue
  182. }
  183. return r
  184. }
  185. }
  186. // quiet reports that nothing arrives for a while. What does arrive is lost,
  187. // so it is for the end of a test or the failure path.
  188. func (c *rawClient) quiet(d time.Duration) bool {
  189. c.nc.SetReadDeadline(time.Now().Add(d))
  190. head := make([]byte, 1)
  191. _, err := c.nc.Read(head)
  192. return err != nil
  193. }
  194. func leaseCreate(t *testing.T, c *rawClient, name string, o createOpts, contexts ...createCtx) createReply {
  195. t.Helper()
  196. return parseCreateReply(c.call(wire.CmdCreate, createWithContexts(name, o, oplockLevelLease, contexts)))
  197. }
  198. func leaseAck(key byte, state uint32) []byte {
  199. w := wire.NewWriter(36)
  200. w.U16(36)
  201. w.U16(0)
  202. w.U32(0)
  203. k := [16]byte{key}
  204. w.Bytes(k[:])
  205. w.U32(state)
  206. w.U64(0)
  207. return w.B
  208. }
  209. const rwh = leaseRead | leaseHandle | leaseWrite
  210. func leaseHarness(t *testing.T, tune ...func(*Config)) *harness {
  211. return newHarness(t, append([]func(*Config){noPoll, func(c *Config) {
  212. c.PendingAfter = 50 * time.Millisecond
  213. c.LeasePoll = -1
  214. }}, tune...)...)
  215. }
  216. var openAllShare = createOpts{access: wire.FileReadData | wire.FileWriteData, share: shareAll, disposition: wire.DispositionOpenIf}
  217. func TestLeaseBreaksForAnotherOpen(t *testing.T) {
  218. h := leaseHarness(t)
  219. os.WriteFile(filepath.Join(h.share.root, "doc.txt"), []byte("hello"), 0644)
  220. a := newRawClient(t, h)
  221. b := newRawClient(t, h)
  222. got := leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, rwh, 0))
  223. if got.status != 0 || got.oplock != oplockLevelLease || got.lease != rwh {
  224. t.Fatalf("grant: %+v", got)
  225. }
  226. //B opens the file; A must first stop holding back writes
  227. b.send(wire.CmdCreate, createBody("doc.txt", openAllShare))
  228. br := parseBreak(t, a.next())
  229. if br.key != 1 || br.current != rwh || br.next != leaseRead|leaseHandle || !br.ack {
  230. t.Fatalf("break: %+v", br)
  231. }
  232. if br.epoch != got.epoch+1 {
  233. t.Errorf("epoch %d after %d", br.epoch, got.epoch)
  234. }
  235. //B hears only that its open is pending
  236. if r := parseReplies(t, b.readFrame())[0]; r.hdr.Status != wire.StatusPending {
  237. t.Fatalf("B got %x before A answered the break", r.hdr.Status)
  238. }
  239. if !b.quiet(150 * time.Millisecond) {
  240. t.Fatal("B's open finished before A answered the break")
  241. }
  242. if r := a.call(wire.CmdOplockBreak, leaseAck(1, leaseRead|leaseHandle)); r.hdr.Status != 0 {
  243. t.Fatalf("ack: %x", r.hdr.Status)
  244. }
  245. if r := b.next(); r.hdr.Command != wire.CmdCreate || r.hdr.Status != 0 {
  246. t.Errorf("B's open: %+v", r.hdr)
  247. }
  248. }
  249. func TestLeaseBreakTimesOut(t *testing.T) {
  250. h := leaseHarness(t, func(c *Config) { c.LeaseBreakTimeout = 200 * time.Millisecond })
  251. os.WriteFile(filepath.Join(h.share.root, "doc.txt"), nil, 0644)
  252. a := newRawClient(t, h)
  253. b := newRawClient(t, h)
  254. leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, rwh, 0))
  255. started := time.Now()
  256. if _, st := b.create("doc.txt", openAllShare); st != 0 {
  257. t.Fatalf("B's open: %x", st)
  258. }
  259. if took := time.Since(started); took < 150*time.Millisecond {
  260. t.Errorf("B's open waited only %v", took)
  261. }
  262. parseBreak(t, a.next())
  263. //The break is over, so a late answer is refused
  264. if r := a.call(wire.CmdOplockBreak, leaseAck(1, leaseRead|leaseHandle)); r.hdr.Status != wire.StatusUnsuccessful {
  265. t.Errorf("late ack: %x", r.hdr.Status)
  266. }
  267. }
  268. func TestLeaseHandleBreakOnShareConflict(t *testing.T) {
  269. h := leaseHarness(t)
  270. os.WriteFile(filepath.Join(h.share.root, "doc.txt"), nil, 0644)
  271. a := newRawClient(t, h)
  272. b := newRawClient(t, h)
  273. readOnly := createOpts{access: wire.FileReadData, share: wire.ShareRead, disposition: wire.DispositionOpen}
  274. got := leaseCreate(t, a, "doc.txt", readOnly, leaseV2(1, leaseRead|leaseHandle, 0))
  275. if got.lease != leaseRead|leaseHandle {
  276. t.Fatalf("grant: %+v", got)
  277. }
  278. //A shares no writing, so B's writer would be refused by A's cached handle
  279. b.send(wire.CmdCreate, createBody("doc.txt", openAllShare))
  280. br := parseBreak(t, a.next())
  281. if br.next != leaseRead || !br.ack {
  282. t.Fatalf("break: %+v", br)
  283. }
  284. //A answers the way Windows does: it closes the cached handle
  285. a.send(wire.CmdClose, closeBody(got.id))
  286. if r := a.next(); r.hdr.Command != wire.CmdClose || r.hdr.Status != 0 {
  287. t.Fatalf("close: %+v", r.hdr)
  288. }
  289. if r := b.next(); r.hdr.Status != 0 {
  290. t.Errorf("B's open: %x", r.hdr.Status)
  291. }
  292. }
  293. func TestWriteBreaksReadLeases(t *testing.T) {
  294. h := leaseHarness(t)
  295. os.WriteFile(filepath.Join(h.share.root, "doc.txt"), []byte("abc"), 0644)
  296. a := newRawClient(t, h)
  297. b := newRawClient(t, h)
  298. if got := leaseCreate(t, a, "doc.txt", openRead, leaseV2(1, leaseRead, 0)); got.lease != leaseRead {
  299. t.Fatalf("grant: %+v", got)
  300. }
  301. id := mustCreate(t, b, "doc.txt", openAllShare)
  302. started := time.Now()
  303. if r := b.call(wire.CmdWrite, writeBodyOf(id, 0, []byte("xyz"))); r.hdr.Status != 0 {
  304. t.Fatalf("write: %x", r.hdr.Status)
  305. }
  306. if time.Since(started) > 100*time.Millisecond {
  307. t.Error("a write must not wait for read caches")
  308. }
  309. br := parseBreak(t, a.next())
  310. if br.current != leaseRead || br.next != 0 || br.ack {
  311. t.Errorf("break: %+v", br)
  312. }
  313. }
  314. func TestOverwriteBreaksEverything(t *testing.T) {
  315. h := leaseHarness(t)
  316. os.WriteFile(filepath.Join(h.share.root, "doc.txt"), []byte("abc"), 0644)
  317. a := newRawClient(t, h)
  318. b := newRawClient(t, h)
  319. leaseCreate(t, a, "doc.txt", openRead, leaseV2(1, leaseRead|leaseHandle, 0))
  320. b.send(wire.CmdCreate, createBody("doc.txt", createOpts{access: wire.FileWriteData, share: shareAll, disposition: wire.DispositionOverwriteIf}))
  321. br := parseBreak(t, a.next())
  322. if br.next != 0 || !br.ack {
  323. t.Fatalf("break: %+v", br)
  324. }
  325. a.call(wire.CmdOplockBreak, leaseAck(1, 0))
  326. if r := b.next(); r.hdr.Status != 0 {
  327. t.Errorf("overwrite: %x", r.hdr.Status)
  328. }
  329. }
  330. func TestDeleteBreaksHandleLeases(t *testing.T) {
  331. h := leaseHarness(t)
  332. os.WriteFile(filepath.Join(h.share.root, "doc.txt"), nil, 0644)
  333. a := newRawClient(t, h)
  334. b := newRawClient(t, h)
  335. held := leaseCreate(t, a, "doc.txt", createOpts{access: wire.FileReadData, share: shareAll, disposition: wire.DispositionOpen}, leaseV2(1, leaseRead|leaseHandle, 0))
  336. id := mustCreate(t, b, "doc.txt", createOpts{access: wire.AccessDelete | wire.FileReadAttributes, share: shareAll, disposition: wire.DispositionOpen})
  337. b.send(wire.CmdSetInfo, setInfoBody(id, wire.FileDispositionInformation, []byte{1}))
  338. br := parseBreak(t, a.next())
  339. if br.next != leaseRead || !br.ack {
  340. t.Fatalf("break: %+v", br)
  341. }
  342. a.send(wire.CmdClose, closeBody(held.id))
  343. a.next()
  344. if r := b.next(); r.hdr.Status != 0 {
  345. t.Fatalf("delete: %x", r.hdr.Status)
  346. }
  347. b.close(id)
  348. if _, err := os.Stat(filepath.Join(h.share.root, "doc.txt")); !os.IsNotExist(err) {
  349. t.Error("the file must be gone once the cached handle closed")
  350. }
  351. }
  352. func TestOwnLeaseDoesNotBreak(t *testing.T) {
  353. h := leaseHarness(t)
  354. a := newRawClient(t, h)
  355. first := leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, rwh, 0))
  356. second := leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, rwh, 0))
  357. if first.lease != rwh || second.lease != rwh {
  358. t.Errorf("grants %x %x: two opens of one lease share it", first.lease, second.lease)
  359. }
  360. if !a.quiet(150 * time.Millisecond) {
  361. t.Error("a lease must not break for its own opens")
  362. }
  363. }
  364. func TestWriteCachingNeedsTheFileAlone(t *testing.T) {
  365. h := leaseHarness(t)
  366. b := newRawClient(t, h)
  367. a := newRawClient(t, h)
  368. mustCreate(t, b, "doc.txt", openAllShare)
  369. if got := leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, rwh, 0)); got.lease != leaseRead|leaseHandle {
  370. t.Errorf("grant %x: writes cannot be held back while B has the file open", got.lease)
  371. }
  372. }
  373. func TestLeaseKeyOnAnotherFileIsRefused(t *testing.T) {
  374. h := leaseHarness(t)
  375. a := newRawClient(t, h)
  376. leaseCreate(t, a, "one.txt", openAllShare, leaseV2(1, leaseRead, 0))
  377. if got := leaseCreate(t, a, "two.txt", openAllShare, leaseV2(1, leaseRead, 0)); got.status != wire.StatusInvalidParameter {
  378. t.Errorf("status %x", got.status)
  379. }
  380. }
  381. func TestLeaseAckChecks(t *testing.T) {
  382. h := leaseHarness(t)
  383. os.WriteFile(filepath.Join(h.share.root, "doc.txt"), nil, 0644)
  384. a := newRawClient(t, h)
  385. b := newRawClient(t, h)
  386. if r := a.call(wire.CmdOplockBreak, leaseAck(9, 0)); r.hdr.Status != wire.StatusObjectNameNotFound {
  387. t.Errorf("unknown lease: %x", r.hdr.Status)
  388. }
  389. leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, rwh, 0))
  390. if r := a.call(wire.CmdOplockBreak, leaseAck(1, 0)); r.hdr.Status != wire.StatusUnsuccessful {
  391. t.Errorf("no break running: %x", r.hdr.Status)
  392. }
  393. b.send(wire.CmdCreate, createBody("doc.txt", openAllShare))
  394. parseBreak(t, a.next())
  395. if r := a.call(wire.CmdOplockBreak, leaseAck(1, rwh)); r.hdr.Status != wire.StatusRequestNotAccepted {
  396. t.Errorf("keeping write caching: %x", r.hdr.Status)
  397. }
  398. if r := a.call(wire.CmdOplockBreak, leaseAck(1, leaseRead)); r.hdr.Status != 0 {
  399. t.Errorf("giving back more than asked: %x", r.hdr.Status)
  400. }
  401. b.next()
  402. }
  403. func TestNoLeasesOnDrivesThatCannotBeWatched(t *testing.T) {
  404. h := leaseHarness(t)
  405. h.share.mu.Lock()
  406. h.share.noPoll = true
  407. h.share.mu.Unlock()
  408. a := newRawClient(t, h)
  409. got := leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, rwh, 0))
  410. if got.status != 0 || got.oplock != 0 || got.hasCtx[wire.ContextLease] {
  411. t.Errorf("reply %+v", got)
  412. }
  413. }
  414. func TestNoLeasesWhenTurnedOff(t *testing.T) {
  415. h := leaseHarness(t, func(c *Config) { c.NoLeases = true })
  416. a := newRawClient(t, h)
  417. if got := leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, rwh, 0)); got.oplock != 0 || got.hasCtx[wire.ContextLease] {
  418. t.Errorf("reply %+v", got)
  419. }
  420. }
  421. func TestLeaseValidatorSeesOutsideChanges(t *testing.T) {
  422. h := leaseHarness(t, func(c *Config) { c.LeasePoll = 50 * time.Millisecond })
  423. p := filepath.Join(h.share.root, "doc.txt")
  424. os.WriteFile(p, []byte("one"), 0644)
  425. a := newRawClient(t, h)
  426. leaseCreate(t, a, "doc.txt", openRead, leaseV2(1, leaseRead, 0))
  427. if !a.quiet(200 * time.Millisecond) {
  428. t.Fatal("an unchanged file must keep its lease")
  429. }
  430. //The File Manager writes the file
  431. os.WriteFile(p, []byte("changed from the browser"), 0644)
  432. br := parseBreak(t, a.next())
  433. if br.next != 0 {
  434. t.Errorf("break: %+v", br)
  435. }
  436. }
  437. func TestOwnWritesDoNotLookLikeOutsideChanges(t *testing.T) {
  438. h := leaseHarness(t, func(c *Config) { c.LeasePoll = 50 * time.Millisecond })
  439. a := newRawClient(t, h)
  440. got := leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, rwh, 0))
  441. for i := 0; i < 5; i++ {
  442. a.call(wire.CmdWrite, writeBodyOf(got.id, uint64(i*10), []byte("0123456789")))
  443. time.Sleep(30 * time.Millisecond)
  444. }
  445. if !a.quiet(200 * time.Millisecond) {
  446. t.Error("the lease holder's own writes broke its lease")
  447. }
  448. }
  449. func TestDurableHandleSurvivesALostConnection(t *testing.T) {
  450. h := leaseHarness(t)
  451. a := newRawClient(t, h)
  452. got := leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, rwh, 0), durableV2(7, 0))
  453. if got.status != 0 || !got.durable {
  454. t.Fatalf("durable grant: %+v", got)
  455. }
  456. a.call(wire.CmdWrite, writeBodyOf(got.id, 0, []byte("unsaved work")))
  457. a.nc.Close() //Wi-Fi drops
  458. time.Sleep(100 * time.Millisecond)
  459. if n := h.srv.files.Count(fileKey(h.share, "doc.txt")); n != 1 {
  460. t.Fatalf("%d handles: the durable open must be kept", n)
  461. }
  462. back := newRawClient(t, h)
  463. again := leaseCreate(t, back, "doc.txt", openAllShare, leaseV2(1, rwh, 0), durableReconnect(got.id, 7))
  464. if again.status != 0 || again.id != got.id || again.lease != rwh {
  465. t.Fatalf("reconnect: %+v", again)
  466. }
  467. r := back.call(wire.CmdRead, readBodyOf(again.id, 0, 12))
  468. if r.hdr.Status != 0 || string(r.body[16:28]) != "unsaved work" {
  469. t.Errorf("read after reconnect: %x %q", r.hdr.Status, r.body)
  470. }
  471. if st := back.close(again.id); st != 0 {
  472. t.Errorf("close: %x", st)
  473. }
  474. if n := h.srv.files.Count(fileKey(h.share, "doc.txt")); n != 0 {
  475. t.Errorf("%d handles left", n)
  476. }
  477. }
  478. func TestDurableReconnectChecks(t *testing.T) {
  479. h := leaseHarness(t)
  480. a := newRawClient(t, h)
  481. got := leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, rwh, 0), durableV2(7, 0))
  482. other := newRawClient(t, h)
  483. //Still connected: not available
  484. if r := leaseCreate(t, other, "doc.txt", openAllShare, leaseV2(1, rwh, 0), durableReconnect(got.id, 7)); r.status != wire.StatusFileNotAvailable {
  485. t.Errorf("attached: %x", r.status)
  486. }
  487. a.nc.Close()
  488. time.Sleep(100 * time.Millisecond)
  489. if r := leaseCreate(t, other, "doc.txt", openAllShare, leaseV2(1, rwh, 0), durableReconnect(got.id, 8)); r.status != wire.StatusObjectNameNotFound {
  490. t.Errorf("wrong create guid: %x", r.status)
  491. }
  492. if r := leaseCreate(t, other, "doc.txt", openAllShare, leaseV2(2, rwh, 0), durableReconnect(got.id, 7)); r.status != wire.StatusObjectNameNotFound {
  493. t.Errorf("wrong lease key: %x", r.status)
  494. }
  495. }
  496. func TestCloseReleasesDetachedHandles(t *testing.T) {
  497. h := leaseHarness(t)
  498. a := newRawClient(t, h)
  499. leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, rwh, 0), durableV2(7, 60000))
  500. a.nc.Close()
  501. time.Sleep(100 * time.Millisecond)
  502. if n := h.share.openCount(); n != 1 {
  503. t.Fatalf("the durable handle must wait for its client, %d open", n)
  504. }
  505. h.srv.Close()
  506. if n := h.share.openCount(); n != 0 {
  507. t.Errorf("Close must close the handles nobody came back for yet, %d open", n)
  508. }
  509. }
  510. func TestDurableHandleGivesWayToAnotherClient(t *testing.T) {
  511. h := leaseHarness(t)
  512. a := newRawClient(t, h)
  513. got := leaseCreate(t, a, "doc.txt", createOpts{access: wire.FileReadData | wire.FileWriteData, share: 0, disposition: wire.DispositionOpenIf}, leaseV2(1, rwh, 0), durableV2(7, 0))
  514. a.nc.Close()
  515. time.Sleep(100 * time.Millisecond)
  516. b := newRawClient(t, h)
  517. started := time.Now()
  518. if _, st := b.create("doc.txt", openAllShare); st != 0 {
  519. t.Fatalf("B's open: %x", st)
  520. }
  521. if took := time.Since(started); took > 2*time.Second {
  522. t.Errorf("B waited %v for a client that is not there", took)
  523. }
  524. back := newRawClient(t, h)
  525. if r := leaseCreate(t, back, "doc.txt", openAllShare, leaseV2(1, rwh, 0), durableReconnect(got.id, 7)); r.status != wire.StatusObjectNameNotFound {
  526. t.Errorf("the closed durable handle came back: %x", r.status)
  527. }
  528. }
  529. func TestDurableHandleTimesOut(t *testing.T) {
  530. h := leaseHarness(t)
  531. a := newRawClient(t, h)
  532. got := leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, rwh, 0), durableV2(7, 100))
  533. a.nc.Close()
  534. time.Sleep(400 * time.Millisecond)
  535. if n := h.srv.files.Count(fileKey(h.share, "doc.txt")); n != 0 {
  536. t.Errorf("%d handles after the timeout", n)
  537. }
  538. back := newRawClient(t, h)
  539. if r := leaseCreate(t, back, "doc.txt", openAllShare, leaseV2(1, rwh, 0), durableReconnect(got.id, 7)); r.status != wire.StatusObjectNameNotFound {
  540. t.Errorf("reconnect after the timeout: %x", r.status)
  541. }
  542. }
  543. // The timeout fires while a reconnect holds the table: Stop cannot cancel the
  544. // callback, which then runs after the handle was taken back.
  545. func TestExpiryThatLosesToAReconnect(t *testing.T) {
  546. h := leaseHarness(t)
  547. a := newRawClient(t, h)
  548. got := leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, rwh, 0), durableV2(7, 0))
  549. a.call(wire.CmdWrite, writeBodyOf(got.id, 0, []byte("unsaved work")))
  550. a.nc.Close()
  551. time.Sleep(100 * time.Millisecond)
  552. h.srv.durables.mu.Lock()
  553. o := h.srv.durables.opens[persistentID(got.id)]
  554. var detach uint64
  555. if o != nil {
  556. detach = o.detachCount
  557. }
  558. h.srv.durables.mu.Unlock()
  559. if o == nil {
  560. t.Fatal("the durable open is not in the table")
  561. }
  562. back := newRawClient(t, h)
  563. again := leaseCreate(t, back, "doc.txt", openAllShare, leaseV2(1, rwh, 0), durableReconnect(got.id, 7))
  564. if again.status != 0 {
  565. t.Fatalf("reconnect: %+v", again)
  566. }
  567. //The late callback
  568. if h.srv.expireDetached(o, detach) {
  569. t.Fatal("an expiry must not take a handle its client took back")
  570. }
  571. r := back.call(wire.CmdRead, readBodyOf(again.id, 0, 12))
  572. if r.hdr.Status != 0 || string(r.body[16:28]) != "unsaved work" {
  573. t.Errorf("read after the late expiry: %x", r.hdr.Status)
  574. }
  575. //A timer of an earlier detach must not close a later one early
  576. back.nc.Close()
  577. time.Sleep(100 * time.Millisecond)
  578. if h.srv.expireDetached(o, detach) {
  579. t.Error("a stale timer expired the handle")
  580. }
  581. if !h.srv.expireDetached(o, detach+1) {
  582. t.Error("the current timer must expire the handle")
  583. }
  584. late := newRawClient(t, h)
  585. if r := leaseCreate(t, late, "doc.txt", openAllShare, leaseV2(1, rwh, 0), durableReconnect(got.id, 7)); r.status != wire.StatusObjectNameNotFound {
  586. t.Errorf("reconnect to an expired handle: %x", r.status)
  587. }
  588. h.srv.closeOpen(o)
  589. }
  590. func TestLogoffClosesDurableHandles(t *testing.T) {
  591. h := leaseHarness(t)
  592. a := newRawClient(t, h)
  593. leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, rwh, 0), durableV2(7, 0))
  594. if r := a.call(wire.CmdLogoff, []byte{4, 0, 0, 0}); r.hdr.Status != 0 {
  595. t.Fatalf("logoff: %x", r.hdr.Status)
  596. }
  597. if n := h.srv.files.Count(fileKey(h.share, "doc.txt")); n != 0 {
  598. t.Errorf("%d handles: a logoff closes durable handles", n)
  599. }
  600. }
  601. func TestNoDurableHandleWithoutHandleCaching(t *testing.T) {
  602. h := leaseHarness(t)
  603. a := newRawClient(t, h)
  604. if got := leaseCreate(t, a, "doc.txt", openAllShare, leaseV2(1, leaseRead, 0), durableV2(7, 0)); got.durable {
  605. t.Error("a durable handle needs a handle caching lease")
  606. }
  607. }