Debian Codegraph @

dockerfile/parser/parser.go

raw
1 // Package parser implements a parser and parse tree dumper for Dockerfiles.
2 package parser
3
4 import (
5 "bufio"
6 "bytes"
7 "errors"
8 "fmt"
9 "io"
10 "regexp"
11 "runtime"
12 "strconv"
13 "strings"
14 "unicode"
15
16 buildkitparser "github.com/moby/buildkit/frontend/dockerfile/parser"
17 buildkitshell "github.com/moby/buildkit/frontend/dockerfile/shell"
18 "github.com/openshift/imagebuilder/dockerfile/command"
19 "github.com/openshift/imagebuilder/internal"
20 sRegexp "go.podman.io/storage/pkg/regexp"
21 "go.podman.io/storage/pkg/system"
22 )
23
24 // Node is a structure used to represent a parse tree.
25 //
26 // In the node there are three fields, Value, Next, and Children. Value is the
27 // current token's string value. Next is always the next non-child token, and
28 // children contains all the children. Here's an example:
29 //
30 // (value next (child child-next child-next-next) next-next)
31 //
32 // This data structure is frankly pretty lousy for handling complex languages,
33 // but lucky for us the Dockerfile isn't very complicated. This structure
34 // works a little more effectively than a "proper" parse tree for our needs.
35 type Node struct {
36 Value string // actual content
37 Next *Node // the next item in the current sexp
38 Children []*Node // the children of this sexp
39 Heredocs []buildkitparser.Heredoc // extra heredoc content attachments
40 Attributes map[string]bool // special attributes for this node
41 Original string // original line used before parsing
42 Flags []string // only top Node should have this set
43 StartLine int // the line in the original dockerfile where the node begins
44 EndLine int // the line in the original dockerfile where the node ends
45 }
46
47 // Dump dumps the AST defined by `node` as a list of sexps.
48 // Returns a string suitable for printing.
49 func (node *Node) Dump() string {
50 str := ""
51 str += node.Value
52
53 if len(node.Flags) > 0 {
54 str += fmt.Sprintf(" %q", node.Flags)
55 }
56
57 for _, n := range node.Children {
58 str += "(" + n.Dump() + ")\n"
59 }
60 if len(node.Heredocs) > 0 {
61 for _, doc := range node.Heredocs {
62 str += "(" + doc.Name + "-" + doc.Content + "-" + strconv.Itoa(int(doc.FileDescriptor)) + "-" + strconv.FormatBool(doc.Expand) + "-" + strconv.FormatBool(doc.Chomp) + ")\n"
63 }
64 }
65 for n := node.Next; n != nil; n = n.Next {
66 if len(n.Children) > 0 {
67 str += " " + n.Dump()
68 } else {
69 str += " " + strconv.Quote(n.Value)
70 }
71 }
72
73 return strings.TrimSpace(str)
74 }
75
76 func (node *Node) lines(start, end int) {
77 node.StartLine = start
78 node.EndLine = end
79 }
80
81 func (node *Node) canContainHeredoc() bool {
82 // check for compound commands, like ONBUILD
83 if ok := heredocCompoundDirectives[strings.ToLower(node.Value)]; ok {
84 if node.Next != nil && len(node.Next.Children) > 0 {
85 node = node.Next.Children[0]
86 }
87 }
88
89 if ok := heredocDirectives[strings.ToLower(node.Value)]; !ok {
90 return false
91 }
92 if isJSON := node.Attributes["json"]; isJSON {
93 return false
94 }
95
96 return true
97 }
98
99 // AddChild adds a new child node, and updates line information
100 func (node *Node) AddChild(child *Node, startLine, endLine int) {
101 child.lines(startLine, endLine)
102 if node.StartLine < 0 {
103 node.StartLine = startLine
104 }
105 node.EndLine = endLine
106 node.Children = append(node.Children, child)
107 }
108
109 var (
110 dispatch map[string]func(string, *Directive) (*Node, map[string]bool, error)
111 tokenWhitespace = sRegexp.Delayed(`[\t\v\f\r ]+`)
112 tokenEscapeCommand = sRegexp.Delayed(`^#[ \t]*escape[ \t]*=[ \t]*(?P<escapechar>.).*$`)
113 tokenPlatformCommand = sRegexp.Delayed(`^#[ \t]*platform[ \t]*=[ \t]*(?P<platform>.*)$`)
114 tokenComment = sRegexp.Delayed(`^#.*$`)
115 )
116
117 // DefaultEscapeToken is the default escape token
118 const DefaultEscapeToken = '\\'
119
120 // defaultPlatformToken is the platform assumed for the build if not explicitly provided
121 var defaultPlatformToken = runtime.GOOS
122
123 var (
124 // Directives allowed to contain heredocs
125 heredocDirectives = map[string]bool{
126 command.Add: true,
127 command.Copy: true,
128 command.Run: true,
129 }
130
131 // Directives allowed to contain directives containing heredocs
132 heredocCompoundDirectives = map[string]bool{
133 command.Onbuild: true,
134 }
135 )
136
137 // Directive is the structure used during a build run to hold the state of
138 // parsing directives.
139 type Directive struct {
140 escapeToken rune // Current escape token
141 platformToken string // Current platform token
142 lineContinuationRegex *regexp.Regexp // Current line continuation regex
143 processingComplete bool // Whether we are done looking for directives
144 escapeSeen bool // Whether the escape directive has been seen
145 platformSeen bool // Whether the platform directive has been seen
146 }
147
148 // setEscapeToken sets the default token for escaping characters in a Dockerfile.
149 func (d *Directive) setEscapeToken(s string) error {
150 if s != "`" && s != "\\" {
151 return fmt.Errorf("invalid ESCAPE '%s'. Must be ` or \\", s)
152 }
153 d.escapeToken = rune(s[0])
154 d.lineContinuationRegex = regexp.MustCompile(`\` + s + `[ \t]*$`)
155 return nil
156 }
157
158 // setPlatformToken sets the default platform for pulling images in a Dockerfile.
159 func (d *Directive) setPlatformToken(s string) error {
160 s = strings.ToLower(s)
161 valid := []string{runtime.GOOS}
162 if system.LCOWSupported() {
163 valid = append(valid, "linux")
164 }
165 for _, item := range valid {
166 if s == item {
167 d.platformToken = s
168 return nil
169 }
170 }
171 return fmt.Errorf("invalid PLATFORM '%s'. Must be one of %v", s, valid)
172 }
173
174 // possibleParserDirective looks for one or more parser directives '# escapeToken=<char>' and
175 // '# platform=<string>'. Parser directives must precede any builder instruction
176 // or other comments, and cannot be repeated.
177 func (d *Directive) possibleParserDirective(line string) error {
178 if d.processingComplete {
179 return nil
180 }
181
182 tecMatch := tokenEscapeCommand.FindStringSubmatch(strings.ToLower(line))
183 if len(tecMatch) != 0 {
184 for i, n := range tokenEscapeCommand.SubexpNames() {
185 if n == "escapechar" {
186 if d.escapeSeen == true {
187 return errors.New("only one escape parser directive can be used")
188 }
189 d.escapeSeen = true
190 return d.setEscapeToken(tecMatch[i])
191 }
192 }
193 }
194
195 // TODO @jhowardmsft LCOW Support: Eventually this check can be removed,
196 // but only recognise a platform token if running in LCOW mode.
197 if system.LCOWSupported() {
198 tpcMatch := tokenPlatformCommand.FindStringSubmatch(strings.ToLower(line))
199 if len(tpcMatch) != 0 {
200 for i, n := range tokenPlatformCommand.SubexpNames() {
201 if n == "platform" {
202 if d.platformSeen == true {
203 return errors.New("only one platform parser directive can be used")
204 }
205 d.platformSeen = true
206 return d.setPlatformToken(tpcMatch[i])
207 }
208 }
209 }
210 }
211
212 d.processingComplete = true
213 return nil
214 }
215
216 // NewDefaultDirective returns a new Directive with the default escapeToken token
217 func NewDefaultDirective() *Directive {
218 directive := Directive{}
219 directive.setEscapeToken(string(DefaultEscapeToken))
220 directive.setPlatformToken(defaultPlatformToken)
221 return &directive
222 }
223
224 func init() {
225 // Dispatch Table. see line_parsers.go for the parse functions.
226 // The command is parsed and mapped to the line parser. The line parser
227 // receives the arguments but not the command, and returns an AST after
228 // reformulating the arguments according to the rules in the parser
229 // functions. Errors are propagated up by Parse() and the resulting AST can
230 // be incorporated directly into the existing AST as a next.
231 dispatch = map[string]func(string, *Directive) (*Node, map[string]bool, error){
232 command.Add: parseMaybeJSONToList,
233 command.Arg: parseNameOrNameVal,
234 command.Cmd: parseMaybeJSON,
235 command.Copy: parseMaybeJSONToList,
236 command.Entrypoint: parseMaybeJSON,
237 command.Env: parseEnv,
238 command.Expose: parseStringsWhitespaceDelimited,
239 command.From: parseStringsWhitespaceDelimited,
240 command.Healthcheck: parseHealthConfig,
241 command.Label: parseLabel,
242 command.Maintainer: parseString,
243 command.Onbuild: parseSubCommand,
244 command.Run: parseMaybeJSON,
245 command.Shell: parseMaybeJSON,
246 command.StopSignal: parseString,
247 command.User: parseString,
248 command.Volume: parseMaybeJSONToList,
249 command.Workdir: parseString,
250 }
251 }
252
253 // newNodeFromLine splits the line into parts, and dispatches to a function
254 // based on the command and command arguments. A Node is created from the
255 // result of the dispatch.
256 func newNodeFromLine(line string, directive *Directive) (*Node, error) {
257 cmd, flags, args, err := splitCommand(line)
258 if err != nil {
259 return nil, err
260 }
261
262 fn := dispatch[cmd]
263 // Ignore invalid Dockerfile instructions
264 if fn == nil {
265 fn = parseIgnore
266 }
267 next, attrs, err := fn(args, directive)
268 if err != nil {
269 return nil, err
270 }
271
272 return &Node{
273 Value: cmd,
274 Original: line,
275 Flags: flags,
276 Next: next,
277 Attributes: attrs,
278 }, nil
279 }
280
281 // Result is the result of parsing a Dockerfile
282 type Result struct {
283 AST *Node
284 EscapeToken rune
285 Platform string
286 Warnings []string
287 }
288
289 // PrintWarnings to the writer
290 func (r *Result) PrintWarnings(out io.Writer) {
291 if len(r.Warnings) == 0 {
292 return
293 }
294 io.WriteString(out, strings.Join(r.Warnings, "\n")+"\n")
295 }
296
297 // Parse reads lines from a Reader, parses the lines into an AST and returns
298 // the AST and escape token
299 func Parse(rwc io.Reader) (*Result, error) {
300 d := NewDefaultDirective()
301 currentLine := 0
302 root := &Node{StartLine: -1}
303 scanner := bufio.NewScanner(rwc)
304 buf := []byte{}
305 // containerfile may contain large lines,
306 // allocate 2MB for such use-cases.
307 scanner.Buffer(buf, 2048*1024)
308 warnings := []string{}
309
310 var err error
311 for scanner.Scan() {
312 bytesRead := scanner.Bytes()
313 if currentLine == 0 {
314 // First line, strip the byte-order-marker if present
315 bytesRead = bytes.TrimPrefix(bytesRead, utf8bom)
316 }
317 bytesRead, err = processLine(d, bytesRead, true)
318 if err != nil {
319 return nil, err
320 }
321 currentLine++
322
323 startLine := currentLine
324 line, isEndOfLine := trimContinuationCharacter(string(bytesRead), d)
325 if isEndOfLine && line == "" {
326 continue
327 }
328
329 var hasEmptyContinuationLine bool
330 for !isEndOfLine && scanner.Scan() {
331 bytesRead, err := processLine(d, scanner.Bytes(), false)
332 if err != nil {
333 return nil, err
334 }
335 currentLine++
336
337 if isEmptyContinuationLine(bytesRead) {
338 hasEmptyContinuationLine = true
339 continue
340 }
341
342 continuationLine := string(bytesRead)
343 continuationLine, isEndOfLine = trimContinuationCharacter(continuationLine, d)
344 line += continuationLine
345 }
346
347 if hasEmptyContinuationLine {
348 warning := "[WARNING]: Empty continuation line found in:\n " + line
349 warnings = append(warnings, warning)
350 }
351
352 child, err := newNodeFromLine(line, d)
353 if err != nil {
354 return nil, err
355 }
356
357 if child.canContainHeredoc() {
358 heredocs, err := heredocsFromLine(line)
359 if err != nil {
360 return nil, err
361 }
362
363 for _, heredoc := range heredocs {
364 terminator := []byte(heredoc.Name)
365 terminated := false
366 for scanner.Scan() {
367 bytesRead := scanner.Bytes()
368 currentLine++
369
370 possibleTerminator := trimNewline(bytesRead)
371 if heredoc.Chomp {
372 possibleTerminator = trimLeadingTabs(possibleTerminator)
373 }
374 if bytes.Equal(possibleTerminator, terminator) {
375 terminated = true
376 break
377 }
378 heredoc.Content += "\n"
379 heredoc.Content += string(bytesRead)
380 }
381 if !terminated {
382 return nil, fmt.Errorf("%s: unterminated heredoc", heredoc.Name)
383 }
384
385 child.Heredocs = append(child.Heredocs, heredoc)
386 }
387 }
388
389 root.AddChild(child, startLine, currentLine)
390 }
391
392 if scannerErr := scanner.Err(); scannerErr != nil {
393 return nil, scannerErr
394 }
395
396 if len(warnings) > 0 {
397 warnings = append(warnings, "[WARNING]: Empty continuation lines will become errors in a future release.")
398 }
399 return &Result{
400 AST: root,
401 Warnings: warnings,
402 EscapeToken: d.escapeToken,
403 Platform: d.platformToken,
404 }, nil
405 }
406
407 func heredocsFromLine(line string) ([]buildkitparser.Heredoc, error) {
408 shlex := buildkitshell.NewLex('\\')
409 shlex.RawQuotes = true
410 shlex.RawEscapes = true
411 shlex.SkipUnsetEnv = true
412 words, _ := shlex.ProcessWords(line, internal.EnvironmentSlice([]string{}))
413
414 var docs []buildkitparser.Heredoc
415 for _, word := range words {
416 heredoc, err := buildkitparser.ParseHeredoc(word)
417 if err != nil {
418 return nil, err
419 }
420 if heredoc != nil {
421 docs = append(docs, *heredoc)
422 }
423 }
424 return docs, nil
425 }
426
427 func trimComments(src []byte) []byte {
428 return tokenComment.ReplaceAll(src, []byte{})
429 }
430
431 func trimWhitespace(src []byte) []byte {
432 return bytes.TrimLeftFunc(src, unicode.IsSpace)
433 }
434
435 func trimLeadingWhitespace(src []byte) []byte {
436 return bytes.TrimLeftFunc(src, unicode.IsSpace)
437 }
438 func trimLeadingTabs(src []byte) []byte {
439 return bytes.TrimLeft(src, "\t")
440 }
441 func trimNewline(src []byte) []byte {
442 return bytes.TrimRight(src, "\r\n")
443 }
444
445 func isEmptyContinuationLine(line []byte) bool {
446 return len(trimComments(trimWhitespace(line))) == 0
447 }
448
449 var utf8bom = []byte{0xEF, 0xBB, 0xBF}
450
451 func trimContinuationCharacter(line string, d *Directive) (string, bool) {
452 if d.lineContinuationRegex.MatchString(line) {
453 line = d.lineContinuationRegex.ReplaceAllString(line, "")
454 return line, false
455 }
456 return line, true
457 }
458
459 // TODO: remove stripLeftWhitespace after deprecation period. It seems silly
460 // to preserve whitespace on continuation lines. Why is that done?
461 func processLine(d *Directive, token []byte, stripLeftWhitespace bool) ([]byte, error) {
462 if stripLeftWhitespace {
463 token = trimWhitespace(token)
464 }
465 return trimComments(token), d.possibleParserDirective(string(token))
466 }