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