Debian Codegraph @

hugolib/alias.go

raw
1 // Copyright 2019 The Hugo Authors. All rights reserved.
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 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package hugolib
15
16 import (
17 "bytes"
18 "context"
19 "errors"
20 "fmt"
21 "io"
22 "path"
23 "path/filepath"
24 "runtime"
25 "strings"
26
27 "github.com/gohugoio/hugo/common/loggers"
28 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
29 "github.com/gohugoio/hugo/output"
30 "github.com/gohugoio/hugo/publisher"
31 "github.com/gohugoio/hugo/resources/page"
32 "github.com/gohugoio/hugo/tpl/tplimpl"
33 )
34
35 type aliasHandler struct {
36 ts *tplimpl.TemplateStore
37 log loggers.Logger
38 allowRoot bool
39 }
40
41 func newAliasHandler(ts *tplimpl.TemplateStore, l loggers.Logger, allowRoot bool) aliasHandler {
42 return aliasHandler{ts, l, allowRoot}
43 }
44
45 type aliasPage struct {
46 Permalink string
47 page.Page
48 }
49
50 func (a aliasHandler) renderAlias(permalink string, p page.Page, matrix sitesmatrix.VectorProvider) (io.Reader, error) {
51 var templateDesc tplimpl.TemplateDescriptor
52 var base string = ""
53 if ps, ok := p.(*pageState); ok {
54 base, templateDesc = ps.GetInternalTemplateBasePathAndDescriptor()
55 }
56 templateDesc.LayoutFromUser = ""
57 templateDesc.Kind = ""
58 templateDesc.OutputFormat = output.AliasHTMLFormat.Name
59 templateDesc.MediaType = output.AliasHTMLFormat.MediaType.Type
60
61 q := tplimpl.TemplateQuery{
62 Path: base,
63 Category: tplimpl.CategoryLayout,
64 Desc: templateDesc,
65 Sites: matrix,
66 }
67
68 t := a.ts.LookupPagesLayout(q)
69 if t == nil {
70 return nil, errors.New("no alias template found")
71 }
72
73 if p == nil {
74 p = page.NopPage
75 }
76
77 data := aliasPage{
78 permalink,
79 p,
80 }
81
82 ctx := a.ts.PrepareTopLevelRenderCtx(context.Background(), p)
83
84 buffer := new(bytes.Buffer)
85 err := a.ts.ExecuteWithContext(ctx, t, buffer, data)
86 if err != nil {
87 return nil, err
88 }
89 return buffer, nil
90 }
91
92 func (s *Site) writeDestAlias(path, permalink string, outputFormat output.Format, p page.Page) (err error) {
93 return s.publishDestAlias(false, path, permalink, outputFormat, p)
94 }
95
96 func (s *Site) publishDestAlias(allowRoot bool, path, permalink string, outputFormat output.Format, p page.Page) (err error) {
97 handler := newAliasHandler(s.GetTemplateStore(), s.Log, allowRoot)
98
99 targetPath, err := handler.targetPathAlias(path, outputFormat)
100 if err != nil {
101 return err
102 }
103
104 aliasContent, err := handler.renderAlias(permalink, p, s.siteVector)
105 if err != nil {
106 return err
107 }
108
109 pd := publisher.Descriptor{
110 Src: aliasContent,
111 TargetPath: targetPath,
112 StatCounter: &s.PathSpec.ProcessingStats.Aliases,
113 OutputFormat: outputFormat,
114 }
115
116 if s.conf.RelativeURLs || s.conf.CanonifyURLs {
117 pd.AbsURLPath = s.absURLPath(targetPath)
118 }
119
120 return s.publisher.Publish(pd)
121 }
122
123 func (a aliasHandler) targetPathAlias(src string, of output.Format) (string, error) {
124 originalAlias := src
125 if len(src) <= 0 {
126 return "", fmt.Errorf("alias \"\" is an empty string")
127 }
128
129 alias := path.Clean(filepath.ToSlash(src))
130
131 if !a.allowRoot && alias == "/" {
132 return "", fmt.Errorf("alias \"%s\" resolves to website root directory", originalAlias)
133 }
134
135 components := strings.Split(alias, "/")
136
137 // Validate against directory traversal
138 if components[0] == ".." {
139 return "", fmt.Errorf("alias \"%s\" traverses outside the website root directory", originalAlias)
140 }
141
142 // Handle Windows file and directory naming restrictions
143 // See "Naming Files, Paths, and Namespaces" on MSDN
144 // https://msdn.microsoft.com/en-us/library/aa365247%28v=VS.85%29.aspx?f=255&MSPPError=-2147217396
145 msgs := []string{}
146 reservedNames := []string{"CON", "PRN", "AUX", "NUL", "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"}
147
148 if strings.ContainsAny(alias, ":*?\"<>|") {
149 msgs = append(msgs, fmt.Sprintf("Alias \"%s\" contains invalid characters on Windows: : * ? \" < > |", originalAlias))
150 }
151 for _, ch := range alias {
152 if ch < ' ' {
153 msgs = append(msgs, fmt.Sprintf("Alias \"%s\" contains ASCII control code (0x00 to 0x1F), invalid on Windows: : * ? \" < > |", originalAlias))
154 continue
155 }
156 }
157 for _, comp := range components {
158 if strings.HasSuffix(comp, " ") || strings.HasSuffix(comp, ".") {
159 msgs = append(msgs, fmt.Sprintf("Alias \"%s\" contains component with a trailing space or period, problematic on Windows", originalAlias))
160 }
161 for _, r := range reservedNames {
162 if comp == r {
163 msgs = append(msgs, fmt.Sprintf("Alias \"%s\" contains component with reserved name \"%s\" on Windows", originalAlias, r))
164 }
165 }
166 }
167 if len(msgs) > 0 {
168 if runtime.GOOS == "windows" {
169 for _, m := range msgs {
170 a.log.Errorln(m)
171 }
172 return "", fmt.Errorf("cannot create \"%s\": Windows filename restriction", originalAlias)
173 }
174 for _, m := range msgs {
175 a.log.Infoln(m)
176 }
177 }
178
179 // Add the final touch. When the alias does not already end in one of the
180 // output format's configured suffixes, treat it as a directory and append
181 // the format's base name and suffix (e.g. index.html).
182 alias = strings.TrimPrefix(alias, "/")
183 baseFile := of.BaseName + of.MediaType.FirstSuffix.FullSuffix
184 if strings.HasSuffix(alias, "/") {
185 alias = alias + baseFile
186 } else if !pathHasOutputFormatSuffix(alias, of) {
187 alias = alias + "/" + baseFile
188 }
189
190 return filepath.FromSlash(alias), nil
191 }
192
193 // pathHasOutputFormatSuffix reports whether the last element of p ends in one
194 // of the suffixes configured for the output format's media type.
195 func pathHasOutputFormatSuffix(p string, of output.Format) bool {
196 ext := path.Ext(p)
197 return ext != "" && of.MediaType.HasSuffix(ext[1:])
198 }