template_sets.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package pongo2
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "path/filepath"
  8. "sync"
  9. )
  10. // A template set allows you to create your own group of templates with their own global context (which is shared
  11. // among all members of the set), their own configuration (like a specific base directory) and their own sandbox.
  12. // It's useful for a separation of different kind of templates (e. g. web templates vs. mail templates).
  13. type TemplateSet struct {
  14. name string
  15. // Globals will be provided to all templates created within this template set
  16. Globals Context
  17. // If debug is true (default false), ExecutionContext.Logf() will work and output to STDOUT. Furthermore,
  18. // FromCache() won't cache the templates. Make sure to synchronize the access to it in case you're changing this
  19. // variable during program execution (and template compilation/execution).
  20. Debug bool
  21. // Base directory: If you set the base directory (string is non-empty), all filename lookups in tags/filters are
  22. // relative to this directory. If it's empty, all lookups are relative to the current filename which is importing.
  23. baseDirectory string
  24. // Sandbox features
  25. // - Limit access to directories (using SandboxDirectories)
  26. // - Disallow access to specific tags and/or filters (using BanTag() and BanFilter())
  27. //
  28. // You can limit file accesses (for all tags/filters which are using pongo2's file resolver technique)
  29. // to these sandbox directories. All default pongo2 filters/tags are respecting these restrictions.
  30. // For example, if you only have your base directory in the list, a {% ssi "/etc/passwd" %} will not work.
  31. // No items in SandboxDirectories means no restrictions at all.
  32. //
  33. // For efficiency reasons you can ban tags/filters only *before* you have added your first
  34. // template to the set (restrictions are statically checked). After you added one, it's not possible anymore
  35. // (for your personal security).
  36. //
  37. // SandboxDirectories can be changed at runtime. Please synchronize the access to it if you need to change it
  38. // after you've added your first template to the set. You *must* use this match pattern for your directories:
  39. // http://golang.org/pkg/path/filepath/#Match
  40. SandboxDirectories []string
  41. firstTemplateCreated bool
  42. bannedTags map[string]bool
  43. bannedFilters map[string]bool
  44. // Template cache (for FromCache())
  45. templateCache map[string]*Template
  46. templateCacheMutex sync.Mutex
  47. }
  48. // Create your own template sets to separate different kind of templates (e. g. web from mail templates) with
  49. // different globals or other configurations (like base directories).
  50. func NewSet(name string) *TemplateSet {
  51. return &TemplateSet{
  52. name: name,
  53. Globals: make(Context),
  54. bannedTags: make(map[string]bool),
  55. bannedFilters: make(map[string]bool),
  56. templateCache: make(map[string]*Template),
  57. }
  58. }
  59. // Use this function to set your template set's base directory. This directory will be used for any relative
  60. // path in filters, tags and From*-functions to determine your template.
  61. func (set *TemplateSet) SetBaseDirectory(name string) error {
  62. // Make the path absolute
  63. if !filepath.IsAbs(name) {
  64. abs, err := filepath.Abs(name)
  65. if err != nil {
  66. return err
  67. }
  68. name = abs
  69. }
  70. // Check for existence
  71. fi, err := os.Stat(name)
  72. if err != nil {
  73. return err
  74. }
  75. if !fi.IsDir() {
  76. return fmt.Errorf("The given path '%s' is not a directory.")
  77. }
  78. set.baseDirectory = name
  79. return nil
  80. }
  81. func (set *TemplateSet) BaseDirectory() string {
  82. return set.baseDirectory
  83. }
  84. // Ban a specific tag for this template set. See more in the documentation for TemplateSet.
  85. func (set *TemplateSet) BanTag(name string) {
  86. _, has := tags[name]
  87. if !has {
  88. panic(fmt.Sprintf("Tag '%s' not found.", name))
  89. }
  90. if set.firstTemplateCreated {
  91. panic("You cannot ban any tags after you've added your first template to your template set.")
  92. }
  93. _, has = set.bannedTags[name]
  94. if has {
  95. panic(fmt.Sprintf("Tag '%s' is already banned.", name))
  96. }
  97. set.bannedTags[name] = true
  98. }
  99. // Ban a specific filter for this template set. See more in the documentation for TemplateSet.
  100. func (set *TemplateSet) BanFilter(name string) {
  101. _, has := filters[name]
  102. if !has {
  103. panic(fmt.Sprintf("Filter '%s' not found.", name))
  104. }
  105. if set.firstTemplateCreated {
  106. panic("You cannot ban any filters after you've added your first template to your template set.")
  107. }
  108. _, has = set.bannedFilters[name]
  109. if has {
  110. panic(fmt.Sprintf("Filter '%s' is already banned.", name))
  111. }
  112. set.bannedFilters[name] = true
  113. }
  114. // FromCache() is a convenient method to cache templates. It is thread-safe
  115. // and will only compile the template associated with a filename once.
  116. // If TemplateSet.Debug is true (for example during development phase),
  117. // FromCache() will not cache the template and instead recompile it on any
  118. // call (to make changes to a template live instantaneously).
  119. // Like FromFile(), FromCache() takes a relative path to a set base directory.
  120. // Sandbox restrictions apply (if given).
  121. func (set *TemplateSet) FromCache(filename string) (*Template, error) {
  122. if set.Debug {
  123. // Recompile on any request
  124. return set.FromFile(filename)
  125. } else {
  126. // Cache the template
  127. cleaned_filename := set.resolveFilename(nil, filename)
  128. set.templateCacheMutex.Lock()
  129. defer set.templateCacheMutex.Unlock()
  130. tpl, has := set.templateCache[cleaned_filename]
  131. // Cache miss
  132. if !has {
  133. tpl, err := set.FromFile(cleaned_filename)
  134. if err != nil {
  135. return nil, err
  136. }
  137. set.templateCache[cleaned_filename] = tpl
  138. return tpl, nil
  139. }
  140. // Cache hit
  141. return tpl, nil
  142. }
  143. }
  144. // Loads a template from string and returns a Template instance.
  145. func (set *TemplateSet) FromString(tpl string) (*Template, error) {
  146. set.firstTemplateCreated = true
  147. return newTemplateString(set, tpl)
  148. }
  149. // Loads a template from a filename and returns a Template instance.
  150. // If a base directory is set, the filename must be either relative to it
  151. // or be an absolute path. Sandbox restrictions (SandboxDirectories) apply
  152. // if given.
  153. func (set *TemplateSet) FromFile(filename string) (*Template, error) {
  154. set.firstTemplateCreated = true
  155. buf, err := ioutil.ReadFile(set.resolveFilename(nil, filename))
  156. if err != nil {
  157. return nil, &Error{
  158. Filename: filename,
  159. Sender: "fromfile",
  160. ErrorMsg: err.Error(),
  161. }
  162. }
  163. return newTemplate(set, filename, false, string(buf))
  164. }
  165. // Shortcut; renders a template string directly. Panics when providing a
  166. // malformed template or an error occurs during execution.
  167. func (set *TemplateSet) RenderTemplateString(s string, ctx Context) string {
  168. set.firstTemplateCreated = true
  169. tpl := Must(set.FromString(s))
  170. result, err := tpl.Execute(ctx)
  171. if err != nil {
  172. panic(err)
  173. }
  174. return result
  175. }
  176. // Shortcut; renders a template file directly. Panics when providing a
  177. // malformed template or an error occurs during execution.
  178. func (set *TemplateSet) RenderTemplateFile(fn string, ctx Context) string {
  179. set.firstTemplateCreated = true
  180. tpl := Must(set.FromFile(fn))
  181. result, err := tpl.Execute(ctx)
  182. if err != nil {
  183. panic(err)
  184. }
  185. return result
  186. }
  187. func (set *TemplateSet) logf(format string, args ...interface{}) {
  188. if set.Debug {
  189. logger.Printf(fmt.Sprintf("[template set: %s] %s", set.name, format), args...)
  190. }
  191. }
  192. // Resolves a filename relative to the base directory. Absolute paths are allowed.
  193. // If sandbox restrictions are given (SandboxDirectories), they will be respected and checked.
  194. // On sandbox restriction violation, resolveFilename() panics.
  195. func (set *TemplateSet) resolveFilename(tpl *Template, filename string) (resolved_path string) {
  196. if len(set.SandboxDirectories) > 0 {
  197. defer func() {
  198. // Remove any ".." or other crap
  199. resolved_path = filepath.Clean(resolved_path)
  200. // Make the path absolute
  201. abs_path, err := filepath.Abs(resolved_path)
  202. if err != nil {
  203. panic(err)
  204. }
  205. resolved_path = abs_path
  206. // Check against the sandbox directories (once one pattern matches, we're done and can allow it)
  207. for _, pattern := range set.SandboxDirectories {
  208. matched, err := filepath.Match(pattern, resolved_path)
  209. if err != nil {
  210. panic("Wrong sandbox directory match pattern (see http://golang.org/pkg/path/filepath/#Match).")
  211. }
  212. if matched {
  213. // OK!
  214. return
  215. }
  216. }
  217. // No pattern matched, we have to log+deny the request
  218. set.logf("Access attempt outside of the sandbox directories (blocked): '%s'", resolved_path)
  219. resolved_path = ""
  220. }()
  221. }
  222. if filepath.IsAbs(filename) {
  223. return filename
  224. }
  225. if set.baseDirectory == "" {
  226. if tpl != nil {
  227. if tpl.is_tpl_string {
  228. return filename
  229. }
  230. base := filepath.Dir(tpl.name)
  231. return filepath.Join(base, filename)
  232. }
  233. return filename
  234. } else {
  235. return filepath.Join(set.baseDirectory, filename)
  236. }
  237. }
  238. // Logging function (internally used)
  239. func logf(format string, items ...interface{}) {
  240. if debug {
  241. logger.Printf(format, items...)
  242. }
  243. }
  244. var (
  245. debug bool // internal debugging
  246. logger = log.New(os.Stdout, "[pongo2] ", log.LstdFlags)
  247. // Creating a default set
  248. DefaultSet = NewSet("default")
  249. // Methods on the default set
  250. FromString = DefaultSet.FromString
  251. FromFile = DefaultSet.FromFile
  252. FromCache = DefaultSet.FromCache
  253. RenderTemplateString = DefaultSet.RenderTemplateString
  254. RenderTemplateFile = DefaultSet.RenderTemplateFile
  255. // Globals for the default set
  256. Globals = DefaultSet.Globals
  257. )