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