github.com/pwn-term/docker@v0.0.0-20210616085119-6e977cce2565/moby/builder/dockerfile/dispatchers.go (about) 1 package dockerfile // import "github.com/docker/docker/builder/dockerfile" 2 3 // This file contains the dispatchers for each command. Note that 4 // `nullDispatch` is not actually a command, but support for commands we parse 5 // but do nothing with. 6 // 7 // See evaluator.go for a higher level discussion of the whole evaluator 8 // package. 9 10 import ( 11 "bytes" 12 "fmt" 13 "runtime" 14 "sort" 15 "strings" 16 17 "github.com/containerd/containerd/platforms" 18 "github.com/docker/docker/api" 19 "github.com/docker/docker/api/types/strslice" 20 "github.com/docker/docker/builder" 21 "github.com/docker/docker/errdefs" 22 "github.com/docker/docker/image" 23 "github.com/docker/docker/pkg/jsonmessage" 24 "github.com/docker/docker/pkg/signal" 25 "github.com/docker/docker/pkg/system" 26 "github.com/docker/go-connections/nat" 27 "github.com/moby/buildkit/frontend/dockerfile/instructions" 28 "github.com/moby/buildkit/frontend/dockerfile/parser" 29 "github.com/moby/buildkit/frontend/dockerfile/shell" 30 specs "github.com/opencontainers/image-spec/specs-go/v1" 31 "github.com/pkg/errors" 32 ) 33 34 // ENV foo bar 35 // 36 // Sets the environment variable foo to bar, also makes interpolation 37 // in the dockerfile available from the next statement on via ${foo}. 38 // 39 func dispatchEnv(d dispatchRequest, c *instructions.EnvCommand) error { 40 runConfig := d.state.runConfig 41 commitMessage := bytes.NewBufferString("ENV") 42 for _, e := range c.Env { 43 name := e.Key 44 newVar := e.String() 45 46 commitMessage.WriteString(" " + newVar) 47 gotOne := false 48 for i, envVar := range runConfig.Env { 49 envParts := strings.SplitN(envVar, "=", 2) 50 compareFrom := envParts[0] 51 if shell.EqualEnvKeys(compareFrom, name) { 52 runConfig.Env[i] = newVar 53 gotOne = true 54 break 55 } 56 } 57 if !gotOne { 58 runConfig.Env = append(runConfig.Env, newVar) 59 } 60 } 61 return d.builder.commit(d.state, commitMessage.String()) 62 } 63 64 // MAINTAINER some text <maybe@an.email.address> 65 // 66 // Sets the maintainer metadata. 67 func dispatchMaintainer(d dispatchRequest, c *instructions.MaintainerCommand) error { 68 69 d.state.maintainer = c.Maintainer 70 return d.builder.commit(d.state, "MAINTAINER "+c.Maintainer) 71 } 72 73 // LABEL some json data describing the image 74 // 75 // Sets the Label variable foo to bar, 76 // 77 func dispatchLabel(d dispatchRequest, c *instructions.LabelCommand) error { 78 if d.state.runConfig.Labels == nil { 79 d.state.runConfig.Labels = make(map[string]string) 80 } 81 commitStr := "LABEL" 82 for _, v := range c.Labels { 83 d.state.runConfig.Labels[v.Key] = v.Value 84 commitStr += " " + v.String() 85 } 86 return d.builder.commit(d.state, commitStr) 87 } 88 89 // ADD foo /path 90 // 91 // Add the file 'foo' to '/path'. Tarball and Remote URL (http, https) handling 92 // exist here. If you do not wish to have this automatic handling, use COPY. 93 // 94 func dispatchAdd(d dispatchRequest, c *instructions.AddCommand) error { 95 downloader := newRemoteSourceDownloader(d.builder.Output, d.builder.Stdout) 96 copier := copierFromDispatchRequest(d, downloader, nil) 97 defer copier.Cleanup() 98 99 copyInstruction, err := copier.createCopyInstruction(c.SourcesAndDest, "ADD") 100 if err != nil { 101 return err 102 } 103 copyInstruction.chownStr = c.Chown 104 copyInstruction.allowLocalDecompression = true 105 106 return d.builder.performCopy(d, copyInstruction) 107 } 108 109 // COPY foo /path 110 // 111 // Same as 'ADD' but without the tar and remote url handling. 112 // 113 func dispatchCopy(d dispatchRequest, c *instructions.CopyCommand) error { 114 var im *imageMount 115 var err error 116 if c.From != "" { 117 im, err = d.getImageMount(c.From) 118 if err != nil { 119 return errors.Wrapf(err, "invalid from flag value %s", c.From) 120 } 121 } 122 copier := copierFromDispatchRequest(d, errOnSourceDownload, im) 123 defer copier.Cleanup() 124 copyInstruction, err := copier.createCopyInstruction(c.SourcesAndDest, "COPY") 125 if err != nil { 126 return err 127 } 128 copyInstruction.chownStr = c.Chown 129 if c.From != "" && copyInstruction.chownStr == "" { 130 copyInstruction.preserveOwnership = true 131 } 132 return d.builder.performCopy(d, copyInstruction) 133 } 134 135 func (d *dispatchRequest) getImageMount(imageRefOrID string) (*imageMount, error) { 136 if imageRefOrID == "" { 137 // TODO: this could return the source in the default case as well? 138 return nil, nil 139 } 140 141 var localOnly bool 142 stage, err := d.stages.get(imageRefOrID) 143 if err != nil { 144 return nil, err 145 } 146 if stage != nil { 147 imageRefOrID = stage.Image 148 localOnly = true 149 } 150 return d.builder.imageSources.Get(imageRefOrID, localOnly, d.builder.platform) 151 } 152 153 // FROM [--platform=platform] imagename[:tag | @digest] [AS build-stage-name] 154 // 155 func initializeStage(d dispatchRequest, cmd *instructions.Stage) error { 156 d.builder.imageProber.Reset() 157 158 var platform *specs.Platform 159 if v := cmd.Platform; v != "" { 160 v, err := d.getExpandedString(d.shlex, v) 161 if err != nil { 162 return errors.Wrapf(err, "failed to process arguments for platform %s", v) 163 } 164 165 p, err := platforms.Parse(v) 166 if err != nil { 167 return errors.Wrapf(err, "failed to parse platform %s", v) 168 } 169 if err := system.ValidatePlatform(p); err != nil { 170 return err 171 } 172 platform = &p 173 } 174 175 image, err := d.getFromImage(d.shlex, cmd.BaseName, platform) 176 if err != nil { 177 return err 178 } 179 state := d.state 180 if err := state.beginStage(cmd.Name, image); err != nil { 181 return err 182 } 183 if len(state.runConfig.OnBuild) > 0 { 184 triggers := state.runConfig.OnBuild 185 state.runConfig.OnBuild = nil 186 return dispatchTriggeredOnBuild(d, triggers) 187 } 188 return nil 189 } 190 191 func dispatchTriggeredOnBuild(d dispatchRequest, triggers []string) error { 192 fmt.Fprintf(d.builder.Stdout, "# Executing %d build trigger", len(triggers)) 193 if len(triggers) > 1 { 194 fmt.Fprint(d.builder.Stdout, "s") 195 } 196 fmt.Fprintln(d.builder.Stdout) 197 for _, trigger := range triggers { 198 d.state.updateRunConfig() 199 ast, err := parser.Parse(strings.NewReader(trigger)) 200 if err != nil { 201 return err 202 } 203 if len(ast.AST.Children) != 1 { 204 return errors.New("onbuild trigger should be a single expression") 205 } 206 cmd, err := instructions.ParseCommand(ast.AST.Children[0]) 207 if err != nil { 208 var uiErr *instructions.UnknownInstruction 209 if errors.As(err, &uiErr) { 210 buildsFailed.WithValues(metricsUnknownInstructionError).Inc() 211 } 212 return err 213 } 214 err = dispatch(d, cmd) 215 if err != nil { 216 return err 217 } 218 } 219 return nil 220 } 221 222 func (d *dispatchRequest) getExpandedString(shlex *shell.Lex, str string) (string, error) { 223 substitutionArgs := []string{} 224 for key, value := range d.state.buildArgs.GetAllMeta() { 225 substitutionArgs = append(substitutionArgs, key+"="+value) 226 } 227 228 name, err := shlex.ProcessWord(str, substitutionArgs) 229 if err != nil { 230 return "", err 231 } 232 return name, nil 233 } 234 235 func (d *dispatchRequest) getImageOrStage(name string, platform *specs.Platform) (builder.Image, error) { 236 var localOnly bool 237 if im, ok := d.stages.getByName(name); ok { 238 name = im.Image 239 localOnly = true 240 } 241 242 if platform == nil { 243 platform = d.builder.platform 244 } 245 246 // Windows cannot support a container with no base image unless it is LCOW. 247 if name == api.NoBaseImageSpecifier { 248 p := platforms.DefaultSpec() 249 if platform != nil { 250 p = *platform 251 } 252 imageImage := &image.Image{} 253 imageImage.OS = p.OS 254 255 // old windows scratch handling 256 // TODO: scratch should not have an os. It should be nil image. 257 // Windows supports scratch. What is not supported is running containers 258 // from it. 259 if "linux" == "windows" { 260 if platform == nil || platform.OS == "linux" { 261 if !system.LCOWSupported() { 262 return nil, errors.New("Linux containers are not supported on this system") 263 } 264 imageImage.OS = "linux" 265 } else if platform.OS == "windows" { 266 return nil, errors.New("Windows does not support FROM scratch") 267 } else { 268 return nil, errors.Errorf("platform %s is not supported", platforms.Format(p)) 269 } 270 } 271 return builder.Image(imageImage), nil 272 } 273 imageMount, err := d.builder.imageSources.Get(name, localOnly, platform) 274 if err != nil { 275 return nil, err 276 } 277 return imageMount.Image(), nil 278 } 279 func (d *dispatchRequest) getFromImage(shlex *shell.Lex, basename string, platform *specs.Platform) (builder.Image, error) { 280 name, err := d.getExpandedString(shlex, basename) 281 if err != nil { 282 return nil, err 283 } 284 // Empty string is interpreted to FROM scratch by images.GetImageAndReleasableLayer, 285 // so validate expanded result is not empty. 286 if name == "" { 287 return nil, errors.Errorf("base name (%s) should not be blank", basename) 288 } 289 290 return d.getImageOrStage(name, platform) 291 } 292 293 func dispatchOnbuild(d dispatchRequest, c *instructions.OnbuildCommand) error { 294 d.state.runConfig.OnBuild = append(d.state.runConfig.OnBuild, c.Expression) 295 return d.builder.commit(d.state, "ONBUILD "+c.Expression) 296 } 297 298 // WORKDIR /tmp 299 // 300 // Set the working directory for future RUN/CMD/etc statements. 301 // 302 func dispatchWorkdir(d dispatchRequest, c *instructions.WorkdirCommand) error { 303 runConfig := d.state.runConfig 304 var err error 305 runConfig.WorkingDir, err = normalizeWorkdir(d.state.operatingSystem, runConfig.WorkingDir, c.Path) 306 if err != nil { 307 return err 308 } 309 310 // For performance reasons, we explicitly do a create/mkdir now 311 // This avoids having an unnecessary expensive mount/unmount calls 312 // (on Windows in particular) during each container create. 313 // Prior to 1.13, the mkdir was deferred and not executed at this step. 314 if d.builder.disableCommit { 315 // Don't call back into the daemon if we're going through docker commit --change "WORKDIR /foo". 316 // We've already updated the runConfig and that's enough. 317 return nil 318 } 319 320 comment := "WORKDIR " + runConfig.WorkingDir 321 runConfigWithCommentCmd := copyRunConfig(runConfig, withCmdCommentString(comment, d.state.operatingSystem)) 322 323 containerID, err := d.builder.probeAndCreate(d.state, runConfigWithCommentCmd) 324 if err != nil || containerID == "" { 325 return err 326 } 327 328 if err := d.builder.docker.ContainerCreateWorkdir(containerID); err != nil { 329 return err 330 } 331 332 return d.builder.commitContainer(d.state, containerID, runConfigWithCommentCmd) 333 } 334 335 // RUN some command yo 336 // 337 // run a command and commit the image. Args are automatically prepended with 338 // the current SHELL which defaults to 'sh -c' under linux or 'cmd /S /C' under 339 // Windows, in the event there is only one argument The difference in processing: 340 // 341 // RUN echo hi # sh -c echo hi (Linux and LCOW) 342 // RUN echo hi # cmd /S /C echo hi (Windows) 343 // RUN [ "echo", "hi" ] # echo hi 344 // 345 func dispatchRun(d dispatchRequest, c *instructions.RunCommand) error { 346 if !system.IsOSSupported(d.state.operatingSystem) { 347 return system.ErrNotSupportedOperatingSystem 348 } 349 stateRunConfig := d.state.runConfig 350 cmdFromArgs, argsEscaped := resolveCmdLine(c.ShellDependantCmdLine, stateRunConfig, d.state.operatingSystem, c.Name(), c.String()) 351 buildArgs := d.state.buildArgs.FilterAllowed(stateRunConfig.Env) 352 353 saveCmd := cmdFromArgs 354 if len(buildArgs) > 0 { 355 saveCmd = prependEnvOnCmd(d.state.buildArgs, buildArgs, cmdFromArgs) 356 } 357 358 runConfigForCacheProbe := copyRunConfig(stateRunConfig, 359 withCmd(saveCmd), 360 withArgsEscaped(argsEscaped), 361 withEntrypointOverride(saveCmd, nil)) 362 if hit, err := d.builder.probeCache(d.state, runConfigForCacheProbe); err != nil || hit { 363 return err 364 } 365 366 runConfig := copyRunConfig(stateRunConfig, 367 withCmd(cmdFromArgs), 368 withArgsEscaped(argsEscaped), 369 withEnv(append(stateRunConfig.Env, buildArgs...)), 370 withEntrypointOverride(saveCmd, strslice.StrSlice{""}), 371 withoutHealthcheck()) 372 373 cID, err := d.builder.create(runConfig) 374 if err != nil { 375 return err 376 } 377 378 if err := d.builder.containerManager.Run(d.builder.clientCtx, cID, d.builder.Stdout, d.builder.Stderr); err != nil { 379 if err, ok := err.(*statusCodeError); ok { 380 // TODO: change error type, because jsonmessage.JSONError assumes HTTP 381 msg := fmt.Sprintf( 382 "The command '%s' returned a non-zero code: %d", 383 strings.Join(runConfig.Cmd, " "), err.StatusCode()) 384 if err.Error() != "" { 385 msg = fmt.Sprintf("%s: %s", msg, err.Error()) 386 } 387 return &jsonmessage.JSONError{ 388 Message: msg, 389 Code: err.StatusCode(), 390 } 391 } 392 return err 393 } 394 395 // Don't persist the argsEscaped value in the committed image. Use the original 396 // from previous build steps (only CMD and ENTRYPOINT persist this). 397 if d.state.operatingSystem == "windows" { 398 runConfigForCacheProbe.ArgsEscaped = stateRunConfig.ArgsEscaped 399 } 400 401 return d.builder.commitContainer(d.state, cID, runConfigForCacheProbe) 402 } 403 404 // Derive the command to use for probeCache() and to commit in this container. 405 // Note that we only do this if there are any build-time env vars. Also, we 406 // use the special argument "|#" at the start of the args array. This will 407 // avoid conflicts with any RUN command since commands can not 408 // start with | (vertical bar). The "#" (number of build envs) is there to 409 // help ensure proper cache matches. We don't want a RUN command 410 // that starts with "foo=abc" to be considered part of a build-time env var. 411 // 412 // remove any unreferenced built-in args from the environment variables. 413 // These args are transparent so resulting image should be the same regardless 414 // of the value. 415 func prependEnvOnCmd(buildArgs *BuildArgs, buildArgVars []string, cmd strslice.StrSlice) strslice.StrSlice { 416 var tmpBuildEnv []string 417 for _, env := range buildArgVars { 418 key := strings.SplitN(env, "=", 2)[0] 419 if buildArgs.IsReferencedOrNotBuiltin(key) { 420 tmpBuildEnv = append(tmpBuildEnv, env) 421 } 422 } 423 424 sort.Strings(tmpBuildEnv) 425 tmpEnv := append([]string{fmt.Sprintf("|%d", len(tmpBuildEnv))}, tmpBuildEnv...) 426 return strslice.StrSlice(append(tmpEnv, cmd...)) 427 } 428 429 // CMD foo 430 // 431 // Set the default command to run in the container (which may be empty). 432 // Argument handling is the same as RUN. 433 // 434 func dispatchCmd(d dispatchRequest, c *instructions.CmdCommand) error { 435 runConfig := d.state.runConfig 436 cmd, argsEscaped := resolveCmdLine(c.ShellDependantCmdLine, runConfig, d.state.operatingSystem, c.Name(), c.String()) 437 438 // We warn here as Windows shell processing operates differently to Linux. 439 // Linux: /bin/sh -c "echo hello" world --> hello 440 // Windows: cmd /s /c "echo hello" world --> hello world 441 if d.state.operatingSystem == "windows" && 442 len(runConfig.Entrypoint) > 0 && 443 d.state.runConfig.ArgsEscaped != argsEscaped { 444 fmt.Fprintf(d.builder.Stderr, " ---> [Warning] Shell-form ENTRYPOINT and exec-form CMD may have unexpected results\n") 445 } 446 447 runConfig.Cmd = cmd 448 runConfig.ArgsEscaped = argsEscaped 449 450 if err := d.builder.commit(d.state, fmt.Sprintf("CMD %q", cmd)); err != nil { 451 return err 452 } 453 if len(c.ShellDependantCmdLine.CmdLine) != 0 { 454 d.state.cmdSet = true 455 } 456 457 return nil 458 } 459 460 // HEALTHCHECK foo 461 // 462 // Set the default healthcheck command to run in the container (which may be empty). 463 // Argument handling is the same as RUN. 464 // 465 func dispatchHealthcheck(d dispatchRequest, c *instructions.HealthCheckCommand) error { 466 runConfig := d.state.runConfig 467 if runConfig.Healthcheck != nil { 468 oldCmd := runConfig.Healthcheck.Test 469 if len(oldCmd) > 0 && oldCmd[0] != "NONE" { 470 fmt.Fprintf(d.builder.Stdout, "Note: overriding previous HEALTHCHECK: %v\n", oldCmd) 471 } 472 } 473 runConfig.Healthcheck = c.Health 474 return d.builder.commit(d.state, fmt.Sprintf("HEALTHCHECK %q", runConfig.Healthcheck)) 475 } 476 477 // ENTRYPOINT /usr/sbin/nginx 478 // 479 // Set the entrypoint to /usr/sbin/nginx. Will accept the CMD as the arguments 480 // to /usr/sbin/nginx. Uses the default shell if not in JSON format. 481 // 482 // Handles command processing similar to CMD and RUN, only req.runConfig.Entrypoint 483 // is initialized at newBuilder time instead of through argument parsing. 484 // 485 func dispatchEntrypoint(d dispatchRequest, c *instructions.EntrypointCommand) error { 486 runConfig := d.state.runConfig 487 cmd, argsEscaped := resolveCmdLine(c.ShellDependantCmdLine, runConfig, d.state.operatingSystem, c.Name(), c.String()) 488 489 // This warning is a little more complex than in dispatchCmd(), as the Windows base images (similar 490 // universally to almost every Linux image out there) have a single .Cmd field populated so that 491 // `docker run --rm image` starts the default shell which would typically be sh on Linux, 492 // or cmd on Windows. The catch to this is that if a dockerfile had `CMD ["c:\\windows\\system32\\cmd.exe"]`, 493 // we wouldn't be able to tell the difference. However, that would be highly unlikely, and besides, this 494 // is only trying to give a helpful warning of possibly unexpected results. 495 if d.state.operatingSystem == "windows" && 496 d.state.runConfig.ArgsEscaped != argsEscaped && 497 ((len(runConfig.Cmd) == 1 && strings.ToLower(runConfig.Cmd[0]) != `c:\windows\system32\cmd.exe` && len(runConfig.Shell) == 0) || (len(runConfig.Cmd) > 1)) { 498 fmt.Fprintf(d.builder.Stderr, " ---> [Warning] Shell-form CMD and exec-form ENTRYPOINT may have unexpected results\n") 499 } 500 501 runConfig.Entrypoint = cmd 502 runConfig.ArgsEscaped = argsEscaped 503 if !d.state.cmdSet { 504 runConfig.Cmd = nil 505 } 506 507 return d.builder.commit(d.state, fmt.Sprintf("ENTRYPOINT %q", runConfig.Entrypoint)) 508 } 509 510 // EXPOSE 6667/tcp 7000/tcp 511 // 512 // Expose ports for links and port mappings. This all ends up in 513 // req.runConfig.ExposedPorts for runconfig. 514 // 515 func dispatchExpose(d dispatchRequest, c *instructions.ExposeCommand, envs []string) error { 516 // custom multi word expansion 517 // expose $FOO with FOO="80 443" is expanded as EXPOSE [80,443]. This is the only command supporting word to words expansion 518 // so the word processing has been de-generalized 519 ports := []string{} 520 for _, p := range c.Ports { 521 ps, err := d.shlex.ProcessWords(p, envs) 522 if err != nil { 523 return err 524 } 525 ports = append(ports, ps...) 526 } 527 c.Ports = ports 528 529 ps, _, err := nat.ParsePortSpecs(ports) 530 if err != nil { 531 return err 532 } 533 534 if d.state.runConfig.ExposedPorts == nil { 535 d.state.runConfig.ExposedPorts = make(nat.PortSet) 536 } 537 for p := range ps { 538 d.state.runConfig.ExposedPorts[p] = struct{}{} 539 } 540 541 return d.builder.commit(d.state, "EXPOSE "+strings.Join(c.Ports, " ")) 542 } 543 544 // USER foo 545 // 546 // Set the user to 'foo' for future commands and when running the 547 // ENTRYPOINT/CMD at container run time. 548 // 549 func dispatchUser(d dispatchRequest, c *instructions.UserCommand) error { 550 d.state.runConfig.User = c.User 551 return d.builder.commit(d.state, fmt.Sprintf("USER %v", c.User)) 552 } 553 554 // VOLUME /foo 555 // 556 // Expose the volume /foo for use. Will also accept the JSON array form. 557 // 558 func dispatchVolume(d dispatchRequest, c *instructions.VolumeCommand) error { 559 if d.state.runConfig.Volumes == nil { 560 d.state.runConfig.Volumes = map[string]struct{}{} 561 } 562 for _, v := range c.Volumes { 563 if v == "" { 564 return errors.New("VOLUME specified can not be an empty string") 565 } 566 d.state.runConfig.Volumes[v] = struct{}{} 567 } 568 return d.builder.commit(d.state, fmt.Sprintf("VOLUME %v", c.Volumes)) 569 } 570 571 // STOPSIGNAL signal 572 // 573 // Set the signal that will be used to kill the container. 574 func dispatchStopSignal(d dispatchRequest, c *instructions.StopSignalCommand) error { 575 576 _, err := signal.ParseSignal(c.Signal) 577 if err != nil { 578 return errdefs.InvalidParameter(err) 579 } 580 d.state.runConfig.StopSignal = c.Signal 581 return d.builder.commit(d.state, fmt.Sprintf("STOPSIGNAL %v", c.Signal)) 582 } 583 584 // ARG name[=value] 585 // 586 // Adds the variable foo to the trusted list of variables that can be passed 587 // to builder using the --build-arg flag for expansion/substitution or passing to 'run'. 588 // Dockerfile author may optionally set a default value of this variable. 589 func dispatchArg(d dispatchRequest, c *instructions.ArgCommand) error { 590 var commitStr strings.Builder 591 commitStr.WriteString("ARG ") 592 for i, arg := range c.Args { 593 if i > 0 { 594 commitStr.WriteString(" ") 595 } 596 commitStr.WriteString(arg.Key) 597 if arg.Value != nil { 598 commitStr.WriteString("=") 599 commitStr.WriteString(*arg.Value) 600 } 601 d.state.buildArgs.AddArg(arg.Key, arg.Value) 602 } 603 604 return d.builder.commit(d.state, commitStr.String()) 605 } 606 607 // SHELL powershell -command 608 // 609 // Set the non-default shell to use. 610 func dispatchShell(d dispatchRequest, c *instructions.ShellCommand) error { 611 d.state.runConfig.Shell = c.Shell 612 return d.builder.commit(d.state, fmt.Sprintf("SHELL %v", d.state.runConfig.Shell)) 613 }