windows_parser.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. package volume
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "regexp"
  7. "runtime"
  8. "strings"
  9. "github.com/docker/docker/api/types/mount"
  10. "github.com/docker/docker/pkg/stringid"
  11. )
  12. type windowsParser struct {
  13. }
  14. const (
  15. // Spec should be in the format [source:]destination[:mode]
  16. //
  17. // Examples: c:\foo bar:d:rw
  18. // c:\foo:d:\bar
  19. // myname:d:
  20. // d:\
  21. //
  22. // Explanation of this regex! Thanks @thaJeztah on IRC and gist for help. See
  23. // https://gist.github.com/thaJeztah/6185659e4978789fb2b2. A good place to
  24. // test is https://regex-golang.appspot.com/assets/html/index.html
  25. //
  26. // Useful link for referencing named capturing groups:
  27. // http://stackoverflow.com/questions/20750843/using-named-matches-from-go-regex
  28. //
  29. // There are three match groups: source, destination and mode.
  30. //
  31. // rxHostDir is the first option of a source
  32. rxHostDir = `(?:\\\\\?\\)?[a-z]:[\\/](?:[^\\/:*?"<>|\r\n]+[\\/]?)*`
  33. // rxName is the second option of a source
  34. rxName = `[^\\/:*?"<>|\r\n]+`
  35. // RXReservedNames are reserved names not possible on Windows
  36. rxReservedNames = `(con)|(prn)|(nul)|(aux)|(com[1-9])|(lpt[1-9])`
  37. // rxPipe is a named path pipe (starts with `\\.\pipe\`, possibly with / instead of \)
  38. rxPipe = `[/\\]{2}.[/\\]pipe[/\\][^:*?"<>|\r\n]+`
  39. // rxSource is the combined possibilities for a source
  40. rxSource = `((?P<source>((` + rxHostDir + `)|(` + rxName + `)|(` + rxPipe + `))):)?`
  41. // Source. Can be either a host directory, a name, or omitted:
  42. // HostDir:
  43. // - Essentially using the folder solution from
  44. // https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch08s18.html
  45. // but adding case insensitivity.
  46. // - Must be an absolute path such as c:\path
  47. // - Can include spaces such as `c:\program files`
  48. // - And then followed by a colon which is not in the capture group
  49. // - And can be optional
  50. // Name:
  51. // - Must not contain invalid NTFS filename characters (https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx)
  52. // - And then followed by a colon which is not in the capture group
  53. // - And can be optional
  54. // rxDestination is the regex expression for the mount destination
  55. rxDestination = `(?P<destination>((?:\\\\\?\\)?([a-z]):((?:[\\/][^\\/:*?"<>\r\n]+)*[\\/]?))|(` + rxPipe + `))`
  56. rxLCOWDestination = `(?P<destination>/(?:[^\\/:*?"<>\r\n]+[/]?)*)`
  57. // Destination (aka container path):
  58. // - Variation on hostdir but can be a drive followed by colon as well
  59. // - If a path, must be absolute. Can include spaces
  60. // - Drive cannot be c: (explicitly checked in code, not RegEx)
  61. // rxMode is the regex expression for the mode of the mount
  62. // Mode (optional):
  63. // - Hopefully self explanatory in comparison to above regex's.
  64. // - Colon is not in the capture group
  65. rxMode = `(:(?P<mode>(?i)ro|rw))?`
  66. )
  67. type mountValidator func(mnt *mount.Mount) error
  68. func windowsSplitRawSpec(raw, destRegex string) ([]string, error) {
  69. specExp := regexp.MustCompile(`^` + rxSource + destRegex + rxMode + `$`)
  70. match := specExp.FindStringSubmatch(strings.ToLower(raw))
  71. // Must have something back
  72. if len(match) == 0 {
  73. return nil, errInvalidSpec(raw)
  74. }
  75. var split []string
  76. matchgroups := make(map[string]string)
  77. // Pull out the sub expressions from the named capture groups
  78. for i, name := range specExp.SubexpNames() {
  79. matchgroups[name] = strings.ToLower(match[i])
  80. }
  81. if source, exists := matchgroups["source"]; exists {
  82. if source != "" {
  83. split = append(split, source)
  84. }
  85. }
  86. if destination, exists := matchgroups["destination"]; exists {
  87. if destination != "" {
  88. split = append(split, destination)
  89. }
  90. }
  91. if mode, exists := matchgroups["mode"]; exists {
  92. if mode != "" {
  93. split = append(split, mode)
  94. }
  95. }
  96. // Fix #26329. If the destination appears to be a file, and the source is null,
  97. // it may be because we've fallen through the possible naming regex and hit a
  98. // situation where the user intention was to map a file into a container through
  99. // a local volume, but this is not supported by the platform.
  100. if matchgroups["source"] == "" && matchgroups["destination"] != "" {
  101. volExp := regexp.MustCompile(`^` + rxName + `$`)
  102. reservedNameExp := regexp.MustCompile(`^` + rxReservedNames + `$`)
  103. if volExp.MatchString(matchgroups["destination"]) {
  104. if reservedNameExp.MatchString(matchgroups["destination"]) {
  105. return nil, fmt.Errorf("volume name %q cannot be a reserved word for Windows filenames", matchgroups["destination"])
  106. }
  107. } else {
  108. exists, isDir, _ := currentFileInfoProvider.fileInfo(matchgroups["destination"])
  109. if exists && !isDir {
  110. return nil, fmt.Errorf("file '%s' cannot be mapped. Only directories can be mapped on this platform", matchgroups["destination"])
  111. }
  112. }
  113. }
  114. return split, nil
  115. }
  116. func windowsValidMountMode(mode string) bool {
  117. if mode == "" {
  118. return true
  119. }
  120. return rwModes[strings.ToLower(mode)]
  121. }
  122. func windowsValidateNotRoot(p string) error {
  123. p = strings.ToLower(strings.Replace(p, `/`, `\`, -1))
  124. if p == "c:" || p == `c:\` {
  125. return fmt.Errorf("destination path cannot be `c:` or `c:\\`: %v", p)
  126. }
  127. return nil
  128. }
  129. var windowsSpecificValidators mountValidator = func(mnt *mount.Mount) error {
  130. return windowsValidateNotRoot(mnt.Target)
  131. }
  132. func windowsValidateRegex(p, r string) error {
  133. if regexp.MustCompile(`^` + r + `$`).MatchString(strings.ToLower(p)) {
  134. return nil
  135. }
  136. return fmt.Errorf("invalid mount path: '%s'", p)
  137. }
  138. func windowsValidateAbsolute(p string) error {
  139. if err := windowsValidateRegex(p, rxDestination); err != nil {
  140. return fmt.Errorf("invalid mount path: '%s' mount path must be absolute", p)
  141. }
  142. return nil
  143. }
  144. func windowsDetectMountType(p string) mount.Type {
  145. if strings.HasPrefix(p, `\\.\pipe\`) {
  146. return mount.TypeNamedPipe
  147. } else if regexp.MustCompile(`^` + rxHostDir + `$`).MatchString(p) {
  148. return mount.TypeBind
  149. } else {
  150. return mount.TypeVolume
  151. }
  152. }
  153. func (p *windowsParser) ReadWrite(mode string) bool {
  154. return strings.ToLower(mode) != "ro"
  155. }
  156. // IsVolumeNameValid checks a volume name in a platform specific manner.
  157. func (p *windowsParser) ValidateVolumeName(name string) error {
  158. nameExp := regexp.MustCompile(`^` + rxName + `$`)
  159. if !nameExp.MatchString(name) {
  160. return errors.New("invalid volume name")
  161. }
  162. nameExp = regexp.MustCompile(`^` + rxReservedNames + `$`)
  163. if nameExp.MatchString(name) {
  164. return fmt.Errorf("volume name %q cannot be a reserved word for Windows filenames", name)
  165. }
  166. return nil
  167. }
  168. func (p *windowsParser) ValidateMountConfig(mnt *mount.Mount) error {
  169. return p.validateMountConfigReg(mnt, rxDestination, windowsSpecificValidators)
  170. }
  171. type fileInfoProvider interface {
  172. fileInfo(path string) (exist, isDir bool, err error)
  173. }
  174. type defaultFileInfoProvider struct {
  175. }
  176. func (defaultFileInfoProvider) fileInfo(path string) (exist, isDir bool, err error) {
  177. fi, err := os.Stat(path)
  178. if err != nil {
  179. if !os.IsNotExist(err) {
  180. return false, false, err
  181. }
  182. return false, false, nil
  183. }
  184. return true, fi.IsDir(), nil
  185. }
  186. var currentFileInfoProvider fileInfoProvider = defaultFileInfoProvider{}
  187. func (p *windowsParser) validateMountConfigReg(mnt *mount.Mount, destRegex string, additionalValidators ...mountValidator) error {
  188. for _, v := range additionalValidators {
  189. if err := v(mnt); err != nil {
  190. return &errMountConfig{mnt, err}
  191. }
  192. }
  193. if len(mnt.Target) == 0 {
  194. return &errMountConfig{mnt, errMissingField("Target")}
  195. }
  196. if err := windowsValidateRegex(mnt.Target, destRegex); err != nil {
  197. return &errMountConfig{mnt, err}
  198. }
  199. switch mnt.Type {
  200. case mount.TypeBind:
  201. if len(mnt.Source) == 0 {
  202. return &errMountConfig{mnt, errMissingField("Source")}
  203. }
  204. // Don't error out just because the propagation mode is not supported on the platform
  205. if opts := mnt.BindOptions; opts != nil {
  206. if len(opts.Propagation) > 0 {
  207. return &errMountConfig{mnt, fmt.Errorf("invalid propagation mode: %s", opts.Propagation)}
  208. }
  209. }
  210. if mnt.VolumeOptions != nil {
  211. return &errMountConfig{mnt, errExtraField("VolumeOptions")}
  212. }
  213. if err := windowsValidateAbsolute(mnt.Source); err != nil {
  214. return &errMountConfig{mnt, err}
  215. }
  216. exists, isdir, err := currentFileInfoProvider.fileInfo(mnt.Source)
  217. if err != nil {
  218. return &errMountConfig{mnt, err}
  219. }
  220. if !exists {
  221. return &errMountConfig{mnt, errBindNotExist}
  222. }
  223. if !isdir {
  224. return &errMountConfig{mnt, fmt.Errorf("source path must be a directory")}
  225. }
  226. case mount.TypeVolume:
  227. if mnt.BindOptions != nil {
  228. return &errMountConfig{mnt, errExtraField("BindOptions")}
  229. }
  230. if len(mnt.Source) == 0 && mnt.ReadOnly {
  231. return &errMountConfig{mnt, fmt.Errorf("must not set ReadOnly mode when using anonymous volumes")}
  232. }
  233. if len(mnt.Source) != 0 {
  234. if err := p.ValidateVolumeName(mnt.Source); err != nil {
  235. return &errMountConfig{mnt, err}
  236. }
  237. }
  238. case mount.TypeNamedPipe:
  239. if len(mnt.Source) == 0 {
  240. return &errMountConfig{mnt, errMissingField("Source")}
  241. }
  242. if mnt.BindOptions != nil {
  243. return &errMountConfig{mnt, errExtraField("BindOptions")}
  244. }
  245. if mnt.ReadOnly {
  246. return &errMountConfig{mnt, errExtraField("ReadOnly")}
  247. }
  248. if windowsDetectMountType(mnt.Source) != mount.TypeNamedPipe {
  249. return &errMountConfig{mnt, fmt.Errorf("'%s' is not a valid pipe path", mnt.Source)}
  250. }
  251. if windowsDetectMountType(mnt.Target) != mount.TypeNamedPipe {
  252. return &errMountConfig{mnt, fmt.Errorf("'%s' is not a valid pipe path", mnt.Target)}
  253. }
  254. default:
  255. return &errMountConfig{mnt, errors.New("mount type unknown")}
  256. }
  257. return nil
  258. }
  259. func (p *windowsParser) ParseMountRaw(raw, volumeDriver string) (*MountPoint, error) {
  260. return p.parseMountRaw(raw, volumeDriver, rxDestination, true, windowsSpecificValidators)
  261. }
  262. func (p *windowsParser) parseMountRaw(raw, volumeDriver, destRegex string, convertTargetToBackslash bool, additionalValidators ...mountValidator) (*MountPoint, error) {
  263. arr, err := windowsSplitRawSpec(raw, destRegex)
  264. if err != nil {
  265. return nil, err
  266. }
  267. var spec mount.Mount
  268. var mode string
  269. switch len(arr) {
  270. case 1:
  271. // Just a destination path in the container
  272. spec.Target = arr[0]
  273. case 2:
  274. if windowsValidMountMode(arr[1]) {
  275. // Destination + Mode is not a valid volume - volumes
  276. // cannot include a mode. e.g. /foo:rw
  277. return nil, errInvalidSpec(raw)
  278. }
  279. // Host Source Path or Name + Destination
  280. spec.Source = strings.Replace(arr[0], `/`, `\`, -1)
  281. spec.Target = arr[1]
  282. case 3:
  283. // HostSourcePath+DestinationPath+Mode
  284. spec.Source = strings.Replace(arr[0], `/`, `\`, -1)
  285. spec.Target = arr[1]
  286. mode = arr[2]
  287. default:
  288. return nil, errInvalidSpec(raw)
  289. }
  290. if convertTargetToBackslash {
  291. spec.Target = strings.Replace(spec.Target, `/`, `\`, -1)
  292. }
  293. if !windowsValidMountMode(mode) {
  294. return nil, errInvalidMode(mode)
  295. }
  296. spec.Type = windowsDetectMountType(spec.Source)
  297. spec.ReadOnly = !p.ReadWrite(mode)
  298. // cannot assume that if a volume driver is passed in that we should set it
  299. if volumeDriver != "" && spec.Type == mount.TypeVolume {
  300. spec.VolumeOptions = &mount.VolumeOptions{
  301. DriverConfig: &mount.Driver{Name: volumeDriver},
  302. }
  303. }
  304. if copyData, isSet := getCopyMode(mode, p.DefaultCopyMode()); isSet {
  305. if spec.VolumeOptions == nil {
  306. spec.VolumeOptions = &mount.VolumeOptions{}
  307. }
  308. spec.VolumeOptions.NoCopy = !copyData
  309. }
  310. mp, err := p.parseMountSpec(spec, destRegex, convertTargetToBackslash, additionalValidators...)
  311. if mp != nil {
  312. mp.Mode = mode
  313. }
  314. if err != nil {
  315. err = fmt.Errorf("%v: %v", errInvalidSpec(raw), err)
  316. }
  317. return mp, err
  318. }
  319. func (p *windowsParser) ParseMountSpec(cfg mount.Mount) (*MountPoint, error) {
  320. return p.parseMountSpec(cfg, rxDestination, true, windowsSpecificValidators)
  321. }
  322. func (p *windowsParser) parseMountSpec(cfg mount.Mount, destRegex string, convertTargetToBackslash bool, additionalValidators ...mountValidator) (*MountPoint, error) {
  323. if err := p.validateMountConfigReg(&cfg, destRegex, additionalValidators...); err != nil {
  324. return nil, err
  325. }
  326. mp := &MountPoint{
  327. RW: !cfg.ReadOnly,
  328. Destination: cfg.Target,
  329. Type: cfg.Type,
  330. Spec: cfg,
  331. }
  332. if convertTargetToBackslash {
  333. mp.Destination = strings.Replace(cfg.Target, `/`, `\`, -1)
  334. }
  335. switch cfg.Type {
  336. case mount.TypeVolume:
  337. if cfg.Source == "" {
  338. mp.Name = stringid.GenerateNonCryptoID()
  339. } else {
  340. mp.Name = cfg.Source
  341. }
  342. mp.CopyData = p.DefaultCopyMode()
  343. if cfg.VolumeOptions != nil {
  344. if cfg.VolumeOptions.DriverConfig != nil {
  345. mp.Driver = cfg.VolumeOptions.DriverConfig.Name
  346. }
  347. if cfg.VolumeOptions.NoCopy {
  348. mp.CopyData = false
  349. }
  350. }
  351. case mount.TypeBind:
  352. mp.Source = strings.Replace(cfg.Source, `/`, `\`, -1)
  353. case mount.TypeNamedPipe:
  354. mp.Source = strings.Replace(cfg.Source, `/`, `\`, -1)
  355. }
  356. // cleanup trailing `\` except for paths like `c:\`
  357. if len(mp.Source) > 3 && mp.Source[len(mp.Source)-1] == '\\' {
  358. mp.Source = mp.Source[:len(mp.Source)-1]
  359. }
  360. if len(mp.Destination) > 3 && mp.Destination[len(mp.Destination)-1] == '\\' {
  361. mp.Destination = mp.Destination[:len(mp.Destination)-1]
  362. }
  363. return mp, nil
  364. }
  365. func (p *windowsParser) ParseVolumesFrom(spec string) (string, string, error) {
  366. if len(spec) == 0 {
  367. return "", "", fmt.Errorf("volumes-from specification cannot be an empty string")
  368. }
  369. specParts := strings.SplitN(spec, ":", 2)
  370. id := specParts[0]
  371. mode := "rw"
  372. if len(specParts) == 2 {
  373. mode = specParts[1]
  374. if !windowsValidMountMode(mode) {
  375. return "", "", errInvalidMode(mode)
  376. }
  377. // Do not allow copy modes on volumes-from
  378. if _, isSet := getCopyMode(mode, p.DefaultCopyMode()); isSet {
  379. return "", "", errInvalidMode(mode)
  380. }
  381. }
  382. return id, mode, nil
  383. }
  384. func (p *windowsParser) DefaultPropagationMode() mount.Propagation {
  385. return mount.Propagation("")
  386. }
  387. func (p *windowsParser) ConvertTmpfsOptions(opt *mount.TmpfsOptions, readOnly bool) (string, error) {
  388. return "", fmt.Errorf("%s does not support tmpfs", runtime.GOOS)
  389. }
  390. func (p *windowsParser) DefaultCopyMode() bool {
  391. return false
  392. }
  393. func (p *windowsParser) IsBackwardCompatible(m *MountPoint) bool {
  394. return false
  395. }
  396. func (p *windowsParser) ValidateTmpfsMountDestination(dest string) error {
  397. return errors.New("Platform does not support tmpfs")
  398. }