github.com/SDLMoe/hugo@v0.47.1/hugolib/alias.go (about)

     1  // Copyright 2017 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  	"fmt"
    19  	"html/template"
    20  	"io"
    21  	"path/filepath"
    22  	"runtime"
    23  	"strings"
    24  
    25  	"github.com/gohugoio/hugo/output"
    26  	"github.com/gohugoio/hugo/publisher"
    27  	"github.com/gohugoio/hugo/tpl"
    28  
    29  	jww "github.com/spf13/jwalterweatherman"
    30  
    31  	"github.com/gohugoio/hugo/helpers"
    32  )
    33  
    34  const (
    35  	alias      = "<!DOCTYPE html><html><head><title>{{ .Permalink }}</title><link rel=\"canonical\" href=\"{{ .Permalink }}\"/><meta name=\"robots\" content=\"noindex\"><meta charset=\"utf-8\" /><meta http-equiv=\"refresh\" content=\"0; url={{ .Permalink }}\" /></head></html>"
    36  	aliasXHtml = "<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title>{{ .Permalink }}</title><link rel=\"canonical\" href=\"{{ .Permalink }}\"/><meta name=\"robots\" content=\"noindex\"><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" /><meta http-equiv=\"refresh\" content=\"0; url={{ .Permalink }}\" /></head></html>"
    37  )
    38  
    39  var defaultAliasTemplates *template.Template
    40  
    41  func init() {
    42  	//TODO(bep) consolidate
    43  	defaultAliasTemplates = template.New("")
    44  	template.Must(defaultAliasTemplates.New("alias").Parse(alias))
    45  	template.Must(defaultAliasTemplates.New("alias-xhtml").Parse(aliasXHtml))
    46  }
    47  
    48  type aliasHandler struct {
    49  	t         tpl.TemplateFinder
    50  	log       *jww.Notepad
    51  	allowRoot bool
    52  }
    53  
    54  func newAliasHandler(t tpl.TemplateFinder, l *jww.Notepad, allowRoot bool) aliasHandler {
    55  	return aliasHandler{t, l, allowRoot}
    56  }
    57  
    58  func (a aliasHandler) renderAlias(isXHTML bool, permalink string, page *Page) (io.Reader, error) {
    59  	t := "alias"
    60  	if isXHTML {
    61  		t = "alias-xhtml"
    62  	}
    63  
    64  	var templ tpl.Template
    65  	var found bool
    66  
    67  	if a.t != nil {
    68  		templ, found = a.t.Lookup("alias.html")
    69  	}
    70  
    71  	if !found {
    72  		def := defaultAliasTemplates.Lookup(t)
    73  		if def != nil {
    74  			templ = &tpl.TemplateAdapter{Template: def}
    75  		}
    76  
    77  	}
    78  	data := struct {
    79  		Permalink string
    80  		Page      *Page
    81  	}{
    82  		permalink,
    83  		page,
    84  	}
    85  
    86  	buffer := new(bytes.Buffer)
    87  	err := templ.Execute(buffer, data)
    88  	if err != nil {
    89  		return nil, err
    90  	}
    91  	return buffer, nil
    92  }
    93  
    94  func (s *Site) writeDestAlias(path, permalink string, outputFormat output.Format, p *Page) (err error) {
    95  	return s.publishDestAlias(false, path, permalink, outputFormat, p)
    96  }
    97  
    98  func (s *Site) publishDestAlias(allowRoot bool, path, permalink string, outputFormat output.Format, p *Page) (err error) {
    99  	handler := newAliasHandler(s.Tmpl, s.Log, allowRoot)
   100  
   101  	isXHTML := strings.HasSuffix(path, ".xhtml")
   102  
   103  	s.Log.DEBUG.Println("creating alias:", path, "redirecting to", permalink)
   104  
   105  	targetPath, err := handler.targetPathAlias(path)
   106  	if err != nil {
   107  		return err
   108  	}
   109  
   110  	aliasContent, err := handler.renderAlias(isXHTML, permalink, p)
   111  	if err != nil {
   112  		return err
   113  	}
   114  
   115  	pd := publisher.Descriptor{
   116  		Src:          aliasContent,
   117  		TargetPath:   targetPath,
   118  		StatCounter:  &s.PathSpec.ProcessingStats.Aliases,
   119  		OutputFormat: outputFormat,
   120  	}
   121  
   122  	return s.publisher.Publish(pd)
   123  
   124  }
   125  
   126  func (a aliasHandler) targetPathAlias(src string) (string, error) {
   127  	originalAlias := src
   128  	if len(src) <= 0 {
   129  		return "", fmt.Errorf("Alias \"\" is an empty string")
   130  	}
   131  
   132  	alias := filepath.Clean(src)
   133  	components := strings.Split(alias, helpers.FilePathSeparator)
   134  
   135  	if !a.allowRoot && alias == helpers.FilePathSeparator {
   136  		return "", fmt.Errorf("Alias \"%s\" resolves to website root directory", originalAlias)
   137  	}
   138  
   139  	// Validate against directory traversal
   140  	if components[0] == ".." {
   141  		return "", fmt.Errorf("Alias \"%s\" traverses outside the website root directory", originalAlias)
   142  	}
   143  
   144  	// Handle Windows file and directory naming restrictions
   145  	// See "Naming Files, Paths, and Namespaces" on MSDN
   146  	// https://msdn.microsoft.com/en-us/library/aa365247%28v=VS.85%29.aspx?f=255&MSPPError=-2147217396
   147  	msgs := []string{}
   148  	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"}
   149  
   150  	if strings.ContainsAny(alias, ":*?\"<>|") {
   151  		msgs = append(msgs, fmt.Sprintf("Alias \"%s\" contains invalid characters on Windows: : * ? \" < > |", originalAlias))
   152  	}
   153  	for _, ch := range alias {
   154  		if ch < ' ' {
   155  			msgs = append(msgs, fmt.Sprintf("Alias \"%s\" contains ASCII control code (0x00 to 0x1F), invalid on Windows: : * ? \" < > |", originalAlias))
   156  			continue
   157  		}
   158  	}
   159  	for _, comp := range components {
   160  		if strings.HasSuffix(comp, " ") || strings.HasSuffix(comp, ".") {
   161  			msgs = append(msgs, fmt.Sprintf("Alias \"%s\" contains component with a trailing space or period, problematic on Windows", originalAlias))
   162  		}
   163  		for _, r := range reservedNames {
   164  			if comp == r {
   165  				msgs = append(msgs, fmt.Sprintf("Alias \"%s\" contains component with reserved name \"%s\" on Windows", originalAlias, r))
   166  			}
   167  		}
   168  	}
   169  	if len(msgs) > 0 {
   170  		if runtime.GOOS == "windows" {
   171  			for _, m := range msgs {
   172  				a.log.ERROR.Println(m)
   173  			}
   174  			return "", fmt.Errorf("Cannot create \"%s\": Windows filename restriction", originalAlias)
   175  		}
   176  		for _, m := range msgs {
   177  			a.log.WARN.Println(m)
   178  		}
   179  	}
   180  
   181  	// Add the final touch
   182  	alias = strings.TrimPrefix(alias, helpers.FilePathSeparator)
   183  	if strings.HasSuffix(alias, helpers.FilePathSeparator) {
   184  		alias = alias + "index.html"
   185  	} else if !strings.HasSuffix(alias, ".html") {
   186  		alias = alias + helpers.FilePathSeparator + "index.html"
   187  	}
   188  	if originalAlias != alias {
   189  		a.log.INFO.Printf("Alias \"%s\" translated to \"%s\"\n", originalAlias, alias)
   190  	}
   191  
   192  	return alias, nil
   193  }