lock.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package webdav
  5. import (
  6. "errors"
  7. "path"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "time"
  12. )
  13. var (
  14. // ErrConfirmationFailed is returned by a LockSystem's Confirm method.
  15. ErrConfirmationFailed = errors.New("webdav: confirmation failed")
  16. // ErrForbidden is returned by a LockSystem's Unlock method.
  17. ErrForbidden = errors.New("webdav: forbidden")
  18. // ErrLocked is returned by a LockSystem's Create, Refresh and Unlock methods.
  19. ErrLocked = errors.New("webdav: locked")
  20. // ErrNoSuchLock is returned by a LockSystem's Refresh and Unlock methods.
  21. ErrNoSuchLock = errors.New("webdav: no such lock")
  22. )
  23. // Condition can match a WebDAV resource, based on a token or ETag.
  24. // Exactly one of Token and ETag should be non-empty.
  25. type Condition struct {
  26. Not bool
  27. Token string
  28. ETag string
  29. }
  30. // Releaser releases previously confirmed lock claims.
  31. //
  32. // Calling Release does not unlock the lock, in the WebDAV UNLOCK sense, but
  33. // once LockSystem.Confirm has confirmed that a lock claim is valid, that lock
  34. // cannot be Confirmed again until it has been Released.
  35. type Releaser interface {
  36. Release()
  37. }
  38. // LockSystem manages access to a collection of named resources. The elements
  39. // in a lock name are separated by slash ('/', U+002F) characters, regardless
  40. // of host operating system convention.
  41. type LockSystem interface {
  42. // Confirm confirms that the caller can claim all of the locks specified by
  43. // the given conditions, and that holding the union of all of those locks
  44. // gives exclusive access to the named resource.
  45. //
  46. // Exactly one of r and err will be non-nil. If r is non-nil, all of the
  47. // requested locks are held until r.Release is called.
  48. //
  49. // If Confirm returns ErrConfirmationFailed then the Handler will continue
  50. // to try any other set of locks presented (a WebDAV HTTP request can
  51. // present more than one set of locks). If it returns any other non-nil
  52. // error, the Handler will write a "500 Internal Server Error" HTTP status.
  53. Confirm(now time.Time, name string, conditions ...Condition) (r Releaser, err error)
  54. // Create creates a lock with the given depth, duration, owner and root
  55. // (name). The depth will either be negative (meaning infinite) or zero.
  56. //
  57. // If Create returns ErrLocked then the Handler will write a "423 Locked"
  58. // HTTP status. If it returns any other non-nil error, the Handler will
  59. // write a "500 Internal Server Error" HTTP status.
  60. //
  61. // See http://www.webdav.org/specs/rfc4918.html#rfc.section.9.10.6 for
  62. // when to use each error.
  63. //
  64. // The token returned identifies the created lock. It should be an absolute
  65. // URI as defined by RFC 3986, Section 4.3. In particular, it should not
  66. // contain whitespace.
  67. Create(now time.Time, details LockDetails) (token string, err error)
  68. // Refresh refreshes the lock with the given token.
  69. //
  70. // If Refresh returns ErrLocked then the Handler will write a "423 Locked"
  71. // HTTP Status. If Refresh returns ErrNoSuchLock then the Handler will write
  72. // a "412 Precondition Failed" HTTP Status. If it returns any other non-nil
  73. // error, the Handler will write a "500 Internal Server Error" HTTP status.
  74. //
  75. // See http://www.webdav.org/specs/rfc4918.html#rfc.section.9.10.6 for
  76. // when to use each error.
  77. Refresh(now time.Time, token string, duration time.Duration) (LockDetails, error)
  78. // Unlock unlocks the lock with the given token.
  79. //
  80. // If Unlock returns ErrForbidden then the Handler will write a "403
  81. // Forbidden" HTTP Status. If Unlock returns ErrLocked then the Handler
  82. // will write a "423 Locked" HTTP status. If Unlock returns ErrNoSuchLock
  83. // then the Handler will write a "409 Conflict" HTTP Status. If it returns
  84. // any other non-nil error, the Handler will write a "500 Internal Server
  85. // Error" HTTP status.
  86. //
  87. // See http://www.webdav.org/specs/rfc4918.html#rfc.section.9.11.1 for
  88. // when to use each error.
  89. Unlock(now time.Time, token string) error
  90. }
  91. // LockDetails are a lock's metadata.
  92. type LockDetails struct {
  93. // Root is the root resource name being locked. For a zero-depth lock, the
  94. // root is the only resource being locked.
  95. Root string
  96. // Duration is the lock timeout. A negative duration means infinite.
  97. Duration time.Duration
  98. // OwnerXML is the verbatim <owner> XML given in a LOCK HTTP request.
  99. //
  100. // TODO: does the "verbatim" nature play well with XML namespaces?
  101. // Does the OwnerXML field need to have more structure? See
  102. // https://codereview.appspot.com/175140043/#msg2
  103. OwnerXML string
  104. // ZeroDepth is whether the lock has zero depth. If it does not have zero
  105. // depth, it has infinite depth.
  106. ZeroDepth bool
  107. }
  108. // NewMemLS returns a new in-memory LockSystem.
  109. func NewMemLS() LockSystem {
  110. return &memLS{
  111. byName: make(map[string]*memLSNode),
  112. byToken: make(map[string]*memLSNode),
  113. gen: uint64(time.Now().Unix()),
  114. }
  115. }
  116. type memLS struct {
  117. mu sync.Mutex
  118. byName map[string]*memLSNode
  119. byToken map[string]*memLSNode
  120. gen uint64
  121. }
  122. func (m *memLS) nextToken() string {
  123. m.gen++
  124. return strconv.FormatUint(m.gen, 10)
  125. }
  126. func (m *memLS) collectExpiredNodes(now time.Time) {
  127. // TODO: implement.
  128. }
  129. func (m *memLS) Confirm(now time.Time, name string, conditions ...Condition) (Releaser, error) {
  130. m.mu.Lock()
  131. defer m.mu.Unlock()
  132. m.collectExpiredNodes(now)
  133. name = path.Clean("/" + name)
  134. // TODO: touch n.held.
  135. panic("TODO")
  136. }
  137. func (m *memLS) Create(now time.Time, details LockDetails) (string, error) {
  138. m.mu.Lock()
  139. defer m.mu.Unlock()
  140. m.collectExpiredNodes(now)
  141. name := path.Clean("/" + details.Root)
  142. if !m.canCreate(name, details.ZeroDepth) {
  143. return "", ErrLocked
  144. }
  145. n := m.create(name)
  146. n.token = m.nextToken()
  147. m.byToken[n.token] = n
  148. n.details = details
  149. // TODO: set n.expiry.
  150. return n.token, nil
  151. }
  152. func (m *memLS) Refresh(now time.Time, token string, duration time.Duration) (LockDetails, error) {
  153. m.mu.Lock()
  154. defer m.mu.Unlock()
  155. m.collectExpiredNodes(now)
  156. n := m.byToken[token]
  157. if n == nil {
  158. return LockDetails{}, ErrNoSuchLock
  159. }
  160. if n.held {
  161. return LockDetails{}, ErrLocked
  162. }
  163. n.details.Duration = duration
  164. // TODO: update n.expiry.
  165. return n.details, nil
  166. }
  167. func (m *memLS) Unlock(now time.Time, token string) error {
  168. m.mu.Lock()
  169. defer m.mu.Unlock()
  170. m.collectExpiredNodes(now)
  171. n := m.byToken[token]
  172. if n == nil {
  173. return ErrNoSuchLock
  174. }
  175. if n.held {
  176. return ErrLocked
  177. }
  178. m.remove(n)
  179. return nil
  180. }
  181. func (m *memLS) canCreate(name string, zeroDepth bool) bool {
  182. return walkToRoot(name, func(name0 string, first bool) bool {
  183. n := m.byName[name0]
  184. if n == nil {
  185. return true
  186. }
  187. if first {
  188. if n.token != "" {
  189. // The target node is already locked.
  190. return false
  191. }
  192. if !zeroDepth {
  193. // The requested lock depth is infinite, and the fact that n exists
  194. // (n != nil) means that a descendent of the target node is locked.
  195. return false
  196. }
  197. } else if n.token != "" && !n.details.ZeroDepth {
  198. // An ancestor of the target node is locked with infinite depth.
  199. return false
  200. }
  201. return true
  202. })
  203. }
  204. func (m *memLS) create(name string) (ret *memLSNode) {
  205. walkToRoot(name, func(name0 string, first bool) bool {
  206. n := m.byName[name0]
  207. if n == nil {
  208. n = &memLSNode{
  209. details: LockDetails{
  210. Root: name0,
  211. },
  212. }
  213. m.byName[name0] = n
  214. }
  215. n.refCount++
  216. if first {
  217. ret = n
  218. }
  219. return true
  220. })
  221. return ret
  222. }
  223. func (m *memLS) remove(n *memLSNode) {
  224. delete(m.byToken, n.token)
  225. n.token = ""
  226. walkToRoot(n.details.Root, func(name0 string, first bool) bool {
  227. x := m.byName[name0]
  228. x.refCount--
  229. if x.refCount == 0 {
  230. delete(m.byName, name0)
  231. }
  232. return true
  233. })
  234. }
  235. func walkToRoot(name string, f func(name0 string, first bool) bool) bool {
  236. for first := true; ; first = false {
  237. if !f(name, first) {
  238. return false
  239. }
  240. if name == "/" {
  241. break
  242. }
  243. name = name[:strings.LastIndex(name, "/")]
  244. if name == "" {
  245. name = "/"
  246. }
  247. }
  248. return true
  249. }
  250. type memLSNode struct {
  251. // details are the lock metadata. Even if this node's name is not explicitly locked,
  252. // details.Root will still equal the node's name.
  253. details LockDetails
  254. // token is the unique identifier for this node's lock. An empty token means that
  255. // this node is not explicitly locked.
  256. token string
  257. // refCount is the number of self-or-descendent nodes that are explicitly locked.
  258. refCount int
  259. // expiry is when this node's lock expires.
  260. expiry time.Time
  261. // held is whether this node's lock is actively held by a Confirm call.
  262. held bool
  263. }