Debian Codegraph @

commands/server.go

raw
1 // Copyright 2024 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 commands
15
16 import (
17 "bytes"
18 "context"
19 "crypto/tls"
20 "crypto/x509"
21 "encoding/json"
22 "encoding/pem"
23 "errors"
24 "fmt"
25 "io"
26 "maps"
27 "net"
28 "net/http"
29 _ "net/http/pprof"
30 "net/url"
31 "os"
32 "os/signal"
33 "path"
34 "path/filepath"
35 "regexp"
36 "sort"
37 "strconv"
38 "strings"
39 "sync"
40 "sync/atomic"
41 "syscall"
42 "time"
43
44 "github.com/bep/mclib"
45 "github.com/pkg/browser"
46
47 "github.com/bep/debounce"
48 "github.com/bep/simplecobra"
49 "github.com/fsnotify/fsnotify"
50 "github.com/gohugoio/hugo/common/herrors"
51 "github.com/gohugoio/hugo/common/hugo"
52 "github.com/gohugoio/hugo/common/paths"
53 "github.com/gohugoio/hugo/langs"
54 "github.com/gohugoio/hugo/tpl/tplimpl"
55
56 "github.com/gohugoio/hugo/common/types"
57 "github.com/gohugoio/hugo/common/urls"
58 "github.com/gohugoio/hugo/config"
59 "github.com/gohugoio/hugo/helpers"
60 "github.com/gohugoio/hugo/hugofs"
61 "github.com/gohugoio/hugo/hugolib"
62 "github.com/gohugoio/hugo/hugolib/filesystems"
63 "github.com/gohugoio/hugo/livereload"
64 "github.com/gohugoio/hugo/transform"
65 "github.com/gohugoio/hugo/transform/livereloadinject"
66 "github.com/spf13/afero"
67 "github.com/spf13/cobra"
68 "github.com/spf13/fsync"
69 "golang.org/x/sync/errgroup"
70 "golang.org/x/sync/semaphore"
71 )
72
73 var (
74 logDuplicateTemplateExecuteRe = regexp.MustCompile(`: template: .*?:\d+:\d+: executing ".*?"`)
75 logDuplicateTemplateParseRe = regexp.MustCompile(`: template: .*?:\d+:\d*`)
76 )
77
78 var logReplacer = strings.NewReplacer(
79 "can't", "can’t", // Chroma lexer doesn't do well with "can't"
80 "*hugolib.pageState", "page.Page", // Page is the public interface.
81 "Rebuild failed:", "",
82 )
83
84 const (
85 configChangeConfig = "config file"
86 configChangeGoMod = "go.mod file"
87 configChangeGoWork = "go work file"
88 )
89
90 const (
91 hugoHeaderRedirect = "X-Hugo-Redirect"
92 )
93
94 func newHugoBuilder(r *rootCommand, s *serverCommand, onConfigLoaded ...func(reloaded bool) error) *hugoBuilder {
95 var visitedURLs *types.EvictingQueue[string]
96 if s != nil && !s.disableFastRender {
97 visitedURLs = types.NewEvictingQueue[string](20)
98 }
99 return &hugoBuilder{
100 r: r,
101 s: s,
102 visitedURLs: visitedURLs,
103 fullRebuildSem: semaphore.NewWeighted(1),
104 debounce: debounce.New(4 * time.Second),
105 onConfigLoaded: func(reloaded bool) error {
106 for _, wc := range onConfigLoaded {
107 if err := wc(reloaded); err != nil {
108 return err
109 }
110 }
111 return nil
112 },
113 }
114 }
115
116 func newServerCommand() *serverCommand {
117 // Flags.
118 var uninstall bool
119
120 c := &serverCommand{
121 quit: make(chan bool),
122 commands: []simplecobra.Commander{
123 &simpleCommand{
124 name: "trust",
125 short: "Install the local CA in the system trust store",
126 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
127 action := "-install"
128 if uninstall {
129 action = "-uninstall"
130 }
131 os.Args = []string{action}
132 return mclib.RunMain()
133 },
134 withc: func(cmd *cobra.Command, r *rootCommand) {
135 cmd.ValidArgsFunction = cobra.NoFileCompletions
136 cmd.Flags().BoolVar(&uninstall, "uninstall", false, "Uninstall the local CA (but do not delete it).")
137 },
138 },
139 },
140 }
141
142 return c
143 }
144
145 func (c *serverCommand) Commands() []simplecobra.Commander {
146 return c.commands
147 }
148
149 type countingStatFs struct {
150 afero.Fs
151 statCounter uint64
152 }
153
154 func (fs *countingStatFs) Stat(name string) (os.FileInfo, error) {
155 f, err := fs.Fs.Stat(name)
156 if err == nil {
157 if !f.IsDir() {
158 atomic.AddUint64(&fs.statCounter, 1)
159 }
160 }
161 return f, err
162 }
163
164 // dynamicEvents contains events that is considered dynamic, as in "not static".
165 // Both of these categories will trigger a new build, but the asset events
166 // does not fit into the "navigate to changed" logic.
167 type dynamicEvents struct {
168 ContentEvents []fsnotify.Event
169 AssetEvents []fsnotify.Event
170 }
171
172 type fileChangeDetector struct {
173 sync.Mutex
174 current map[string]uint64
175 prev map[string]uint64
176
177 irrelevantRe *regexp.Regexp
178 }
179
180 func (f *fileChangeDetector) OnFileClose(name string, checksum uint64) {
181 f.Lock()
182 defer f.Unlock()
183 f.current[name] = checksum
184 }
185
186 func (f *fileChangeDetector) PrepareNew() {
187 if f == nil {
188 return
189 }
190
191 f.Lock()
192 defer f.Unlock()
193
194 if f.current == nil {
195 f.current = make(map[string]uint64)
196 f.prev = make(map[string]uint64)
197 return
198 }
199
200 f.prev = make(map[string]uint64)
201 maps.Copy(f.prev, f.current)
202 f.current = make(map[string]uint64)
203 }
204
205 func (f *fileChangeDetector) changed() []string {
206 if f == nil {
207 return nil
208 }
209 f.Lock()
210 defer f.Unlock()
211 var c []string
212 for k, v := range f.current {
213 vv, found := f.prev[k]
214 if !found || v != vv {
215 c = append(c, k)
216 }
217 }
218
219 return f.filterIrrelevantAndSort(c)
220 }
221
222 func (f *fileChangeDetector) filterIrrelevantAndSort(in []string) []string {
223 var filtered []string
224 for _, v := range in {
225 if !f.irrelevantRe.MatchString(v) {
226 filtered = append(filtered, v)
227 }
228 }
229 sort.Strings(filtered)
230 return filtered
231 }
232
233 type fileServer struct {
234 baseURLs []urls.BaseURL
235 roots []string
236 errorTemplate func(err any) (io.Reader, error)
237 c *serverCommand
238 }
239
240 func (f *fileServer) createEndpoint(i int) (*http.ServeMux, net.Listener, string, string, error) {
241 r := f.c.r
242 baseURL := f.baseURLs[i]
243 root := f.roots[i]
244 port := f.c.serverPorts[i].p
245 listener := f.c.serverPorts[i].ln
246 logger := f.c.r.logger
247
248 if i == 0 {
249 r.Printf("Environment: %q\n", f.c.hugoTry().Deps.Site.Hugo().Environment())
250 mainTarget := "disk"
251 if f.c.r.renderToMemory {
252 mainTarget = "memory"
253 }
254 if f.c.renderStaticToDisk {
255 r.Printf("Serving pages from %s and static files from disk\n", mainTarget)
256 } else {
257 r.Printf("Serving pages from %s\n", mainTarget)
258 }
259 }
260
261 var httpFs *afero.HttpFs
262 f.c.withConf(func(conf *commonConfig) {
263 httpFs = afero.NewHttpFs(conf.fs.PublishDirServer)
264 })
265
266 fs := filesOnlyFs{httpFs.Dir(path.Join("/", root))}
267 if i == 0 && f.c.fastRenderMode {
268 r.Println("Running in Fast Render Mode. For full rebuilds on change: hugo server --disableFastRender")
269 }
270
271 decorate := func(h http.Handler) http.Handler {
272 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
273 if f.c.showErrorInBrowser {
274 // First check the error state
275 err := f.c.getErrorWithContext()
276 if err != nil {
277 f.c.errState.setWasErr(true)
278 w.WriteHeader(500)
279 r, err := f.errorTemplate(err)
280 if err != nil {
281 logger.Errorln(err)
282 }
283
284 port = 1313
285 f.c.withConfOrOldConf(func(conf *commonConfig) {
286 if lrport := conf.configs.GetFirstLanguageConfig().BaseURLLiveReload().Port(); lrport != 0 {
287 port = lrport
288 }
289 })
290 lr := baseURL.URL()
291 lr.Host = fmt.Sprintf("%s:%d", lr.Hostname(), port)
292 fmt.Fprint(w, injectLiveReloadScript(r, lr))
293
294 return
295 }
296 }
297
298 if f.c.noHTTPCache {
299 w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
300 w.Header().Set("Pragma", "no-cache")
301 }
302
303 var serverConfig config.Server
304 f.c.withConf(func(conf *commonConfig) {
305 serverConfig = conf.configs.Base.Server
306 })
307
308 // Ignore any query params for the operations below.
309 requestURI, _ := url.PathUnescape(strings.TrimSuffix(r.RequestURI, "?"+r.URL.RawQuery))
310
311 for _, header := range serverConfig.MatchHeaders(requestURI) {
312 w.Header().Set(header.Key, header.Value)
313 }
314
315 if canRedirect(requestURI, r) {
316 if redirect := serverConfig.MatchRedirect(requestURI, r.Header); !redirect.IsZero() {
317 doRedirect := true
318 // This matches Netlify's behavior and is needed for SPA behavior.
319 // See https://docs.netlify.com/routing/redirects/rewrites-proxies/
320 if !redirect.Force {
321 path := filepath.Clean(strings.TrimPrefix(requestURI, baseURL.Path()))
322 if root != "" {
323 path = filepath.Join(root, path)
324 }
325 var fs afero.Fs
326 f.c.withConf(func(conf *commonConfig) {
327 fs = conf.fs.PublishDirServer
328 })
329
330 fi, err := fs.Stat(path)
331
332 if err == nil {
333 if fi.IsDir() {
334 // There will be overlapping directories, so we
335 // need to check for a file.
336 _, err = fs.Stat(filepath.Join(path, "index.html"))
337 doRedirect = err != nil
338 } else {
339 doRedirect = false
340 }
341 }
342 }
343
344 if doRedirect {
345 w.Header().Set(hugoHeaderRedirect, "true")
346 switch redirect.Status {
347 case 404:
348 w.WriteHeader(404)
349 file, err := fs.Open(strings.TrimPrefix(redirect.To, baseURL.Path()))
350 if err == nil {
351 defer file.Close()
352 io.Copy(w, file)
353 } else {
354 fmt.Fprintln(w, "<h1>Page Not Found</h1>")
355 }
356 return
357 case 200:
358 if r2 := f.rewriteRequest(r, strings.TrimPrefix(redirect.To, baseURL.Path())); r2 != nil {
359 requestURI = redirect.To
360 r = r2
361 }
362 default:
363 w.Header().Set("Content-Type", "")
364 http.Redirect(w, r, redirect.To, redirect.Status)
365 return
366
367 }
368 }
369 }
370 }
371
372 if f.c.fastRenderMode && f.c.errState.buildErr() == nil {
373 if isNavigation(requestURI, r) {
374 // See issue 14240.
375 // Hugo escapes the URL paths when generating them,
376 // that may not be the case when we receive it back from the browser.
377 // PathEscape will escape if it is not already escaped.
378 requestURI = paths.PathEscape(requestURI)
379
380 if !f.c.visitedURLs.Contains(requestURI) {
381 // If not already on stack, re-render that single page.
382 if err := f.c.partialReRender(requestURI); err != nil {
383 f.c.handleBuildErr(err, fmt.Sprintf("Failed to render %q", requestURI))
384 if f.c.showErrorInBrowser {
385 http.Redirect(w, r, requestURI, http.StatusMovedPermanently)
386 return
387 }
388 }
389 }
390
391 f.c.visitedURLs.Add(requestURI)
392
393 }
394 }
395
396 h.ServeHTTP(w, r)
397 })
398 }
399
400 fileserver := decorate(http.FileServer(fs))
401 mu := http.NewServeMux()
402 if baseURL.Path() == "" || baseURL.Path() == "/" {
403 mu.Handle("/", fileserver)
404 } else {
405 mu.Handle(baseURL.Path(), http.StripPrefix(baseURL.Path(), fileserver))
406 }
407 if r.IsTestRun() {
408 var shutDownOnce sync.Once
409 mu.HandleFunc("/__stop", func(w http.ResponseWriter, r *http.Request) {
410 shutDownOnce.Do(func() {
411 close(f.c.quit)
412 })
413 })
414 }
415
416 endpoint := net.JoinHostPort(f.c.serverInterface, strconv.Itoa(port))
417
418 return mu, listener, baseURL.String(), endpoint, nil
419 }
420
421 func (f *fileServer) rewriteRequest(r *http.Request, toPath string) *http.Request {
422 r2 := new(http.Request)
423 *r2 = *r
424 r2.URL = new(url.URL)
425 *r2.URL = *r.URL
426 r2.URL.Path = toPath
427 r2.Header.Set("X-Rewrite-Original-URI", r.URL.RequestURI())
428
429 return r2
430 }
431
432 type filesOnlyFs struct {
433 fs http.FileSystem
434 }
435
436 func (fs filesOnlyFs) Open(name string) (http.File, error) {
437 f, err := fs.fs.Open(name)
438 if err != nil {
439 return nil, err
440 }
441 return noDirFile{f}, nil
442 }
443
444 type noDirFile struct {
445 http.File
446 }
447
448 func (f noDirFile) Readdir(count int) ([]os.FileInfo, error) {
449 return nil, nil
450 }
451
452 type serverCommand struct {
453 r *rootCommand
454
455 commands []simplecobra.Commander
456
457 *hugoBuilder
458
459 quit chan bool // Closed when the server should shut down. Used in tests only.
460 serverPorts []serverPortListener
461 doLiveReload bool
462
463 // Flags.
464 renderStaticToDisk bool
465 navigateToChanged bool
466 openBrowser bool
467 serverAppend bool
468 serverInterface string
469 tlsCertFile string
470 tlsKeyFile string
471 tlsAuto bool
472 pprof bool
473 serverPort int
474 liveReloadPort int
475 serverWatch bool
476 noHTTPCache bool
477 disableLiveReload bool
478 disableFastRender bool
479 disableBrowserError bool
480 }
481
482 func (c *serverCommand) Name() string {
483 return "server"
484 }
485
486 func (c *serverCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
487 if c.pprof {
488 go func() {
489 http.ListenAndServe("localhost:8080", nil)
490 }()
491 }
492 // Watch runs its own server as part of the routine
493 if c.serverWatch {
494
495 watchDirs, err := c.getDirList()
496 if err != nil {
497 return err
498 }
499
500 watchGroups := helpers.ExtractAndGroupRootPaths(watchDirs)
501
502 c.r.Printf("Watching for changes in %s\n", strings.Join(watchGroups, ", "))
503 watcher, err := c.newWatcher(c.r.poll, watchDirs...)
504 if err != nil {
505 return err
506 }
507
508 defer watcher.Close()
509
510 }
511
512 err := func() error {
513 defer c.r.timeTrack(time.Now(), "Built")
514 return c.build()
515 }()
516 if err != nil {
517 return err
518 }
519
520 return c.serve()
521 }
522
523 func (c *serverCommand) Init(cd *simplecobra.Commandeer) error {
524 cmd := cd.CobraCommand
525 cmd.Short = "Start the embedded web server"
526 cmd.Long = `Hugo provides its own webserver which builds and serves the project.
527 While hugo server is high performance, it is a webserver with limited options.
528
529 The ` + "`" + `hugo server` + "`" + ` command will by default write and serve files from disk, but
530 you can render to memory by using the ` + "`" + `--renderToMemory` + "`" + ` flag. This can be
531 faster in some cases, but it will consume more memory.
532
533 By default hugo will also watch your files for any changes you make and
534 automatically rebuild the project. It will then live reload any open browser pages
535 and push the latest content to them. As most Hugo projects are built in a fraction
536 of a second, you will be able to save and see your changes nearly instantly.`
537 cmd.Aliases = []string{"serve"}
538
539 cmd.Flags().IntVarP(&c.serverPort, "port", "p", 1313, "port on which the server will listen")
540 _ = cmd.RegisterFlagCompletionFunc("port", cobra.NoFileCompletions)
541 cmd.Flags().IntVar(&c.liveReloadPort, "liveReloadPort", -1, "port for live reloading (i.e. 443 in HTTPS proxy situations)")
542 _ = cmd.RegisterFlagCompletionFunc("liveReloadPort", cobra.NoFileCompletions)
543 cmd.Flags().StringVarP(&c.serverInterface, "bind", "", "127.0.0.1", "interface to which the server will bind")
544 _ = cmd.RegisterFlagCompletionFunc("bind", cobra.NoFileCompletions)
545 cmd.Flags().StringVarP(&c.tlsCertFile, "tlsCertFile", "", "", "path to TLS certificate file")
546 _ = cmd.MarkFlagFilename("tlsCertFile", "pem")
547 cmd.Flags().StringVarP(&c.tlsKeyFile, "tlsKeyFile", "", "", "path to TLS key file")
548 _ = cmd.MarkFlagFilename("tlsKeyFile", "pem")
549 cmd.Flags().BoolVar(&c.tlsAuto, "tlsAuto", false, "generate and use locally-trusted certificates.")
550 cmd.Flags().BoolVar(&c.pprof, "pprof", false, "enable the pprof server (port 8080)")
551 cmd.Flags().BoolVarP(&c.serverWatch, "watch", "w", true, "watch filesystem for changes and recreate as needed")
552 cmd.Flags().BoolVar(&c.noHTTPCache, "noHTTPCache", false, "disable browser caching of pages served by the embedded web server")
553 cmd.Flags().BoolVarP(&c.serverAppend, "appendPort", "", true, "append port to baseURL")
554 cmd.Flags().BoolVar(&c.disableLiveReload, "disableLiveReload", false, "watch without enabling live browser reload on rebuild")
555 cmd.Flags().BoolVarP(&c.navigateToChanged, "navigateToChanged", "N", false, "navigate to changed content file on live browser reload")
556 cmd.Flags().BoolVarP(&c.openBrowser, "openBrowser", "O", false, "open the project in a browser after server startup")
557 cmd.Flags().BoolVar(&c.renderStaticToDisk, "renderStaticToDisk", false, "serve static files from disk and dynamic files from memory")
558 cmd.Flags().BoolVar(&c.disableFastRender, "disableFastRender", false, "enables full re-renders on changes")
559 cmd.Flags().BoolVar(&c.disableBrowserError, "disableBrowserError", false, "do not show build errors in the browser")
560
561 r := cd.Root.Command.(*rootCommand)
562 applyLocalFlagsBuild(cmd, r)
563
564 return nil
565 }
566
567 func (c *serverCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
568 c.r = cd.Root.Command.(*rootCommand)
569
570 c.hugoBuilder = newHugoBuilder(
571 c.r,
572 c,
573 func(reloaded bool) error {
574 if !reloaded {
575 if err := c.createServerPorts(cd); err != nil {
576 return err
577 }
578
579 if (c.tlsCertFile == "" || c.tlsKeyFile == "") && c.tlsAuto {
580 c.withConfE(func(conf *commonConfig) error {
581 return c.createCertificates(conf)
582 })
583 }
584 }
585
586 if err := c.setServerInfoInConfig(); err != nil {
587 return err
588 }
589
590 if !reloaded && c.fastRenderMode {
591 c.withConf(func(conf *commonConfig) {
592 conf.fs.PublishDir = hugofs.NewHashingFs(conf.fs.PublishDir, c.changeDetector)
593 conf.fs.PublishDirStatic = hugofs.NewHashingFs(conf.fs.PublishDirStatic, c.changeDetector)
594 })
595 }
596
597 return nil
598 },
599 )
600
601 destinationFlag := cd.CobraCommand.Flags().Lookup("destination")
602 if c.r.renderToMemory && (destinationFlag != nil && destinationFlag.Changed) {
603 return fmt.Errorf("cannot use --renderToMemory with --destination")
604 }
605 c.doLiveReload = !c.disableLiveReload
606 c.fastRenderMode = !c.disableFastRender
607 c.showErrorInBrowser = c.doLiveReload && !c.disableBrowserError
608
609 if c.fastRenderMode {
610 // For now, fast render mode only. It should, however, be fast enough
611 // for the full variant, too.
612 c.changeDetector = &fileChangeDetector{
613 // We use this detector to decide to do a Hot reload of a single path or not.
614 // We need to filter out source maps and possibly some other to be able
615 // to make that decision.
616 irrelevantRe: regexp.MustCompile(`\.map$`),
617 }
618
619 c.changeDetector.PrepareNew()
620
621 }
622
623 err := c.loadConfig(cd, true)
624 if err != nil {
625 return err
626 }
627
628 return nil
629 }
630
631 func (c *serverCommand) setServerInfoInConfig() error {
632 if len(c.serverPorts) == 0 {
633 panic("no server ports set")
634 }
635 return c.withConfE(func(conf *commonConfig) error {
636 for i, language := range conf.configs.Languages {
637 isMultihost := conf.configs.IsMultihost
638 var serverPort int
639 if isMultihost {
640 serverPort = c.serverPorts[i].p
641 } else {
642 serverPort = c.serverPorts[0].p
643 }
644 langConfig := conf.configs.LanguageConfigMap[language.Lang]
645 baseURLStr, err := c.fixURL(langConfig.BaseURL, c.r.baseURL, serverPort)
646 if err != nil {
647 return err
648 }
649 baseURL, err := urls.NewBaseURLFromString(baseURLStr)
650 if err != nil {
651 return fmt.Errorf("failed to create baseURL from %q: %s", baseURLStr, err)
652 }
653
654 baseURLLiveReload := baseURL
655 if c.liveReloadPort != -1 {
656 baseURLLiveReload, _ = baseURLLiveReload.WithPort(c.liveReloadPort)
657 }
658 langConfig.C.SetServerInfo(baseURL, baseURLLiveReload, c.serverInterface)
659
660 }
661 return nil
662 })
663 }
664
665 func (c *serverCommand) getErrorWithContext() any {
666 buildErr := c.errState.buildErr()
667 if buildErr == nil {
668 return nil
669 }
670
671 m := make(map[string]any)
672
673 m["Error"] = cleanErrorLog(c.r.logger.Errors())
674
675 m["Version"] = hugo.BuildVersionString()
676 ferrors := herrors.UnwrapFileErrorsWithErrorContext(buildErr)
677 m["Files"] = ferrors
678
679 return m
680 }
681
682 func (c *serverCommand) createCertificates(conf *commonConfig) error {
683 hostname := "localhost"
684 if c.r.baseURL != "" {
685 u, err := url.Parse(c.r.baseURL)
686 if err != nil {
687 return err
688 }
689 hostname = u.Hostname()
690 }
691
692 // For now, store these in the Hugo cache dir.
693 // Hugo should probably introduce some concept of a less temporary application directory.
694 keyDir := filepath.Join(conf.configs.LoadingInfo.BaseConfig.CacheDir, "_mkcerts")
695
696 // Create the directory if it doesn't exist.
697 if _, err := os.Stat(keyDir); os.IsNotExist(err) {
698 if err := os.MkdirAll(keyDir, 0o777); err != nil {
699 return err
700 }
701 }
702
703 c.tlsCertFile = filepath.Join(keyDir, fmt.Sprintf("%s.pem", hostname))
704 c.tlsKeyFile = filepath.Join(keyDir, fmt.Sprintf("%s-key.pem", hostname))
705
706 // Check if the certificate already exists and is valid.
707 certPEM, err := os.ReadFile(c.tlsCertFile)
708 if err == nil {
709 rootPem, err := os.ReadFile(filepath.Join(mclib.GetCAROOT(), "rootCA.pem"))
710 if err == nil {
711 if err := c.verifyCert(rootPem, certPEM, hostname); err == nil {
712 c.r.Println("Using existing", c.tlsCertFile, "and", c.tlsKeyFile)
713 return nil
714 }
715 }
716 }
717
718 c.r.Println("Creating TLS certificates in", keyDir)
719
720 // Yes, this is unfortunate, but it's currently the only way to use Mkcert as a library.
721 os.Args = []string{"-cert-file", c.tlsCertFile, "-key-file", c.tlsKeyFile, hostname}
722 return mclib.RunMain()
723 }
724
725 func (c *serverCommand) verifyCert(rootPEM, certPEM []byte, name string) error {
726 roots := x509.NewCertPool()
727 ok := roots.AppendCertsFromPEM(rootPEM)
728 if !ok {
729 return fmt.Errorf("failed to parse root certificate")
730 }
731
732 block, _ := pem.Decode(certPEM)
733 if block == nil {
734 return fmt.Errorf("failed to parse certificate PEM")
735 }
736 cert, err := x509.ParseCertificate(block.Bytes)
737 if err != nil {
738 return fmt.Errorf("failed to parse certificate: %v", err.Error())
739 }
740
741 opts := x509.VerifyOptions{
742 DNSName: name,
743 Roots: roots,
744 }
745
746 if _, err := cert.Verify(opts); err != nil {
747 return fmt.Errorf("failed to verify certificate: %v", err.Error())
748 }
749
750 return nil
751 }
752
753 func (c *serverCommand) createServerPorts(cd *simplecobra.Commandeer) error {
754 flags := cd.CobraCommand.Flags()
755 var cerr error
756 c.withConf(func(conf *commonConfig) {
757 isMultihost := conf.configs.IsMultihost
758 c.serverPorts = make([]serverPortListener, 1)
759 if isMultihost {
760 if !c.serverAppend {
761 cerr = errors.New("--appendPort=false not supported when in multihost mode")
762 return
763 }
764 c.serverPorts = make([]serverPortListener, len(conf.configs.Languages))
765 }
766 currentServerPort := c.serverPort
767 for i := range c.serverPorts {
768 l, err := net.Listen("tcp", net.JoinHostPort(c.serverInterface, strconv.Itoa(currentServerPort)))
769 if err == nil {
770 c.serverPorts[i] = serverPortListener{ln: l, p: currentServerPort}
771 } else {
772 if i == 0 && flags.Changed("port") {
773 // port set explicitly by user -- he/she probably meant it!
774 cerr = fmt.Errorf("server startup failed: %s", err)
775 return
776 }
777 c.r.Println("port", currentServerPort, "already in use, attempting to use an available port")
778 l, sp, err := helpers.TCPListen()
779 if err != nil {
780 cerr = fmt.Errorf("unable to find alternative port to use: %s", err)
781 return
782 }
783 c.serverPorts[i] = serverPortListener{ln: l, p: sp.Port}
784 }
785
786 currentServerPort = c.serverPorts[i].p + 1
787 }
788 })
789
790 return cerr
791 }
792
793 // fixURL massages the baseURL into a form needed for serving
794 // all pages correctly.
795 func (c *serverCommand) fixURL(baseURLFromConfig, baseURLFromFlag string, port int) (string, error) {
796 certsSet := (c.tlsCertFile != "" && c.tlsKeyFile != "") || c.tlsAuto
797 useLocalhost := false
798 baseURL := baseURLFromFlag
799 if baseURL == "" {
800 baseURL = baseURLFromConfig
801 useLocalhost = true
802 }
803
804 if !strings.HasSuffix(baseURL, "/") {
805 baseURL = baseURL + "/"
806 }
807
808 // do an initial parse of the input string
809 u, err := url.Parse(baseURL)
810 if err != nil {
811 return "", err
812 }
813
814 // if no Host is defined, then assume that no schema or double-slash were
815 // present in the url. Add a double-slash and make a best effort attempt.
816 if u.Host == "" && baseURL != "/" {
817 baseURL = "//" + baseURL
818
819 u, err = url.Parse(baseURL)
820 if err != nil {
821 return "", err
822 }
823 }
824
825 if useLocalhost {
826 if certsSet {
827 u.Scheme = "https"
828 } else if u.Scheme == "https" {
829 u.Scheme = "http"
830 }
831 u.Host = "localhost"
832 }
833
834 if c.serverAppend {
835 if strings.Contains(u.Host, ":") {
836 u.Host, _, err = net.SplitHostPort(u.Host)
837 if err != nil {
838 return "", fmt.Errorf("failed to split baseURL hostport: %w", err)
839 }
840 }
841 u.Host += fmt.Sprintf(":%d", port)
842 }
843
844 return u.String(), nil
845 }
846
847 func (c *serverCommand) partialReRender(urls ...string) (err error) {
848 defer func() {
849 c.errState.setWasErr(false)
850 }()
851 visited := types.NewEvictingQueue[string](len(urls))
852 for _, url := range urls {
853 visited.Add(url)
854 }
855
856 var h *hugolib.HugoSites
857 h, err = c.hugo()
858 if err != nil {
859 return
860 }
861
862 // Note: We do not set NoBuildLock as the file lock is not acquired at this stage.
863 err = h.Build(hugolib.BuildCfg{NoBuildLock: false, RecentlyTouched: visited, PartialReRender: true, ErrRecovery: c.errState.wasErr()})
864
865 return
866 }
867
868 func (c *serverCommand) serve() error {
869 var (
870 baseURLs []urls.BaseURL
871 roots []string
872 h *hugolib.HugoSites
873 )
874 err := c.withConfE(func(conf *commonConfig) error {
875 isMultihost := conf.configs.IsMultihost
876 var err error
877 h, err = c.r.HugFromConfig(conf)
878 if err != nil {
879 return err
880 }
881
882 // We need the server to share the same logger as the Hugo build (for error counts etc.)
883 c.r.logger = h.Log
884
885 if isMultihost {
886 for _, l := range conf.configs.ConfigLangs() {
887 baseURLs = append(baseURLs, l.BaseURL())
888 roots = append(roots, l.Language().(*langs.Language).Lang)
889 }
890 } else {
891 l := conf.configs.GetFirstLanguageConfig()
892 baseURLs = []urls.BaseURL{l.BaseURL()}
893 roots = []string{""}
894 }
895
896 return nil
897 })
898 if err != nil {
899 return err
900 }
901
902 // Cache it here. The HugoSites object may be unavailable later on due to intermittent configuration errors.
903 // To allow the en user to change the error template while the server is running, we use
904 // the freshest template we can provide.
905 var (
906 errTempl *tplimpl.TemplInfo
907 templHandler *tplimpl.TemplateStore
908 )
909 getErrorTemplateAndHandler := func(h *hugolib.HugoSites) (*tplimpl.TemplInfo, *tplimpl.TemplateStore) {
910 if h == nil {
911 return errTempl, templHandler
912 }
913 templHandler := h.GetTemplateStore()
914 errTempl := templHandler.LookupByPath("/_server/error.html")
915 if errTempl == nil {
916 panic("template server/error.html not found")
917 }
918 return errTempl, templHandler
919 }
920 errTempl, templHandler = getErrorTemplateAndHandler(h)
921
922 srv := &fileServer{
923 baseURLs: baseURLs,
924 roots: roots,
925 c: c,
926 errorTemplate: func(ctx any) (io.Reader, error) {
927 // hugoTry does not block, getErrorTemplateAndHandler will fall back
928 // to cached values if nil.
929 templ, handler := getErrorTemplateAndHandler(c.hugoTry())
930 b := &bytes.Buffer{}
931 err := handler.ExecuteWithContext(context.Background(), templ, b, ctx)
932 return b, err
933 },
934 }
935
936 doLiveReload := !c.disableLiveReload
937
938 if doLiveReload {
939 livereload.Initialize()
940 }
941
942 sigs := make(chan os.Signal, 1)
943 signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
944 var servers []*http.Server
945
946 wg1, ctx := errgroup.WithContext(context.Background())
947
948 for i := range baseURLs {
949 mu, listener, serverURL, endpoint, err := srv.createEndpoint(i)
950 var srv *http.Server
951 if c.tlsCertFile != "" && c.tlsKeyFile != "" {
952 srv = &http.Server{
953 Addr: endpoint,
954 Handler: mu,
955 TLSConfig: &tls.Config{
956 MinVersion: tls.VersionTLS12,
957 },
958 }
959 } else {
960 srv = &http.Server{
961 Addr: endpoint,
962 Handler: mu,
963 }
964 }
965
966 servers = append(servers, srv)
967
968 if doLiveReload {
969 baseURL := baseURLs[i]
970 mu.HandleFunc(baseURL.Path()+"livereload.js", livereload.ServeJS)
971 mu.HandleFunc(baseURL.Path()+"livereload", livereload.Handler)
972 }
973 c.r.Printf("Web Server is available at %s (bind address %s) %s\n", serverURL, c.serverInterface, roots[i])
974 wg1.Go(func() error {
975 if c.tlsCertFile != "" && c.tlsKeyFile != "" {
976 err = srv.ServeTLS(listener, c.tlsCertFile, c.tlsKeyFile)
977 } else {
978 err = srv.Serve(listener)
979 }
980 if err != nil && err != http.ErrServerClosed {
981 return err
982 }
983 return nil
984 })
985 }
986
987 if c.r.IsTestRun() {
988 // Write a .ready file to disk to signal ready status.
989 // This is where the test is run from.
990 var baseURLs []string
991 for _, baseURL := range srv.baseURLs {
992 baseURLs = append(baseURLs, baseURL.String())
993 }
994 testInfo := map[string]any{
995 "baseURLs": baseURLs,
996 }
997
998 dir := os.Getenv("WORK")
999 if dir != "" {
1000 readyFile := filepath.Join(dir, ".ready")
1001 // encode the test info as JSON into the .ready file.
1002 b, err := json.Marshal(testInfo)
1003 if err != nil {
1004 return err
1005 }
1006 err = os.WriteFile(readyFile, b, 0o777)
1007 if err != nil {
1008 return err
1009 }
1010 }
1011
1012 }
1013
1014 c.r.Println("Press Ctrl+C to stop")
1015
1016 if c.openBrowser {
1017 // There may be more than one baseURL in multihost mode, open the first.
1018 if err := browser.OpenURL(baseURLs[0].String()); err != nil {
1019 c.r.logger.Warnf("Failed to open browser: %s", err)
1020 }
1021 }
1022
1023 err = func() error {
1024 for {
1025 select {
1026 case <-c.quit:
1027 return nil
1028 case <-sigs:
1029 return nil
1030 case <-ctx.Done():
1031 return ctx.Err()
1032 }
1033 }
1034 }()
1035 if err != nil {
1036 c.r.Println("Error:", err)
1037 }
1038
1039 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
1040 defer cancel()
1041 wg2, ctx := errgroup.WithContext(ctx)
1042 for _, srv := range servers {
1043 wg2.Go(func() error {
1044 return srv.Shutdown(ctx)
1045 })
1046 }
1047
1048 err1, err2 := wg1.Wait(), wg2.Wait()
1049 if err1 != nil {
1050 return err1
1051 }
1052 return err2
1053 }
1054
1055 type serverPortListener struct {
1056 p int
1057 ln net.Listener
1058 }
1059
1060 type staticSyncer struct {
1061 c *hugoBuilder
1062 }
1063
1064 func (s *staticSyncer) isStatic(h *hugolib.HugoSites, filename string) bool {
1065 return h.BaseFs.SourceFilesystems.IsStatic(filename)
1066 }
1067
1068 func (s *staticSyncer) syncsStaticEvents(staticEvents []fsnotify.Event) error {
1069 c := s.c
1070
1071 syncFn := func(sourceFs *filesystems.SourceFilesystem) (uint64, error) {
1072 publishDir := helpers.FilePathSeparator
1073
1074 if sourceFs.PublishFolder != "" {
1075 publishDir = filepath.Join(publishDir, sourceFs.PublishFolder)
1076 }
1077
1078 syncer := fsync.NewSyncer()
1079 c.withConf(func(conf *commonConfig) {
1080 syncer.NoTimes = conf.configs.Base.NoTimes
1081 syncer.NoChmod = conf.configs.Base.NoChmod
1082 syncer.ChmodFilter = chmodFilter
1083 syncer.SrcFs = sourceFs.Fs
1084 syncer.DestFs = conf.fs.PublishDir
1085 if c.s != nil && c.s.renderStaticToDisk {
1086 syncer.DestFs = conf.fs.PublishDirStatic
1087 }
1088 })
1089
1090 logger := s.c.r.logger
1091
1092 for _, ev := range staticEvents {
1093 // Due to our approach of layering both directories and the content's rendered output
1094 // into one we can't accurately remove a file not in one of the source directories.
1095 // If a file is in the local static dir and also in the theme static dir and we remove
1096 // it from one of those locations we expect it to still exist in the destination
1097 //
1098 // If Hugo generates a file (from the content dir) over a static file
1099 // the content generated file should take precedence.
1100 //
1101 // Because we are now watching and handling individual events it is possible that a static
1102 // event that occupies the same path as a content generated file will take precedence
1103 // until a regeneration of the content takes places.
1104 //
1105 // Hugo assumes that these cases are very rare and will permit this bad behavior
1106 // The alternative is to track every single file and which pipeline rendered it
1107 // and then to handle conflict resolution on every event.
1108
1109 fromPath := ev.Name
1110
1111 relPath, found := sourceFs.MakePathRelative(fromPath, false)
1112
1113 if !found {
1114 // Not member of this virtual host.
1115 continue
1116 }
1117
1118 // Remove || rename is harder and will require an assumption.
1119 // Hugo takes the following approach:
1120 // If the static file exists in any of the static source directories after this event
1121 // Hugo will re-sync it.
1122 // If it does not exist in all of the static directories Hugo will remove it.
1123 //
1124 // This assumes that Hugo has not generated content on top of a static file and then removed
1125 // the source of that static file. In this case Hugo will incorrectly remove that file
1126 // from the published directory.
1127 if ev.Op&fsnotify.Rename == fsnotify.Rename || ev.Op&fsnotify.Remove == fsnotify.Remove {
1128 if _, err := sourceFs.Fs.Stat(relPath); herrors.IsNotExist(err) {
1129 // If file doesn't exist in any static dir, remove it
1130 logger.Println("File no longer exists in static dir, removing", relPath)
1131 c.withConf(func(conf *commonConfig) {
1132 _ = conf.fs.PublishDirStatic.RemoveAll(relPath)
1133 })
1134
1135 } else if err == nil {
1136 // If file still exists, sync it
1137 logger.Println("Syncing", relPath, "to", publishDir)
1138
1139 if err := syncer.Sync(relPath, relPath); err != nil {
1140 c.r.logger.Errorln(err)
1141 }
1142 } else {
1143 c.r.logger.Errorln(err)
1144 }
1145
1146 continue
1147 }
1148
1149 // For all other event operations Hugo will sync static.
1150 logger.Println("Syncing", relPath, "to", publishDir)
1151 if err := syncer.Sync(filepath.Join(publishDir, relPath), relPath); err != nil {
1152 c.r.logger.Errorln(err)
1153 }
1154 }
1155
1156 return 0, nil
1157 }
1158
1159 _, err := c.doWithPublishDirs(syncFn)
1160 return err
1161 }
1162
1163 // chmodFilter is a ChmodFilter for static syncing.
1164 // Returns true to skip syncing permissions for directories and files without
1165 // owner-write permission. The primary use case is files from the module cache (0444).
1166 func chmodFilter(dst, src os.FileInfo) bool {
1167 if src.IsDir() {
1168 return true
1169 }
1170 return src.Mode().Perm()&0o200 == 0
1171 }
1172
1173 func cleanErrorLog(content string) string {
1174 content = logReplacer.Replace(content)
1175 content = logDuplicateTemplateExecuteRe.ReplaceAllString(content, "")
1176 content = logDuplicateTemplateParseRe.ReplaceAllString(content, "")
1177 seen := make(map[string]bool)
1178 parts := strings.Split(content, ": ")
1179 keep := make([]string, 0, len(parts))
1180 for _, part := range parts {
1181 if seen[part] {
1182 continue
1183 }
1184 seen[part] = true
1185 keep = append(keep, part)
1186 }
1187 return strings.Join(keep, ": ")
1188 }
1189
1190 func injectLiveReloadScript(src io.Reader, baseURL *url.URL) string {
1191 var b bytes.Buffer
1192 chain := transform.Chain{livereloadinject.New(baseURL)}
1193 chain.Apply(&b, src)
1194
1195 return b.String()
1196 }
1197
1198 func partitionDynamicEvents(sourceFs *filesystems.SourceFilesystems, events []fsnotify.Event) (de dynamicEvents) {
1199 for _, e := range events {
1200 if !sourceFs.IsContent(e.Name) {
1201 de.AssetEvents = append(de.AssetEvents, e)
1202 } else {
1203 de.ContentEvents = append(de.ContentEvents, e)
1204 }
1205 }
1206 return
1207 }
1208
1209 func pickOneWriteOrCreatePath(contentTypes config.ContentTypesProvider, events []fsnotify.Event) string {
1210 name := ""
1211
1212 for _, ev := range events {
1213 if ev.Op&fsnotify.Write == fsnotify.Write || ev.Op&fsnotify.Create == fsnotify.Create {
1214 if contentTypes.IsIndexContentFile(ev.Name) {
1215 return ev.Name
1216 }
1217
1218 if contentTypes.IsContentFile(ev.Name) {
1219 name = ev.Name
1220 }
1221
1222 }
1223 }
1224
1225 return name
1226 }
1227
1228 func formatByteCount(b uint64) string {
1229 const unit = 1000
1230 if b < unit {
1231 return fmt.Sprintf("%d B", b)
1232 }
1233 div, exp := int64(unit), 0
1234 for n := b / unit; n >= unit; n /= unit {
1235 div *= unit
1236 exp++
1237 }
1238 return fmt.Sprintf("%.1f %cB",
1239 float64(b)/float64(div), "kMGTPE"[exp])
1240 }
1241
1242 func canRedirect(requestURIWithoutQuery string, r *http.Request) bool {
1243 if r.Header.Get(hugoHeaderRedirect) != "" {
1244 return false
1245 }
1246 return isNavigation(requestURIWithoutQuery, r)
1247 }
1248
1249 // Sec-Fetch-Mode should be sent by all recent browser versions, see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-Fetch-Mode#navigate
1250 // Fall back to the file extension if not set.
1251 // The main take here is that we don't want to have CSS/JS files etc. partake in this logic.
1252 func isNavigation(requestURIWithoutQuery string, r *http.Request) bool {
1253 return r.Header.Get("Sec-Fetch-Mode") == "navigate" || isPropablyHTMLRequest(requestURIWithoutQuery)
1254 }
1255
1256 func isPropablyHTMLRequest(requestURIWithoutQuery string) bool {
1257 if strings.HasSuffix(requestURIWithoutQuery, "/") || strings.HasSuffix(requestURIWithoutQuery, "html") || strings.HasSuffix(requestURIWithoutQuery, "htm") {
1258 return true
1259 }
1260 return !strings.Contains(requestURIWithoutQuery, ".")
1261 }