| 1 | // Copyright 2023 Google LLC. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | // Package shtemplate is a drop-in-replacement for using text/template to produce shell scripts, that adds automatic detection for argument/command injection |
| 16 | package shtemplate |
| 17 | |
| 18 | import ( |
| 19 | "bytes" |
| 20 | "errors" |
| 21 | "fmt" |
| 22 | "io" |
| 23 | "io/fs" |
| 24 | "os" |
| 25 | "path" |
| 26 | "path/filepath" |
| 27 | "reflect" |
| 28 | "strings" |
| 29 | "text/template" |
| 30 | "text/template/parse" |
| 31 | "unicode/utf8" |
| 32 | |
| 33 | "github.com/google/safetext/common" |
| 34 | |
| 35 | "mvdan.cc/sh/v3/syntax" |
| 36 | "github.com/pborman/uuid" |
| 37 | ) |
| 38 | |
| 39 | // ErrInvalidShTemplate indicates the requested template is not a valid script |
| 40 | var ErrInvalidShTemplate error = errors.New("Invalid Shell Template") |
| 41 | |
| 42 | // ErrShInjection indicates the inputs resulted in shell injection. |
| 43 | var ErrShInjection error = errors.New("Shell Injection Detected") |
| 44 | |
| 45 | // ExecError is the custom error type returned when Execute has an |
| 46 | // error evaluating its template. (If a write error occurs, the actual |
| 47 | // error is returned; it will not be of type ExecError.) |
| 48 | type ExecError = template.ExecError |
| 49 | |
| 50 | // FuncMap is the type of the map defining the mapping from names to functions. |
| 51 | // Each function must have either a single return value, or two return values of |
| 52 | // which the second has type error. In that case, if the second (error) |
| 53 | // return value evaluates to non-nil during execution, execution terminates and |
| 54 | // Execute returns that error. |
| 55 | // |
| 56 | // Errors returned by Execute wrap the underlying error; call errors.As to |
| 57 | // uncover them. |
| 58 | // |
| 59 | // When template execution invokes a function with an argument list, that list |
| 60 | // must be assignable to the function's parameter types. Functions meant to |
| 61 | // apply to arguments of arbitrary type can use parameters of type any or |
| 62 | // of type reflect.Value. Similarly, functions meant to return a result of arbitrary |
| 63 | // type can return any or reflect.Value. |
| 64 | type FuncMap = template.FuncMap |
| 65 | |
| 66 | // Template is the representation of a parsed template. The *parse.Tree |
| 67 | // field is exported only for use by html/template and should be treated |
| 68 | // as unexported by all other clients. |
| 69 | type Template struct { |
| 70 | unsafeTemplate *template.Template |
| 71 | uuid string |
| 72 | } |
| 73 | |
| 74 | // New allocates a new, undefined template with the given name. |
| 75 | func New(name string) *Template { |
| 76 | id := uuid.New() |
| 77 | funcMap := common.BuildTextTemplateFuncMap(id) |
| 78 | return &Template{unsafeTemplate: template.New(name).Funcs(funcMap), uuid: id} |
| 79 | } |
| 80 | |
| 81 | // Mutation algorithm |
| 82 | func mutateString(s string) string { |
| 83 | out := make([]rune, utf8.RuneCountInString(s)*2) |
| 84 | |
| 85 | i := 0 |
| 86 | for _, r := range s { |
| 87 | out[i] = r |
| 88 | i++ |
| 89 | |
| 90 | out[i] = r |
| 91 | i++ |
| 92 | } |
| 93 | |
| 94 | return string(out[:i]) |
| 95 | } |
| 96 | |
| 97 | func paramExprMatch(a, b, c *syntax.ParamExp) bool { |
| 98 | if b.Short != a.Short || c.Short != a.Short { |
| 99 | return false |
| 100 | } |
| 101 | |
| 102 | if b.Excl != a.Excl || c.Excl != a.Excl { |
| 103 | return false |
| 104 | } |
| 105 | |
| 106 | if b.Length != a.Length || c.Length != a.Length { |
| 107 | return false |
| 108 | } |
| 109 | |
| 110 | if b.Width != a.Width || c.Width != a.Width { |
| 111 | return false |
| 112 | } |
| 113 | |
| 114 | if (b.Param == nil) != (a.Param == nil) || (c.Param == nil) != (a.Param == nil) { |
| 115 | return false |
| 116 | } |
| 117 | |
| 118 | if a.Param != nil && |
| 119 | (b.Param.Value != a.Param.Value || c.Param.Value != a.Param.Value) { |
| 120 | return false |
| 121 | } |
| 122 | |
| 123 | if (b.Index == nil) != (a.Index == nil) || (c.Index == nil) != (a.Index == nil) { |
| 124 | return false |
| 125 | } |
| 126 | |
| 127 | if a.Index != nil && !arithmExprMatch(a.Index, b.Index, c.Index) { |
| 128 | return false |
| 129 | } |
| 130 | |
| 131 | if (b.Slice == nil) != (a.Slice == nil) || (c.Slice == nil) != (a.Slice == nil) { |
| 132 | return false |
| 133 | } |
| 134 | |
| 135 | if a.Slice != nil && !slicesMatch(a.Slice, b.Slice, c.Slice) { |
| 136 | return false |
| 137 | } |
| 138 | |
| 139 | if (b.Repl == nil) != (a.Repl == nil) || (c.Repl == nil) != (a.Repl == nil) { |
| 140 | return false |
| 141 | } |
| 142 | |
| 143 | if a.Repl != nil && !replaceMatch(a.Repl, b.Repl, c.Repl) { |
| 144 | return false |
| 145 | } |
| 146 | |
| 147 | if b.Names != a.Names || c.Names != a.Names { |
| 148 | return false |
| 149 | } |
| 150 | |
| 151 | if (b.Exp == nil) != (a.Exp == nil) || (c.Exp == nil) != (a.Exp == nil) { |
| 152 | return false |
| 153 | } |
| 154 | |
| 155 | if a.Exp != nil && !wordsMatch(a.Exp.Word.Parts, b.Exp.Word.Parts, c.Exp.Word.Parts, matchExactly) { |
| 156 | return false |
| 157 | } |
| 158 | |
| 159 | return true |
| 160 | } |
| 161 | |
| 162 | func cmdSubstMatch(a, b, c *syntax.CmdSubst) bool { |
| 163 | if b.Backquotes != a.Backquotes || c.Backquotes != a.Backquotes { |
| 164 | return false |
| 165 | } |
| 166 | |
| 167 | if b.TempFile != a.TempFile || c.TempFile != a.TempFile { |
| 168 | return false |
| 169 | } |
| 170 | |
| 171 | if b.ReplyVar != a.ReplyVar || c.ReplyVar != a.ReplyVar { |
| 172 | return false |
| 173 | } |
| 174 | |
| 175 | if !statementsArrayMatch(a.Stmts, b.Stmts, c.Stmts) { |
| 176 | return false |
| 177 | } |
| 178 | |
| 179 | return true |
| 180 | } |
| 181 | |
| 182 | func slicesMatch(a, b, c *syntax.Slice) bool { |
| 183 | return arithmExprMatch(a.Offset, b.Offset, c.Offset) && arithmExprMatch(a.Length, b.Length, c.Length) |
| 184 | } |
| 185 | |
| 186 | func replaceMatch(a, b, c *syntax.Replace) bool { |
| 187 | if b.All != a.All || c.All != a.All { |
| 188 | return false |
| 189 | } |
| 190 | |
| 191 | if !wordsMatch(a.Orig.Parts, b.Orig.Parts, c.Orig.Parts, justStructure) { |
| 192 | return false |
| 193 | } |
| 194 | |
| 195 | if !wordsMatch(a.With.Parts, b.With.Parts, c.With.Parts, justStructure) { |
| 196 | return false |
| 197 | } |
| 198 | |
| 199 | return true |
| 200 | } |
| 201 | |
| 202 | func arithmExpMatch(a, b, c syntax.ArithmExp) bool { |
| 203 | if b.Bracket != a.Bracket || c.Bracket != a.Bracket { |
| 204 | return false |
| 205 | } |
| 206 | |
| 207 | if b.Unsigned != a.Unsigned || c.Unsigned != a.Unsigned { |
| 208 | return false |
| 209 | } |
| 210 | |
| 211 | return arithmExprMatch(a.X, b.X, c.X) |
| 212 | } |
| 213 | |
| 214 | func arithmExprArrayMatch(a, b, c []syntax.ArithmExpr) bool { |
| 215 | if len(b) != len(a) || len(c) != len(a) { |
| 216 | return false |
| 217 | } |
| 218 | |
| 219 | for i := range a { |
| 220 | if !arithmExprMatch(a[i], b[i], c[i]) { |
| 221 | return false |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | return true |
| 226 | } |
| 227 | |
| 228 | func arithmExprMatch(a, b, c syntax.ArithmExpr) bool { |
| 229 | if reflect.TypeOf(b) != reflect.TypeOf(a) || reflect.TypeOf(c) != reflect.TypeOf(a) { |
| 230 | return false |
| 231 | } |
| 232 | |
| 233 | switch a := a.(type) { |
| 234 | case *syntax.BinaryArithm: |
| 235 | if b.(*syntax.BinaryArithm).Op != a.Op || c.(*syntax.BinaryArithm).Op != a.Op { |
| 236 | return false |
| 237 | } |
| 238 | if !arithmExprMatch(a.X, b.(*syntax.BinaryArithm).X, c.(*syntax.BinaryArithm).X) { |
| 239 | return false |
| 240 | } |
| 241 | if !arithmExprMatch(a.Y, b.(*syntax.BinaryArithm).Y, c.(*syntax.BinaryArithm).Y) { |
| 242 | return false |
| 243 | } |
| 244 | case *syntax.UnaryArithm: |
| 245 | if b.(*syntax.UnaryArithm).Op != a.Op || c.(*syntax.UnaryArithm).Op != a.Op { |
| 246 | return false |
| 247 | } |
| 248 | if b.(*syntax.UnaryArithm).Post != a.Post || c.(*syntax.UnaryArithm).Post != a.Post { |
| 249 | return false |
| 250 | } |
| 251 | if !arithmExprMatch(a.X, b.(*syntax.UnaryArithm).X, c.(*syntax.UnaryArithm).X) { |
| 252 | return false |
| 253 | } |
| 254 | case *syntax.ParenArithm: |
| 255 | if !arithmExprMatch(a.X, b.(*syntax.ParenArithm).X, c.(*syntax.ParenArithm).X) { |
| 256 | return false |
| 257 | } |
| 258 | case *syntax.Word: |
| 259 | if !wordsMatch(a.Parts, b.(*syntax.Word).Parts, c.(*syntax.Word).Parts, justStructure) { |
| 260 | return false |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | return true |
| 265 | } |
| 266 | |
| 267 | func assignArrayMatch(a, b, c []*syntax.Assign) bool { |
| 268 | if len(b) != len(a) || len(c) != len(a) { |
| 269 | return false |
| 270 | } |
| 271 | |
| 272 | for i := range a { |
| 273 | if !assignMatch(a[i], b[i], c[i]) { |
| 274 | return false |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | return true |
| 279 | } |
| 280 | |
| 281 | func assignMatch(a, b, c *syntax.Assign) bool { |
| 282 | if b.Append != a.Append || c.Append != a.Append { |
| 283 | return false |
| 284 | } |
| 285 | |
| 286 | if b.Naked != a.Naked || c.Naked != a.Naked { |
| 287 | return false |
| 288 | } |
| 289 | |
| 290 | if (b.Name == nil) != (a.Name == nil) || (c.Name == nil) != (a.Name == nil) { |
| 291 | return false |
| 292 | } |
| 293 | |
| 294 | if a.Name != nil && |
| 295 | (b.Name.Value != a.Name.Value || c.Name.Value != a.Name.Value) { |
| 296 | return false |
| 297 | } |
| 298 | |
| 299 | if (b.Index == nil) != (a.Index == nil) || (c.Index == nil) != (a.Index == nil) { |
| 300 | return false |
| 301 | } |
| 302 | |
| 303 | if a.Index != nil && !arithmExprMatch(a.Index, b.Index, c.Index) { |
| 304 | return false |
| 305 | } |
| 306 | |
| 307 | if (b.Value == nil) != (a.Value == nil) || (c.Value == nil) != (a.Value == nil) { |
| 308 | return false |
| 309 | } |
| 310 | |
| 311 | if a.Value != nil && !wordsMatch(a.Value.Parts, b.Value.Parts, c.Value.Parts, justStructure) { |
| 312 | return false |
| 313 | } |
| 314 | |
| 315 | if (b.Array == nil) != (a.Array == nil) || (c.Array == nil) != (a.Array == nil) { |
| 316 | return false |
| 317 | } |
| 318 | |
| 319 | if a.Array != nil && !arrayExprMatch(a.Array, b.Array, c.Array) { |
| 320 | return false |
| 321 | } |
| 322 | |
| 323 | return true |
| 324 | } |
| 325 | |
| 326 | func arrayExprMatch(a, b, c *syntax.ArrayExpr) bool { |
| 327 | if len(b.Elems) != len(a.Elems) || len(c.Elems) != len(a.Elems) { |
| 328 | return false |
| 329 | } |
| 330 | |
| 331 | for i := range a.Elems { |
| 332 | if !arrayElemMatch(a.Elems[i], b.Elems[i], c.Elems[i]) { |
| 333 | return false |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | return true |
| 338 | } |
| 339 | |
| 340 | func arrayElemMatch(a, b, c *syntax.ArrayElem) bool { |
| 341 | if (b.Index == nil) != (a.Index == nil) || (c.Index == nil) != (a.Index == nil) { |
| 342 | return false |
| 343 | } |
| 344 | |
| 345 | if a.Index != nil && !arithmExprMatch(a.Index, b.Index, c.Index) { |
| 346 | return false |
| 347 | } |
| 348 | |
| 349 | if (b.Value == nil) != (a.Value == nil) || (c.Value == nil) != (a.Value == nil) { |
| 350 | return false |
| 351 | } |
| 352 | |
| 353 | if a.Value != nil && !wordsMatch(a.Value.Parts, b.Value.Parts, c.Value.Parts, justStructure) { |
| 354 | return false |
| 355 | } |
| 356 | |
| 357 | return true |
| 358 | } |
| 359 | |
| 360 | func caseItemArrayMatch(a, b, c []*syntax.CaseItem) bool { |
| 361 | if len(b) != len(a) || len(c) != len(a) { |
| 362 | return false |
| 363 | } |
| 364 | |
| 365 | for i := range a { |
| 366 | if !caseItemMatch(a[i], b[i], c[i]) { |
| 367 | return false |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | return true |
| 372 | } |
| 373 | |
| 374 | func caseItemMatch(a, b, c *syntax.CaseItem) bool { |
| 375 | if b.Op != a.Op || c.Op != a.Op { |
| 376 | return false |
| 377 | } |
| 378 | |
| 379 | if !wordsArrayMatch(a.Patterns, b.Patterns, c.Patterns, justStructure) { |
| 380 | return false |
| 381 | } |
| 382 | |
| 383 | if !statementsArrayMatch(a.Stmts, b.Stmts, c.Stmts) { |
| 384 | return false |
| 385 | } |
| 386 | |
| 387 | return true |
| 388 | } |
| 389 | |
| 390 | func loopMatch(a, b, c syntax.Loop) bool { |
| 391 | if reflect.TypeOf(b) != reflect.TypeOf(a) || reflect.TypeOf(c) != reflect.TypeOf(a) { |
| 392 | return false |
| 393 | } |
| 394 | |
| 395 | switch a := a.(type) { |
| 396 | case *syntax.WordIter: |
| 397 | if (b.(*syntax.WordIter).Name == nil) != (a.Name == nil) || (c.(*syntax.WordIter).Name == nil) != (a.Name == nil) { |
| 398 | return false |
| 399 | } |
| 400 | |
| 401 | if a.Name != nil && |
| 402 | (b.(*syntax.WordIter).Name.Value != a.Name.Value || c.(*syntax.WordIter).Name.Value != a.Name.Value) { |
| 403 | return false |
| 404 | } |
| 405 | |
| 406 | if !wordsArrayMatch(a.Items, b.(*syntax.WordIter).Items, c.(*syntax.WordIter).Items, justStructure) { |
| 407 | return false |
| 408 | } |
| 409 | case *syntax.CStyleLoop: |
| 410 | if (b.(*syntax.CStyleLoop).Init == nil) != (a.Init == nil) || (c.(*syntax.CStyleLoop).Init == nil) != (a.Init == nil) { |
| 411 | return false |
| 412 | } |
| 413 | |
| 414 | if a.Init != nil && !arithmExprMatch(a.Init, b.(*syntax.CStyleLoop).Init, c.(*syntax.CStyleLoop).Init) { |
| 415 | return false |
| 416 | } |
| 417 | |
| 418 | if (b.(*syntax.CStyleLoop).Cond == nil) != (a.Cond == nil) || (c.(*syntax.CStyleLoop).Cond == nil) != (a.Cond == nil) { |
| 419 | return false |
| 420 | } |
| 421 | |
| 422 | if a.Cond != nil && !arithmExprMatch(a.Cond, b.(*syntax.CStyleLoop).Cond, c.(*syntax.CStyleLoop).Cond) { |
| 423 | return false |
| 424 | } |
| 425 | |
| 426 | if (b.(*syntax.CStyleLoop).Post == nil) != (a.Post == nil) || (c.(*syntax.CStyleLoop).Post == nil) != (a.Post == nil) { |
| 427 | return false |
| 428 | } |
| 429 | |
| 430 | if a.Post != nil && !arithmExprMatch(a.Post, b.(*syntax.CStyleLoop).Post, c.(*syntax.CStyleLoop).Post) { |
| 431 | return false |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | return true |
| 436 | } |
| 437 | |
| 438 | func testExprMatch(a, b, c syntax.TestExpr) bool { |
| 439 | if reflect.TypeOf(b) != reflect.TypeOf(a) || reflect.TypeOf(c) != reflect.TypeOf(a) { |
| 440 | return false |
| 441 | } |
| 442 | |
| 443 | switch a := a.(type) { |
| 444 | case *syntax.BinaryTest: |
| 445 | if b.(*syntax.BinaryTest).Op != a.Op || c.(*syntax.BinaryTest).Op != a.Op { |
| 446 | return false |
| 447 | } |
| 448 | |
| 449 | if !testExprMatch(a.X, b.(*syntax.BinaryTest).X, c.(*syntax.BinaryTest).X) { |
| 450 | return false |
| 451 | } |
| 452 | |
| 453 | if !testExprMatch(a.Y, b.(*syntax.BinaryTest).Y, c.(*syntax.BinaryTest).Y) { |
| 454 | return false |
| 455 | } |
| 456 | case *syntax.UnaryTest: |
| 457 | if b.(*syntax.UnaryTest).Op != a.Op || c.(*syntax.UnaryTest).Op != a.Op { |
| 458 | return false |
| 459 | } |
| 460 | |
| 461 | if !testExprMatch(a.X, b.(*syntax.UnaryTest).X, c.(*syntax.UnaryTest).X) { |
| 462 | return false |
| 463 | } |
| 464 | case *syntax.ParenTest: |
| 465 | if !testExprMatch(a.X, b.(*syntax.ParenTest).X, c.(*syntax.ParenTest).X) { |
| 466 | return false |
| 467 | } |
| 468 | case *syntax.Word: |
| 469 | if !wordsMatch(a.Parts, b.(*syntax.Word).Parts, c.(*syntax.Word).Parts, justStructure) { |
| 470 | return false |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | return true |
| 475 | } |
| 476 | |
| 477 | type wordComparisonContext int |
| 478 | |
| 479 | const ( |
| 480 | matchExactly wordComparisonContext = 0 |
| 481 | forbidFlagInjection wordComparisonContext = 1 |
| 482 | justStructure wordComparisonContext = 2 |
| 483 | ) |
| 484 | |
| 485 | func wordsArrayMatch(a, b, c []*syntax.Word, ctx wordComparisonContext) bool { |
| 486 | if len(b) != len(a) || len(c) != len(a) { |
| 487 | return false |
| 488 | } |
| 489 | |
| 490 | for i := range a { |
| 491 | if !wordsMatch(a[i].Parts, b[i].Parts, c[i].Parts, ctx) { |
| 492 | return false |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | return true |
| 497 | } |
| 498 | |
| 499 | func wordsMatch(a, b, c []syntax.WordPart, ctx wordComparisonContext) bool { |
| 500 | if len(b) != len(a) || len(c) != len(a) { |
| 501 | return false |
| 502 | } |
| 503 | |
| 504 | for i, p := range a { |
| 505 | if !wordPartsMatch(p, b[i], c[i], ctx) { |
| 506 | return false |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | return true |
| 511 | } |
| 512 | |
| 513 | func verifyStrings(a, b, c string, ctx wordComparisonContext) bool { |
| 514 | if ctx == matchExactly { |
| 515 | if b != a || c != a { |
| 516 | return false |
| 517 | } |
| 518 | } else if ctx == forbidFlagInjection { |
| 519 | if flagInjected(a, b, c) { |
| 520 | return false |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | return true |
| 525 | } |
| 526 | |
| 527 | func flagInjected(a, b, c string) bool { |
| 528 | return !strings.HasPrefix(a, "-") && (strings.HasPrefix(b, "-") || strings.HasPrefix(c, "-")) |
| 529 | } |
| 530 | |
| 531 | // Check for introduction or removal of ? * + @ ! characters |
| 532 | func literalInjection(a, b, c string) bool { |
| 533 | for _, specialChar := range []string{"?", "*", "+", "@", "!"} { |
| 534 | count := strings.Count(a, specialChar) |
| 535 | |
| 536 | if strings.Count(b, specialChar) != count || strings.Count(c, specialChar) != count { |
| 537 | return true |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | return false |
| 542 | } |
| 543 | |
| 544 | func wordPartsMatch(a, b, c syntax.WordPart, ctx wordComparisonContext) bool { |
| 545 | if reflect.TypeOf(b) != reflect.TypeOf(a) || reflect.TypeOf(c) != reflect.TypeOf(a) { |
| 546 | return false |
| 547 | } |
| 548 | |
| 549 | switch a := a.(type) { |
| 550 | case *syntax.Lit: |
| 551 | if !verifyStrings(a.Value, b.(*syntax.Lit).Value, c.(*syntax.Lit).Value, ctx) { |
| 552 | return false |
| 553 | } |
| 554 | |
| 555 | if literalInjection(a.Value, b.(*syntax.Lit).Value, c.(*syntax.Lit).Value) { |
| 556 | return false |
| 557 | } |
| 558 | case *syntax.SglQuoted: |
| 559 | if !verifyStrings(a.Value, b.(*syntax.SglQuoted).Value, c.(*syntax.SglQuoted).Value, ctx) { |
| 560 | return false |
| 561 | } |
| 562 | case *syntax.DblQuoted: |
| 563 | if !wordsMatch(a.Parts, b.(*syntax.DblQuoted).Parts, c.(*syntax.DblQuoted).Parts, ctx) { |
| 564 | return false |
| 565 | } |
| 566 | case *syntax.ParamExp: |
| 567 | if !paramExprMatch(a, b.(*syntax.ParamExp), c.(*syntax.ParamExp)) { |
| 568 | return false |
| 569 | } |
| 570 | case *syntax.CmdSubst: |
| 571 | if !cmdSubstMatch(a, b.(*syntax.CmdSubst), c.(*syntax.CmdSubst)) { |
| 572 | return false |
| 573 | } |
| 574 | case *syntax.ArithmExp: |
| 575 | if !arithmExpMatch(*a, *b.(*syntax.ArithmExp), *c.(*syntax.ArithmExp)) { |
| 576 | return false |
| 577 | } |
| 578 | case *syntax.ProcSubst: |
| 579 | if b.(*syntax.ProcSubst).Op != a.Op || c.(*syntax.ProcSubst).Op != a.Op { |
| 580 | return false |
| 581 | } |
| 582 | |
| 583 | if !statementsArrayMatch(a.Stmts, b.(*syntax.ProcSubst).Stmts, c.(*syntax.ProcSubst).Stmts) { |
| 584 | return false |
| 585 | } |
| 586 | case *syntax.ExtGlob: |
| 587 | if b.(*syntax.ExtGlob).Op != a.Op || c.(*syntax.ExtGlob).Op != a.Op { |
| 588 | return false |
| 589 | } |
| 590 | |
| 591 | if b.(*syntax.ExtGlob).Pattern.Value != a.Pattern.Value || c.(*syntax.ExtGlob).Pattern.Value != a.Pattern.Value { |
| 592 | return false |
| 593 | } |
| 594 | case *syntax.BraceExp: |
| 595 | if !wordsArrayMatch(a.Elems, b.(*syntax.BraceExp).Elems, c.(*syntax.BraceExp).Elems, ctx) { |
| 596 | return false |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | return true |
| 601 | } |
| 602 | |
| 603 | func commandsMatch(a, b, c syntax.Command) bool { |
| 604 | if reflect.TypeOf(b) != reflect.TypeOf(a) || reflect.TypeOf(c) != reflect.TypeOf(a) { |
| 605 | return false |
| 606 | } |
| 607 | |
| 608 | switch cmd := a.(type) { |
| 609 | case *syntax.CallExpr: |
| 610 | if !assignArrayMatch(cmd.Assigns, b.(*syntax.CallExpr).Assigns, c.(*syntax.CallExpr).Assigns) { |
| 611 | return false |
| 612 | } |
| 613 | |
| 614 | if len(b.(*syntax.CallExpr).Args) != len(cmd.Args) || len(c.(*syntax.CallExpr).Args) != len(cmd.Args) { |
| 615 | return false |
| 616 | } |
| 617 | |
| 618 | // First "argument" is command name |
| 619 | context := matchExactly |
| 620 | for i := 0; i < len(cmd.Args); i++ { |
| 621 | if !wordsMatch(cmd.Args[i].Parts, b.(*syntax.CallExpr).Args[i].Parts, c.(*syntax.CallExpr).Args[i].Parts, context) { |
| 622 | return false |
| 623 | } |
| 624 | |
| 625 | // For subsequent arguments, just check for argument inject |
| 626 | context = forbidFlagInjection |
| 627 | } |
| 628 | |
| 629 | case *syntax.IfClause: |
| 630 | if !statementsArrayMatch(cmd.Cond, b.(*syntax.IfClause).Cond, c.(*syntax.IfClause).Cond) { |
| 631 | return false |
| 632 | } |
| 633 | |
| 634 | if !statementsArrayMatch(cmd.Then, b.(*syntax.IfClause).Then, c.(*syntax.IfClause).Then) { |
| 635 | return false |
| 636 | } |
| 637 | |
| 638 | if (b.(*syntax.IfClause).Else == nil) != (cmd.Else == nil) || (c.(*syntax.IfClause).Else == nil) != (cmd.Else == nil) { |
| 639 | return false |
| 640 | } |
| 641 | |
| 642 | if cmd.Else != nil && !commandsMatch(cmd.Else, b.(*syntax.IfClause).Else, c.(*syntax.IfClause).Else) { |
| 643 | return false |
| 644 | } |
| 645 | case *syntax.WhileClause: |
| 646 | if b.(*syntax.WhileClause).Until != cmd.Until || c.(*syntax.WhileClause).Until != cmd.Until { |
| 647 | return false |
| 648 | } |
| 649 | |
| 650 | if !statementsArrayMatch(cmd.Cond, b.(*syntax.WhileClause).Cond, c.(*syntax.WhileClause).Cond) { |
| 651 | return false |
| 652 | } |
| 653 | |
| 654 | if !statementsArrayMatch(cmd.Do, b.(*syntax.WhileClause).Do, c.(*syntax.WhileClause).Do) { |
| 655 | return false |
| 656 | } |
| 657 | case *syntax.ForClause: |
| 658 | if b.(*syntax.ForClause).Select != cmd.Select || c.(*syntax.ForClause).Select != cmd.Select { |
| 659 | return false |
| 660 | } |
| 661 | |
| 662 | if !loopMatch(cmd.Loop, b.(*syntax.ForClause).Loop, c.(*syntax.ForClause).Loop) { |
| 663 | return false |
| 664 | } |
| 665 | |
| 666 | if !statementsArrayMatch(cmd.Do, b.(*syntax.ForClause).Do, c.(*syntax.ForClause).Do) { |
| 667 | return false |
| 668 | } |
| 669 | case *syntax.CaseClause: |
| 670 | if !wordsMatch(cmd.Word.Parts, b.(*syntax.CaseClause).Word.Parts, c.(*syntax.CaseClause).Word.Parts, justStructure) { |
| 671 | return false |
| 672 | } |
| 673 | |
| 674 | if !caseItemArrayMatch(cmd.Items, b.(*syntax.CaseClause).Items, c.(*syntax.CaseClause).Items) { |
| 675 | return false |
| 676 | } |
| 677 | case *syntax.Block: |
| 678 | if !statementsArrayMatch(cmd.Stmts, b.(*syntax.Block).Stmts, c.(*syntax.Block).Stmts) { |
| 679 | return false |
| 680 | } |
| 681 | case *syntax.Subshell: |
| 682 | if !statementsArrayMatch(cmd.Stmts, b.(*syntax.Subshell).Stmts, c.(*syntax.Subshell).Stmts) { |
| 683 | return false |
| 684 | } |
| 685 | case *syntax.BinaryCmd: |
| 686 | if b.(*syntax.BinaryCmd).Op != cmd.Op || c.(*syntax.BinaryCmd).Op != cmd.Op { |
| 687 | return false |
| 688 | } |
| 689 | |
| 690 | if !statementsMatch(cmd.X, b.(*syntax.BinaryCmd).X, c.(*syntax.BinaryCmd).X) { |
| 691 | return false |
| 692 | } |
| 693 | |
| 694 | if !statementsMatch(cmd.Y, b.(*syntax.BinaryCmd).Y, c.(*syntax.BinaryCmd).Y) { |
| 695 | return false |
| 696 | } |
| 697 | |
| 698 | case *syntax.FuncDecl: |
| 699 | if b.(*syntax.FuncDecl).RsrvWord != cmd.RsrvWord || c.(*syntax.FuncDecl).RsrvWord != cmd.RsrvWord { |
| 700 | return false |
| 701 | } |
| 702 | |
| 703 | if b.(*syntax.FuncDecl).Name.Value != cmd.Name.Value || c.(*syntax.FuncDecl).Name.Value != cmd.Name.Value { |
| 704 | return false |
| 705 | } |
| 706 | |
| 707 | if !statementsMatch(cmd.Body, b.(*syntax.FuncDecl).Body, c.(*syntax.FuncDecl).Body) { |
| 708 | return false |
| 709 | } |
| 710 | case *syntax.ArithmCmd: |
| 711 | if b.(*syntax.ArithmCmd).Unsigned != cmd.Unsigned || c.(*syntax.ArithmCmd).Unsigned != cmd.Unsigned { |
| 712 | return false |
| 713 | } |
| 714 | |
| 715 | if !arithmExprMatch(cmd.X, b.(*syntax.ArithmCmd).X, c.(*syntax.ArithmCmd).X) { |
| 716 | return false |
| 717 | } |
| 718 | case *syntax.TestClause: |
| 719 | if !testExprMatch(cmd.X, b.(*syntax.TestClause).X, c.(*syntax.TestClause).X) { |
| 720 | return false |
| 721 | } |
| 722 | case *syntax.DeclClause: |
| 723 | if (b.(*syntax.DeclClause).Variant == nil) != (cmd.Variant == nil) || (c.(*syntax.DeclClause).Variant == nil) != (cmd.Variant == nil) { |
| 724 | return false |
| 725 | } |
| 726 | |
| 727 | if cmd.Variant != nil && |
| 728 | (b.(*syntax.DeclClause).Variant.Value != cmd.Variant.Value || c.(*syntax.DeclClause).Variant.Value != cmd.Variant.Value) { |
| 729 | return false |
| 730 | } |
| 731 | |
| 732 | if !assignArrayMatch(cmd.Args, b.(*syntax.DeclClause).Args, c.(*syntax.DeclClause).Args) { |
| 733 | return false |
| 734 | } |
| 735 | case *syntax.LetClause: |
| 736 | if !arithmExprArrayMatch(cmd.Exprs, b.(*syntax.LetClause).Exprs, c.(*syntax.LetClause).Exprs) { |
| 737 | return false |
| 738 | } |
| 739 | case *syntax.TimeClause: |
| 740 | if !statementsMatch(cmd.Stmt, b.(*syntax.TimeClause).Stmt, c.(*syntax.TimeClause).Stmt) { |
| 741 | return false |
| 742 | } |
| 743 | case *syntax.CoprocClause: |
| 744 | if !wordsMatch(cmd.Name.Parts, b.(*syntax.CoprocClause).Name.Parts, c.(*syntax.CoprocClause).Name.Parts, justStructure) { |
| 745 | return false |
| 746 | } |
| 747 | |
| 748 | if !statementsMatch(cmd.Stmt, b.(*syntax.CoprocClause).Stmt, c.(*syntax.CoprocClause).Stmt) { |
| 749 | return false |
| 750 | } |
| 751 | } |
| 752 | |
| 753 | return true |
| 754 | } |
| 755 | |
| 756 | func redirectsMatch(a, b, c *syntax.Redirect) bool { |
| 757 | if b.Op != a.Op || c.Op != a.Op { |
| 758 | return false |
| 759 | } |
| 760 | |
| 761 | if (b.N == nil) != (a.N == nil) || (c.N == nil) != (a.N == nil) { |
| 762 | return false |
| 763 | } |
| 764 | |
| 765 | if a.N != nil && |
| 766 | (b.N.Value != a.N.Value || c.N.Value != a.N.Value) { |
| 767 | return false |
| 768 | } |
| 769 | |
| 770 | if (b.Word == nil) != (a.Word == nil) || (c.Word == nil) != (a.Word == nil) { |
| 771 | return false |
| 772 | } |
| 773 | |
| 774 | if a.Word != nil && !wordsMatch(a.Word.Parts, b.Word.Parts, c.Word.Parts, matchExactly) { |
| 775 | return false |
| 776 | } |
| 777 | |
| 778 | if (b.Hdoc == nil) != (a.Hdoc == nil) || (c.Hdoc == nil) != (a.Hdoc == nil) { |
| 779 | return false |
| 780 | } |
| 781 | |
| 782 | if a.Hdoc != nil && !wordsMatch(a.Hdoc.Parts, b.Hdoc.Parts, c.Hdoc.Parts, matchExactly) { |
| 783 | return false |
| 784 | } |
| 785 | |
| 786 | return true |
| 787 | } |
| 788 | |
| 789 | func redirectsArrayMatch(a, b, c []*syntax.Redirect) bool { |
| 790 | for i := range a { |
| 791 | if !redirectsMatch(a[i], b[i], c[i]) { |
| 792 | return false |
| 793 | } |
| 794 | } |
| 795 | |
| 796 | return true |
| 797 | } |
| 798 | |
| 799 | func statementsMatch(a, b, c *syntax.Stmt) bool { |
| 800 | if b.Negated != a.Negated || c.Negated != a.Negated { |
| 801 | return false |
| 802 | } |
| 803 | |
| 804 | if b.Background != a.Background || c.Background != a.Background { |
| 805 | return false |
| 806 | } |
| 807 | |
| 808 | if b.Coprocess != a.Coprocess || c.Coprocess != a.Coprocess { |
| 809 | return false |
| 810 | } |
| 811 | |
| 812 | if !redirectsArrayMatch(a.Redirs, b.Redirs, c.Redirs) { |
| 813 | return false |
| 814 | } |
| 815 | |
| 816 | if (b.Cmd == nil) != (a.Cmd == nil) || (c.Cmd == nil) != (a.Cmd == nil) { |
| 817 | return false |
| 818 | } |
| 819 | |
| 820 | if a.Cmd != nil && !commandsMatch(a.Cmd, b.Cmd, c.Cmd) { |
| 821 | return false |
| 822 | } |
| 823 | |
| 824 | return true |
| 825 | } |
| 826 | |
| 827 | func statementsArrayMatch(a, b, c []*syntax.Stmt) bool { |
| 828 | for i := range a { |
| 829 | if !statementsMatch(a[i], b[i], c[i]) { |
| 830 | return false |
| 831 | } |
| 832 | } |
| 833 | |
| 834 | return true |
| 835 | } |
| 836 | |
| 837 | func scriptsMatch(a, b, c *syntax.File) bool { |
| 838 | if len(b.Stmts) != len(a.Stmts) || len(c.Stmts) != len(a.Stmts) { |
| 839 | return false |
| 840 | } |
| 841 | |
| 842 | if !statementsArrayMatch(a.Stmts, b.Stmts, c.Stmts) { |
| 843 | return false |
| 844 | } |
| 845 | |
| 846 | return true |
| 847 | } |
| 848 | |
| 849 | func prefixDash(in string) string { |
| 850 | return "-" + in |
| 851 | } |
| 852 | |
| 853 | // Execute applies a parsed template to the specified data object, |
| 854 | // and writes the output to wr. |
| 855 | // If an error occurs executing the template or writing its output, |
| 856 | // execution stops, but partial results may already have been written to |
| 857 | // the output writer. |
| 858 | // A template may be executed safely in parallel, although if parallel |
| 859 | // executions share a Writer the output may be interleaved. |
| 860 | // |
| 861 | // If data is a reflect.Value, the template applies to the concrete |
| 862 | // value that the reflect.Value holds, as in fmt.Print. |
| 863 | func (t *Template) Execute(wr io.Writer, data any) (err error) { |
| 864 | if data == nil { |
| 865 | return t.unsafeTemplate.Execute(wr, data) |
| 866 | } |
| 867 | |
| 868 | // An attacker may be able to cause type confusion or nil dereference panic at some stage of comparison |
| 869 | defer func() { |
| 870 | if r := recover(); r != nil { |
| 871 | err = ErrShInjection |
| 872 | } |
| 873 | }() |
| 874 | |
| 875 | // Calculate requested result first |
| 876 | var requestedResult bytes.Buffer |
| 877 | |
| 878 | if err := common.ExecuteWithShCallback(t.unsafeTemplate, t.uuid, common.EchoString, common.EchoString, &requestedResult, data); err != nil { |
| 879 | return err |
| 880 | } |
| 881 | |
| 882 | walked, err := t.unsafeTemplate.Clone() |
| 883 | if err != nil { |
| 884 | return err |
| 885 | } |
| 886 | walked.Tree = walked.Tree.Copy() |
| 887 | |
| 888 | common.WalkApplyFuncToNonDeclaractiveActions(walked, walked.Tree.Root) |
| 889 | |
| 890 | // Get baseline |
| 891 | var baselineResult bytes.Buffer |
| 892 | if err = common.ExecuteWithShCallback(walked, t.uuid, common.BaselineString, prefixDash, &baselineResult, data); err != nil { |
| 893 | return err |
| 894 | } |
| 895 | |
| 896 | parsedBaselineResult, err := syntax.NewParser().Parse(strings.NewReader(baselineResult.String()), "template.sh") |
| 897 | if err != nil { |
| 898 | return ErrInvalidShTemplate |
| 899 | } |
| 900 | |
| 901 | // If baseline was valid, request must also be valid YAML for no injection to have occurred |
| 902 | parsedRequestedResult, err := syntax.NewParser().Parse(strings.NewReader(requestedResult.String()), "template.sh") |
| 903 | if err != nil { |
| 904 | return ErrShInjection |
| 905 | } |
| 906 | |
| 907 | // Mutate the input |
| 908 | var mutatedResult bytes.Buffer |
| 909 | if err = common.ExecuteWithShCallback(walked, t.uuid, mutateString, prefixDash, &mutatedResult, data); err != nil { |
| 910 | return err |
| 911 | } |
| 912 | |
| 913 | parsedMutatedResult, err := syntax.NewParser().Parse(strings.NewReader(mutatedResult.String()), "template.sh") |
| 914 | if err != nil { |
| 915 | return ErrShInjection |
| 916 | } |
| 917 | |
| 918 | // Compare results |
| 919 | if !scriptsMatch(parsedBaselineResult, parsedRequestedResult, parsedMutatedResult) { |
| 920 | return ErrShInjection |
| 921 | } |
| 922 | |
| 923 | requestedResult.WriteTo(wr) |
| 924 | return nil |
| 925 | } |
| 926 | |
| 927 | // Name returns the name of the template. |
| 928 | func (t *Template) Name() string { |
| 929 | return t.unsafeTemplate.Name() |
| 930 | } |
| 931 | |
| 932 | // New allocates a new, undefined template associated with the given one and with the same |
| 933 | // delimiters. The association, which is transitive, allows one template to |
| 934 | // invoke another with a {{template}} action. |
| 935 | // |
| 936 | // Because associated templates share underlying data, template construction |
| 937 | // cannot be done safely in parallel. Once the templates are constructed, they |
| 938 | // can be executed in parallel. |
| 939 | func (t *Template) New(name string) *Template { |
| 940 | id := uuid.New() |
| 941 | funcMap := common.BuildTextTemplateFuncMap(id) |
| 942 | return &Template{unsafeTemplate: t.unsafeTemplate.New(name).Funcs(funcMap), uuid: id} |
| 943 | } |
| 944 | |
| 945 | // Clone returns a duplicate of the template, including all associated |
| 946 | // templates. The actual representation is not copied, but the name space of |
| 947 | // associated templates is, so further calls to Parse in the copy will add |
| 948 | // templates to the copy but not to the original. Clone can be used to prepare |
| 949 | // common templates and use them with variant definitions for other templates |
| 950 | // by adding the variants after the clone is made. |
| 951 | func (t *Template) Clone() (*Template, error) { |
| 952 | id := uuid.New() |
| 953 | nt, err := t.unsafeTemplate.Clone() |
| 954 | return &Template{unsafeTemplate: nt, uuid: id}, err |
| 955 | } |
| 956 | |
| 957 | // AddParseTree associates the argument parse tree with the template t, giving |
| 958 | // it the specified name. If the template has not been defined, this tree becomes |
| 959 | // its definition. If it has been defined and already has that name, the existing |
| 960 | // definition is replaced; otherwise a new template is created, defined, and returned. |
| 961 | func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error) { |
| 962 | nt, err := t.unsafeTemplate.AddParseTree(name, tree) |
| 963 | |
| 964 | if nt != t.unsafeTemplate { |
| 965 | id := uuid.New() |
| 966 | return &Template{unsafeTemplate: nt, uuid: id}, err |
| 967 | } |
| 968 | return t, err |
| 969 | } |
| 970 | |
| 971 | // Option sets options for the template. Options are described by |
| 972 | // strings, either a simple string or "key=value". There can be at |
| 973 | // most one equals sign in an option string. If the option string |
| 974 | // is unrecognized or otherwise invalid, Option panics. |
| 975 | // |
| 976 | // Known options: |
| 977 | // |
| 978 | // missingkey: Control the behavior during execution if a map is |
| 979 | // indexed with a key that is not present in the map. |
| 980 | // |
| 981 | // "missingkey=default" or "missingkey=invalid" |
| 982 | // The default behavior: Do nothing and continue execution. |
| 983 | // If printed, the result of the index operation is the string |
| 984 | // "<no value>". |
| 985 | // "missingkey=zero" |
| 986 | // The operation returns the zero value for the map type's element. |
| 987 | // "missingkey=error" |
| 988 | // Execution stops immediately with an error. |
| 989 | func (t *Template) Option(opt ...string) *Template { |
| 990 | for _, s := range opt { |
| 991 | t.unsafeTemplate.Option(s) |
| 992 | } |
| 993 | return t |
| 994 | } |
| 995 | |
| 996 | // Templates returns a slice of defined templates associated with t. |
| 997 | func (t *Template) Templates() []*Template { |
| 998 | s := t.unsafeTemplate.Templates() |
| 999 | var id string |
| 1000 | |
| 1001 | var ns []*Template |
| 1002 | for _, nt := range s { |
| 1003 | id = uuid.New() |
| 1004 | ns = append(ns, &Template{unsafeTemplate: nt, uuid: id}) |
| 1005 | } |
| 1006 | |
| 1007 | return ns |
| 1008 | } |
| 1009 | |
| 1010 | // ExecuteTemplate applies the template associated with t that has the given name |
| 1011 | // to the specified data object and writes the output to wr. |
| 1012 | // If an error occurs executing the template or writing its output, |
| 1013 | // execution stops, but partial results may already have been written to |
| 1014 | // the output writer. |
| 1015 | // A template may be executed safely in parallel, although if parallel |
| 1016 | // executions share a Writer the output may be interleaved. |
| 1017 | func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error { |
| 1018 | tmpl := t.Lookup(name) |
| 1019 | if tmpl == nil { |
| 1020 | return fmt.Errorf("template: no template %q associated with template %q", name, t.Name()) |
| 1021 | } |
| 1022 | return tmpl.Execute(wr, data) |
| 1023 | } |
| 1024 | |
| 1025 | // Delims sets the action delimiters to the specified strings, to be used in |
| 1026 | // subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template |
| 1027 | // definitions will inherit the settings. An empty delimiter stands for the |
| 1028 | // corresponding default: {{ or }}. |
| 1029 | // The return value is the template, so calls can be chained. |
| 1030 | func (t *Template) Delims(left, right string) *Template { |
| 1031 | t.unsafeTemplate.Delims(left, right) |
| 1032 | return t |
| 1033 | } |
| 1034 | |
| 1035 | // DefinedTemplates returns a string listing the defined templates, |
| 1036 | // prefixed by the string "; defined templates are: ". If there are none, |
| 1037 | // it returns the empty string. For generating an error message here |
| 1038 | // and in html/template. |
| 1039 | func (t *Template) DefinedTemplates() string { |
| 1040 | return t.unsafeTemplate.DefinedTemplates() |
| 1041 | } |
| 1042 | |
| 1043 | // Funcs adds the elements of the argument map to the template's function map. |
| 1044 | // It must be called before the template is parsed. |
| 1045 | // It panics if a value in the map is not a function with appropriate return |
| 1046 | // type or if the name cannot be used syntactically as a function in a template. |
| 1047 | // It is legal to overwrite elements of the map. The return value is the template, |
| 1048 | // so calls can be chained. |
| 1049 | func (t *Template) Funcs(funcMap FuncMap) *Template { |
| 1050 | t.unsafeTemplate.Funcs(funcMap) |
| 1051 | return t |
| 1052 | } |
| 1053 | |
| 1054 | // Lookup returns the template with the given name that is associated with t. |
| 1055 | // It returns nil if there is no such template or the template has no definition. |
| 1056 | func (t *Template) Lookup(name string) *Template { |
| 1057 | nt := t.unsafeTemplate.Lookup(name) |
| 1058 | |
| 1059 | if nt == nil { |
| 1060 | return nil |
| 1061 | } |
| 1062 | |
| 1063 | if nt != t.unsafeTemplate { |
| 1064 | id := uuid.New() |
| 1065 | return &Template{unsafeTemplate: nt, uuid: id} |
| 1066 | } |
| 1067 | |
| 1068 | return t |
| 1069 | } |
| 1070 | |
| 1071 | // Parse parses text as a template body for t. |
| 1072 | // Named template definitions ({{define ...}} or {{block ...}} statements) in text |
| 1073 | // define additional templates associated with t and are removed from the |
| 1074 | // definition of t itself. |
| 1075 | // |
| 1076 | // Templates can be redefined in successive calls to Parse. |
| 1077 | // A template definition with a body containing only white space and comments |
| 1078 | // is considered empty and will not replace an existing template's body. |
| 1079 | // This allows using Parse to add new named template definitions without |
| 1080 | // overwriting the main template body. |
| 1081 | func (t *Template) Parse(text string) (*Template, error) { |
| 1082 | nt, err := t.unsafeTemplate.Parse(text) |
| 1083 | |
| 1084 | if nt != t.unsafeTemplate { |
| 1085 | id := uuid.New() |
| 1086 | return &Template{unsafeTemplate: nt, uuid: id}, err |
| 1087 | } |
| 1088 | |
| 1089 | return t, err |
| 1090 | } |
| 1091 | |
| 1092 | // Must is a helper that wraps a call to a function returning (*Template, error) |
| 1093 | // and panics if the error is non-nil. It is intended for use in variable |
| 1094 | // initializations such as |
| 1095 | // |
| 1096 | // var t = template.Must(template.New("name").Parse("text")) |
| 1097 | func Must(t *Template, err error) *Template { |
| 1098 | if err != nil { |
| 1099 | panic(err) |
| 1100 | } |
| 1101 | return t |
| 1102 | } |
| 1103 | |
| 1104 | func readFileOS(file string) (name string, b []byte, err error) { |
| 1105 | name = filepath.Base(file) |
| 1106 | b, err = os.ReadFile(file) |
| 1107 | return |
| 1108 | } |
| 1109 | |
| 1110 | func readFileFS(fsys fs.FS) func(string) (string, []byte, error) { |
| 1111 | return func(file string) (name string, b []byte, err error) { |
| 1112 | name = path.Base(file) |
| 1113 | b, err = fs.ReadFile(fsys, file) |
| 1114 | return |
| 1115 | } |
| 1116 | } |
| 1117 | |
| 1118 | func parseFiles(t *Template, readFile func(string) (string, []byte, error), filenames ...string) (*Template, error) { |
| 1119 | if len(filenames) == 0 { |
| 1120 | // Not really a problem, but be consistent. |
| 1121 | return nil, fmt.Errorf("template: no files named in call to ParseFiles") |
| 1122 | } |
| 1123 | for _, filename := range filenames { |
| 1124 | name, b, err := readFile(filename) |
| 1125 | if err != nil { |
| 1126 | return nil, err |
| 1127 | } |
| 1128 | s := string(b) |
| 1129 | // First template becomes return value if not already defined, |
| 1130 | // and we use that one for subsequent New calls to associate |
| 1131 | // all the templates together. Also, if this file has the same name |
| 1132 | // as t, this file becomes the contents of t, so |
| 1133 | // t, err := New(name).Funcs(xxx).ParseFiles(name) |
| 1134 | // works. Otherwise we create a new template associated with t. |
| 1135 | var tmpl *Template |
| 1136 | if t == nil { |
| 1137 | t = New(name) |
| 1138 | } |
| 1139 | if name == t.Name() { |
| 1140 | tmpl = t |
| 1141 | } else { |
| 1142 | tmpl = t.New(name) |
| 1143 | } |
| 1144 | _, err = tmpl.Parse(s) |
| 1145 | if err != nil { |
| 1146 | return nil, err |
| 1147 | } |
| 1148 | } |
| 1149 | return t, nil |
| 1150 | } |
| 1151 | |
| 1152 | // parseGlob is the implementation of the function and method ParseGlob. |
| 1153 | func parseGlob(t *Template, pattern string) (*Template, error) { |
| 1154 | filenames, err := filepath.Glob(pattern) |
| 1155 | if err != nil { |
| 1156 | return nil, err |
| 1157 | } |
| 1158 | if len(filenames) == 0 { |
| 1159 | return nil, fmt.Errorf("template: pattern matches no files: %#q", pattern) |
| 1160 | } |
| 1161 | return parseFiles(t, readFileOS, filenames...) |
| 1162 | } |
| 1163 | |
| 1164 | func parseFS(t *Template, fsys fs.FS, patterns []string) (*Template, error) { |
| 1165 | var filenames []string |
| 1166 | for _, pattern := range patterns { |
| 1167 | list, err := fs.Glob(fsys, pattern) |
| 1168 | if err != nil { |
| 1169 | return nil, err |
| 1170 | } |
| 1171 | if len(list) == 0 { |
| 1172 | return nil, fmt.Errorf("template: pattern matches no files: %#q", pattern) |
| 1173 | } |
| 1174 | filenames = append(filenames, list...) |
| 1175 | } |
| 1176 | return parseFiles(t, readFileFS(fsys), filenames...) |
| 1177 | } |
| 1178 | |
| 1179 | // ParseFiles creates a new Template and parses the template definitions from |
| 1180 | // the named files. The returned template's name will have the base name and |
| 1181 | // parsed contents of the first file. There must be at least one file. |
| 1182 | // If an error occurs, parsing stops and the returned *Template is nil. |
| 1183 | // |
| 1184 | // When parsing multiple files with the same name in different directories, |
| 1185 | // the last one mentioned will be the one that results. |
| 1186 | // For instance, ParseFiles("a/foo", "b/foo") stores "b/foo" as the template |
| 1187 | // named "foo", while "a/foo" is unavailable. |
| 1188 | func ParseFiles(filenames ...string) (*Template, error) { |
| 1189 | return parseFiles(nil, readFileOS, filenames...) |
| 1190 | } |
| 1191 | |
| 1192 | // ParseFiles parses the named files and associates the resulting templates with |
| 1193 | // t. If an error occurs, parsing stops and the returned template is nil; |
| 1194 | // otherwise it is t. There must be at least one file. |
| 1195 | // Since the templates created by ParseFiles are named by the base |
| 1196 | // names of the argument files, t should usually have the name of one |
| 1197 | // of the (base) names of the files. If it does not, depending on t's |
| 1198 | // contents before calling ParseFiles, t.Execute may fail. In that |
| 1199 | // case use t.ExecuteTemplate to execute a valid template. |
| 1200 | // |
| 1201 | // When parsing multiple files with the same name in different directories, |
| 1202 | // the last one mentioned will be the one that results. |
| 1203 | func (t *Template) ParseFiles(filenames ...string) (*Template, error) { |
| 1204 | // Ensure template is inited |
| 1205 | t.Option() |
| 1206 | |
| 1207 | return parseFiles(t, readFileOS, filenames...) |
| 1208 | } |
| 1209 | |
| 1210 | // ParseGlob creates a new Template and parses the template definitions from |
| 1211 | // the files identified by the pattern. The files are matched according to the |
| 1212 | // semantics of filepath.Match, and the pattern must match at least one file. |
| 1213 | // The returned template will have the (base) name and (parsed) contents of the |
| 1214 | // first file matched by the pattern. ParseGlob is equivalent to calling |
| 1215 | // ParseFiles with the list of files matched by the pattern. |
| 1216 | // |
| 1217 | // When parsing multiple files with the same name in different directories, |
| 1218 | // the last one mentioned will be the one that results. |
| 1219 | func ParseGlob(pattern string) (*Template, error) { |
| 1220 | return parseGlob(nil, pattern) |
| 1221 | } |
| 1222 | |
| 1223 | // ParseGlob parses the template definitions in the files identified by the |
| 1224 | // pattern and associates the resulting templates with t. The files are matched |
| 1225 | // according to the semantics of filepath.Match, and the pattern must match at |
| 1226 | // least one file. ParseGlob is equivalent to calling t.ParseFiles with the |
| 1227 | // list of files matched by the pattern. |
| 1228 | // |
| 1229 | // When parsing multiple files with the same name in different directories, |
| 1230 | // the last one mentioned will be the one that results. |
| 1231 | func (t *Template) ParseGlob(pattern string) (*Template, error) { |
| 1232 | // Ensure template is inited |
| 1233 | t.Option() |
| 1234 | |
| 1235 | return parseGlob(t, pattern) |
| 1236 | } |
| 1237 | |
| 1238 | // ParseFS is like ParseFiles or ParseGlob but reads from the file system fsys |
| 1239 | // instead of the host operating system's file system. |
| 1240 | // It accepts a list of glob patterns. |
| 1241 | // (Note that most file names serve as glob patterns matching only themselves.) |
| 1242 | func ParseFS(fsys fs.FS, patterns ...string) (*Template, error) { |
| 1243 | return parseFS(nil, fsys, patterns) |
| 1244 | } |
| 1245 | |
| 1246 | // ParseFS is like ParseFiles or ParseGlob but reads from the file system fsys |
| 1247 | // instead of the host operating system's file system. |
| 1248 | // It accepts a list of glob patterns. |
| 1249 | // (Note that most file names serve as glob patterns matching only themselves.) |
| 1250 | func (t *Template) ParseFS(fsys fs.FS, patterns ...string) (*Template, error) { |
| 1251 | // Ensure template is inited |
| 1252 | t.Option() |
| 1253 | |
| 1254 | return parseFS(t, fsys, patterns) |
| 1255 | } |
| 1256 | |
| 1257 | // HTMLEscape writes to w the escaped HTML equivalent of the plain text data b. |
| 1258 | func HTMLEscape(w io.Writer, b []byte) { |
| 1259 | template.HTMLEscape(w, b) |
| 1260 | } |
| 1261 | |
| 1262 | // HTMLEscapeString returns the escaped HTML equivalent of the plain text data s. |
| 1263 | func HTMLEscapeString(s string) string { |
| 1264 | return template.HTMLEscapeString(s) |
| 1265 | } |
| 1266 | |
| 1267 | // HTMLEscaper returns the escaped HTML equivalent of the textual |
| 1268 | // representation of its arguments. |
| 1269 | func HTMLEscaper(args ...any) string { |
| 1270 | return template.HTMLEscaper(args) |
| 1271 | } |
| 1272 | |
| 1273 | // IsTrue reports whether the value is 'true', in the sense of not the zero of its type, |
| 1274 | // and whether the value has a meaningful truth value. This is the definition of |
| 1275 | // truth used by if and other such actions. |
| 1276 | func IsTrue(val any) (truth, ok bool) { |
| 1277 | return template.IsTrue(val) |
| 1278 | } |
| 1279 | |
| 1280 | // JSEscape writes to w the escaped JavaScript equivalent of the plain text data b. |
| 1281 | func JSEscape(w io.Writer, b []byte) { |
| 1282 | template.JSEscape(w, b) |
| 1283 | } |
| 1284 | |
| 1285 | // JSEscapeString returns the escaped JavaScript equivalent of the plain text data s. |
| 1286 | func JSEscapeString(s string) string { |
| 1287 | return template.JSEscapeString(s) |
| 1288 | } |
| 1289 | |
| 1290 | // JSEscaper returns the escaped JavaScript equivalent of the textual |
| 1291 | // representation of its arguments. |
| 1292 | func JSEscaper(args ...any) string { |
| 1293 | return template.JSEscaper(args) |
| 1294 | } |
| 1295 | |
| 1296 | // URLQueryEscaper returns the escaped value of the textual representation of |
| 1297 | // its arguments in a form suitable for embedding in a URL query. |
| 1298 | func URLQueryEscaper(args ...any) string { |
| 1299 | return template.URLQueryEscaper(args) |
| 1300 | } |