context.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. package continuity
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "log"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "github.com/containerd/continuity/devices"
  11. driverpkg "github.com/containerd/continuity/driver"
  12. "github.com/containerd/continuity/pathdriver"
  13. "github.com/opencontainers/go-digest"
  14. )
  15. var (
  16. // ErrNotFound represents the resource not found
  17. ErrNotFound = fmt.Errorf("not found")
  18. // ErrNotSupported represents the resource not supported
  19. ErrNotSupported = fmt.Errorf("not supported")
  20. )
  21. // Context represents a file system context for accessing resources. The
  22. // responsibility of the context is to convert system specific resources to
  23. // generic Resource objects. Most of this is safe path manipulation, as well
  24. // as extraction of resource details.
  25. type Context interface {
  26. Apply(Resource) error
  27. Verify(Resource) error
  28. Resource(string, os.FileInfo) (Resource, error)
  29. Walk(filepath.WalkFunc) error
  30. }
  31. // SymlinkPath is intended to give the symlink target value
  32. // in a root context. Target and linkname are absolute paths
  33. // not under the given root.
  34. type SymlinkPath func(root, linkname, target string) (string, error)
  35. // ContextOptions represents options to create a new context.
  36. type ContextOptions struct {
  37. Digester Digester
  38. Driver driverpkg.Driver
  39. PathDriver pathdriver.PathDriver
  40. Provider ContentProvider
  41. }
  42. // context represents a file system context for accessing resources.
  43. // Generally, all path qualified access and system considerations should land
  44. // here.
  45. type context struct {
  46. driver driverpkg.Driver
  47. pathDriver pathdriver.PathDriver
  48. root string
  49. digester Digester
  50. provider ContentProvider
  51. }
  52. // NewContext returns a Context associated with root. The default driver will
  53. // be used, as returned by NewDriver.
  54. func NewContext(root string) (Context, error) {
  55. return NewContextWithOptions(root, ContextOptions{})
  56. }
  57. // NewContextWithOptions returns a Context associate with the root.
  58. func NewContextWithOptions(root string, options ContextOptions) (Context, error) {
  59. // normalize to absolute path
  60. pathDriver := options.PathDriver
  61. if pathDriver == nil {
  62. pathDriver = pathdriver.LocalPathDriver
  63. }
  64. root = pathDriver.FromSlash(root)
  65. root, err := pathDriver.Abs(pathDriver.Clean(root))
  66. if err != nil {
  67. return nil, err
  68. }
  69. driver := options.Driver
  70. if driver == nil {
  71. driver, err = driverpkg.NewSystemDriver()
  72. if err != nil {
  73. return nil, err
  74. }
  75. }
  76. digester := options.Digester
  77. if digester == nil {
  78. digester = simpleDigester{digest.Canonical}
  79. }
  80. // Check the root directory. Need to be a little careful here. We are
  81. // allowing a link for now, but this may have odd behavior when
  82. // canonicalizing paths. As long as all files are opened through the link
  83. // path, this should be okay.
  84. fi, err := driver.Stat(root)
  85. if err != nil {
  86. return nil, err
  87. }
  88. if !fi.IsDir() {
  89. return nil, &os.PathError{Op: "NewContext", Path: root, Err: os.ErrInvalid}
  90. }
  91. return &context{
  92. root: root,
  93. driver: driver,
  94. pathDriver: pathDriver,
  95. digester: digester,
  96. provider: options.Provider,
  97. }, nil
  98. }
  99. // Resource returns the resource as path p, populating the entry with info
  100. // from fi. The path p should be the path of the resource in the context,
  101. // typically obtained through Walk or from the value of Resource.Path(). If fi
  102. // is nil, it will be resolved.
  103. func (c *context) Resource(p string, fi os.FileInfo) (Resource, error) {
  104. fp, err := c.fullpath(p)
  105. if err != nil {
  106. return nil, err
  107. }
  108. if fi == nil {
  109. fi, err = c.driver.Lstat(fp)
  110. if err != nil {
  111. return nil, err
  112. }
  113. }
  114. base, err := newBaseResource(p, fi)
  115. if err != nil {
  116. return nil, err
  117. }
  118. base.xattrs, err = c.resolveXAttrs(fp, fi, base)
  119. if err == ErrNotSupported {
  120. log.Printf("resolving xattrs on %s not supported", fp)
  121. } else if err != nil {
  122. return nil, err
  123. }
  124. // TODO(stevvooe): Handle windows alternate data streams.
  125. if fi.Mode().IsRegular() {
  126. dgst, err := c.digest(p)
  127. if err != nil {
  128. return nil, err
  129. }
  130. return newRegularFile(*base, base.paths, fi.Size(), dgst)
  131. }
  132. if fi.Mode().IsDir() {
  133. return newDirectory(*base)
  134. }
  135. if fi.Mode()&os.ModeSymlink != 0 {
  136. // We handle relative links vs absolute links by including a
  137. // beginning slash for absolute links. Effectively, the bundle's
  138. // root is treated as the absolute link anchor.
  139. target, err := c.driver.Readlink(fp)
  140. if err != nil {
  141. return nil, err
  142. }
  143. return newSymLink(*base, target)
  144. }
  145. if fi.Mode()&os.ModeNamedPipe != 0 {
  146. return newNamedPipe(*base, base.paths)
  147. }
  148. if fi.Mode()&os.ModeDevice != 0 {
  149. deviceDriver, ok := c.driver.(driverpkg.DeviceInfoDriver)
  150. if !ok {
  151. log.Printf("device extraction not supported %s", fp)
  152. return nil, ErrNotSupported
  153. }
  154. // character and block devices merely need to recover the
  155. // major/minor device number.
  156. major, minor, err := deviceDriver.DeviceInfo(fi)
  157. if err != nil {
  158. return nil, err
  159. }
  160. return newDevice(*base, base.paths, major, minor)
  161. }
  162. log.Printf("%q (%v) is not supported", fp, fi.Mode())
  163. return nil, ErrNotFound
  164. }
  165. func (c *context) verifyMetadata(resource, target Resource) error {
  166. if target.Mode() != resource.Mode() {
  167. return fmt.Errorf("resource %q has incorrect mode: %v != %v", target.Path(), target.Mode(), resource.Mode())
  168. }
  169. if target.UID() != resource.UID() {
  170. return fmt.Errorf("unexpected uid for %q: %v != %v", target.Path(), target.UID(), resource.GID())
  171. }
  172. if target.GID() != resource.GID() {
  173. return fmt.Errorf("unexpected gid for %q: %v != %v", target.Path(), target.GID(), target.GID())
  174. }
  175. if xattrer, ok := resource.(XAttrer); ok {
  176. txattrer, tok := target.(XAttrer)
  177. if !tok {
  178. return fmt.Errorf("resource %q has xattrs but target does not support them", resource.Path())
  179. }
  180. // For xattrs, only ensure that we have those defined in the resource
  181. // and their values match. We can ignore other xattrs. In other words,
  182. // we only verify that target has the subset defined by resource.
  183. txattrs := txattrer.XAttrs()
  184. for attr, value := range xattrer.XAttrs() {
  185. tvalue, ok := txattrs[attr]
  186. if !ok {
  187. return fmt.Errorf("resource %q target missing xattr %q", resource.Path(), attr)
  188. }
  189. if !bytes.Equal(value, tvalue) {
  190. return fmt.Errorf("xattr %q value differs for resource %q", attr, resource.Path())
  191. }
  192. }
  193. }
  194. switch r := resource.(type) {
  195. case RegularFile:
  196. // TODO(stevvooe): Another reason to use a record-based approach. We
  197. // have to do another type switch to get this to work. This could be
  198. // fixed with an Equal function, but let's study this a little more to
  199. // be sure.
  200. t, ok := target.(RegularFile)
  201. if !ok {
  202. return fmt.Errorf("resource %q target not a regular file", r.Path())
  203. }
  204. if t.Size() != r.Size() {
  205. return fmt.Errorf("resource %q target has incorrect size: %v != %v", t.Path(), t.Size(), r.Size())
  206. }
  207. case Directory:
  208. t, ok := target.(Directory)
  209. if !ok {
  210. return fmt.Errorf("resource %q target not a directory", t.Path())
  211. }
  212. case SymLink:
  213. t, ok := target.(SymLink)
  214. if !ok {
  215. return fmt.Errorf("resource %q target not a symlink", t.Path())
  216. }
  217. if t.Target() != r.Target() {
  218. return fmt.Errorf("resource %q target has mismatched target: %q != %q", t.Path(), t.Target(), r.Target())
  219. }
  220. case Device:
  221. t, ok := target.(Device)
  222. if !ok {
  223. return fmt.Errorf("resource %q is not a device", t.Path())
  224. }
  225. if t.Major() != r.Major() || t.Minor() != r.Minor() {
  226. return fmt.Errorf("resource %q has mismatched major/minor numbers: %d,%d != %d,%d", t.Path(), t.Major(), t.Minor(), r.Major(), r.Minor())
  227. }
  228. case NamedPipe:
  229. t, ok := target.(NamedPipe)
  230. if !ok {
  231. return fmt.Errorf("resource %q is not a named pipe", t.Path())
  232. }
  233. default:
  234. return fmt.Errorf("cannot verify resource: %v", resource)
  235. }
  236. return nil
  237. }
  238. // Verify the resource in the context. An error will be returned a discrepancy
  239. // is found.
  240. func (c *context) Verify(resource Resource) error {
  241. fp, err := c.fullpath(resource.Path())
  242. if err != nil {
  243. return err
  244. }
  245. fi, err := c.driver.Lstat(fp)
  246. if err != nil {
  247. return err
  248. }
  249. target, err := c.Resource(resource.Path(), fi)
  250. if err != nil {
  251. return err
  252. }
  253. if target.Path() != resource.Path() {
  254. return fmt.Errorf("resource paths do not match: %q != %q", target.Path(), resource.Path())
  255. }
  256. if err := c.verifyMetadata(resource, target); err != nil {
  257. return err
  258. }
  259. if h, isHardlinkable := resource.(Hardlinkable); isHardlinkable {
  260. hardlinkKey, err := newHardlinkKey(fi)
  261. if err == errNotAHardLink {
  262. if len(h.Paths()) > 1 {
  263. return fmt.Errorf("%q is not a hardlink to %q", h.Paths()[1], resource.Path())
  264. }
  265. } else if err != nil {
  266. return err
  267. }
  268. for _, path := range h.Paths()[1:] {
  269. fpLink, err := c.fullpath(path)
  270. if err != nil {
  271. return err
  272. }
  273. fiLink, err := c.driver.Lstat(fpLink)
  274. if err != nil {
  275. return err
  276. }
  277. targetLink, err := c.Resource(path, fiLink)
  278. if err != nil {
  279. return err
  280. }
  281. hardlinkKeyLink, err := newHardlinkKey(fiLink)
  282. if err != nil {
  283. return err
  284. }
  285. if hardlinkKeyLink != hardlinkKey {
  286. return fmt.Errorf("%q is not a hardlink to %q", path, resource.Path())
  287. }
  288. if err := c.verifyMetadata(resource, targetLink); err != nil {
  289. return err
  290. }
  291. }
  292. }
  293. switch r := resource.(type) {
  294. case RegularFile:
  295. t, ok := target.(RegularFile)
  296. if !ok {
  297. return fmt.Errorf("resource %q target not a regular file", r.Path())
  298. }
  299. // TODO(stevvooe): This may need to get a little more sophisticated
  300. // for digest comparison. We may want to actually calculate the
  301. // provided digests, rather than the implementations having an
  302. // overlap.
  303. if !digestsMatch(t.Digests(), r.Digests()) {
  304. return fmt.Errorf("digests for resource %q do not match: %v != %v", t.Path(), t.Digests(), r.Digests())
  305. }
  306. }
  307. return nil
  308. }
  309. func (c *context) checkoutFile(fp string, rf RegularFile) error {
  310. if c.provider == nil {
  311. return fmt.Errorf("no file provider")
  312. }
  313. var (
  314. r io.ReadCloser
  315. err error
  316. )
  317. for _, dgst := range rf.Digests() {
  318. r, err = c.provider.Reader(dgst)
  319. if err == nil {
  320. break
  321. }
  322. }
  323. if err != nil {
  324. return fmt.Errorf("file content could not be provided: %v", err)
  325. }
  326. defer r.Close()
  327. return atomicWriteFile(fp, r, rf.Size(), rf.Mode())
  328. }
  329. // Apply the resource to the contexts. An error will be returned if the
  330. // operation fails. Depending on the resource type, the resource may be
  331. // created. For resource that cannot be resolved, an error will be returned.
  332. func (c *context) Apply(resource Resource) error {
  333. fp, err := c.fullpath(resource.Path())
  334. if err != nil {
  335. return err
  336. }
  337. if !strings.HasPrefix(fp, c.root) {
  338. return fmt.Errorf("resource %v escapes root", resource)
  339. }
  340. var chmod = true
  341. fi, err := c.driver.Lstat(fp)
  342. if err != nil {
  343. if !os.IsNotExist(err) {
  344. return err
  345. }
  346. }
  347. switch r := resource.(type) {
  348. case RegularFile:
  349. if fi == nil {
  350. if err := c.checkoutFile(fp, r); err != nil {
  351. return fmt.Errorf("error checking out file %q: %v", resource.Path(), err)
  352. }
  353. chmod = false
  354. } else {
  355. if !fi.Mode().IsRegular() {
  356. return fmt.Errorf("file %q should be a regular file, but is not", resource.Path())
  357. }
  358. if fi.Size() != r.Size() {
  359. if err := c.checkoutFile(fp, r); err != nil {
  360. return fmt.Errorf("error checking out file %q: %v", resource.Path(), err)
  361. }
  362. } else {
  363. for _, dgst := range r.Digests() {
  364. f, err := os.Open(fp)
  365. if err != nil {
  366. return fmt.Errorf("failure opening file for read %q: %v", resource.Path(), err)
  367. }
  368. compared, err := dgst.Algorithm().FromReader(f)
  369. if err == nil && dgst != compared {
  370. if err := c.checkoutFile(fp, r); err != nil {
  371. return fmt.Errorf("error checking out file %q: %v", resource.Path(), err)
  372. }
  373. break
  374. }
  375. if err1 := f.Close(); err == nil {
  376. err = err1
  377. }
  378. if err != nil {
  379. return fmt.Errorf("error checking digest for %q: %v", resource.Path(), err)
  380. }
  381. }
  382. }
  383. }
  384. case Directory:
  385. if fi == nil {
  386. if err := c.driver.Mkdir(fp, resource.Mode()); err != nil {
  387. return err
  388. }
  389. } else if !fi.Mode().IsDir() {
  390. return fmt.Errorf("%q should be a directory, but is not", resource.Path())
  391. }
  392. case SymLink:
  393. var target string // only possibly set if target resource is a symlink
  394. if fi != nil {
  395. if fi.Mode()&os.ModeSymlink != 0 {
  396. target, err = c.driver.Readlink(fp)
  397. if err != nil {
  398. return err
  399. }
  400. }
  401. }
  402. if target != r.Target() {
  403. if fi != nil {
  404. if err := c.driver.Remove(fp); err != nil { // RemoveAll in case of directory?
  405. return err
  406. }
  407. }
  408. if err := c.driver.Symlink(r.Target(), fp); err != nil {
  409. return err
  410. }
  411. }
  412. case Device:
  413. if fi == nil {
  414. if err := c.driver.Mknod(fp, resource.Mode(), int(r.Major()), int(r.Minor())); err != nil {
  415. return err
  416. }
  417. } else if (fi.Mode() & os.ModeDevice) == 0 {
  418. return fmt.Errorf("%q should be a device, but is not", resource.Path())
  419. } else {
  420. major, minor, err := devices.DeviceInfo(fi)
  421. if err != nil {
  422. return err
  423. }
  424. if major != r.Major() || minor != r.Minor() {
  425. if err := c.driver.Remove(fp); err != nil {
  426. return err
  427. }
  428. if err := c.driver.Mknod(fp, resource.Mode(), int(r.Major()), int(r.Minor())); err != nil {
  429. return err
  430. }
  431. }
  432. }
  433. case NamedPipe:
  434. if fi == nil {
  435. if err := c.driver.Mkfifo(fp, resource.Mode()); err != nil {
  436. return err
  437. }
  438. } else if (fi.Mode() & os.ModeNamedPipe) == 0 {
  439. return fmt.Errorf("%q should be a named pipe, but is not", resource.Path())
  440. }
  441. }
  442. if h, isHardlinkable := resource.(Hardlinkable); isHardlinkable {
  443. for _, path := range h.Paths() {
  444. if path == resource.Path() {
  445. continue
  446. }
  447. lp, err := c.fullpath(path)
  448. if err != nil {
  449. return err
  450. }
  451. if _, fi := c.driver.Lstat(lp); fi == nil {
  452. c.driver.Remove(lp)
  453. }
  454. if err := c.driver.Link(fp, lp); err != nil {
  455. return err
  456. }
  457. }
  458. }
  459. // Update filemode if file was not created
  460. if chmod {
  461. if err := c.driver.Lchmod(fp, resource.Mode()); err != nil {
  462. return err
  463. }
  464. }
  465. if err := c.driver.Lchown(fp, resource.UID(), resource.GID()); err != nil {
  466. return err
  467. }
  468. if xattrer, ok := resource.(XAttrer); ok {
  469. // For xattrs, only ensure that we have those defined in the resource
  470. // and their values are set. We can ignore other xattrs. In other words,
  471. // we only set xattres defined by resource but never remove.
  472. if _, ok := resource.(SymLink); ok {
  473. lxattrDriver, ok := c.driver.(driverpkg.LXAttrDriver)
  474. if !ok {
  475. return fmt.Errorf("unsupported symlink xattr for resource %q", resource.Path())
  476. }
  477. if err := lxattrDriver.LSetxattr(fp, xattrer.XAttrs()); err != nil {
  478. return err
  479. }
  480. } else {
  481. xattrDriver, ok := c.driver.(driverpkg.XAttrDriver)
  482. if !ok {
  483. return fmt.Errorf("unsupported xattr for resource %q", resource.Path())
  484. }
  485. if err := xattrDriver.Setxattr(fp, xattrer.XAttrs()); err != nil {
  486. return err
  487. }
  488. }
  489. }
  490. return nil
  491. }
  492. // Walk provides a convenience function to call filepath.Walk correctly for
  493. // the context. Otherwise identical to filepath.Walk, the path argument is
  494. // corrected to be contained within the context.
  495. func (c *context) Walk(fn filepath.WalkFunc) error {
  496. root := c.root
  497. fi, err := c.driver.Lstat(c.root)
  498. if err == nil && fi.Mode()&os.ModeSymlink != 0 {
  499. root, err = c.driver.Readlink(c.root)
  500. if err != nil {
  501. return err
  502. }
  503. }
  504. return c.pathDriver.Walk(root, func(p string, fi os.FileInfo, err error) error {
  505. contained, err := c.containWithRoot(p, root)
  506. return fn(contained, fi, err)
  507. })
  508. }
  509. // fullpath returns the system path for the resource, joined with the context
  510. // root. The path p must be a part of the context.
  511. func (c *context) fullpath(p string) (string, error) {
  512. p = c.pathDriver.Join(c.root, p)
  513. if !strings.HasPrefix(p, c.root) {
  514. return "", fmt.Errorf("invalid context path")
  515. }
  516. return p, nil
  517. }
  518. // contain cleans and santizes the filesystem path p to be an absolute path,
  519. // effectively relative to the context root.
  520. func (c *context) contain(p string) (string, error) {
  521. return c.containWithRoot(p, c.root)
  522. }
  523. // containWithRoot cleans and santizes the filesystem path p to be an absolute path,
  524. // effectively relative to the passed root. Extra care should be used when calling this
  525. // instead of contain. This is needed for Walk, as if context root is a symlink,
  526. // it must be evaluated prior to the Walk
  527. func (c *context) containWithRoot(p string, root string) (string, error) {
  528. sanitized, err := c.pathDriver.Rel(root, p)
  529. if err != nil {
  530. return "", err
  531. }
  532. // ZOMBIES(stevvooe): In certain cases, we may want to remap these to a
  533. // "containment error", so the caller can decide what to do.
  534. return c.pathDriver.Join("/", c.pathDriver.Clean(sanitized)), nil
  535. }
  536. // digest returns the digest of the file at path p, relative to the root.
  537. func (c *context) digest(p string) (digest.Digest, error) {
  538. f, err := c.driver.Open(c.pathDriver.Join(c.root, p))
  539. if err != nil {
  540. return "", err
  541. }
  542. defer f.Close()
  543. return c.digester.Digest(f)
  544. }
  545. // resolveXAttrs attempts to resolve the extended attributes for the resource
  546. // at the path fp, which is the full path to the resource. If the resource
  547. // cannot have xattrs, nil will be returned.
  548. func (c *context) resolveXAttrs(fp string, fi os.FileInfo, base *resource) (map[string][]byte, error) {
  549. if fi.Mode().IsRegular() || fi.Mode().IsDir() {
  550. xattrDriver, ok := c.driver.(driverpkg.XAttrDriver)
  551. if !ok {
  552. log.Println("xattr extraction not supported")
  553. return nil, ErrNotSupported
  554. }
  555. return xattrDriver.Getxattr(fp)
  556. }
  557. if fi.Mode()&os.ModeSymlink != 0 {
  558. lxattrDriver, ok := c.driver.(driverpkg.LXAttrDriver)
  559. if !ok {
  560. log.Println("xattr extraction for symlinks not supported")
  561. return nil, ErrNotSupported
  562. }
  563. return lxattrDriver.LGetxattr(fp)
  564. }
  565. return nil, nil
  566. }