Debian Codegraph @

cmd/commandfuncs.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
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 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package caddycmd
16
17 import (
18 "bytes"
19 "context"
20 "crypto/rand"
21 "encoding/json"
22 "errors"
23 "fmt"
24 "io"
25 "io/fs"
26 "log"
27 "maps"
28 "net"
29 "net/http"
30 "os"
31 "os/exec"
32 "runtime"
33 "runtime/debug"
34 "strings"
35
36 "github.com/aryann/difflib"
37 "go.uber.org/zap"
38
39 "github.com/caddyserver/caddy/v2"
40 "github.com/caddyserver/caddy/v2/caddyconfig"
41 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
42 "github.com/caddyserver/caddy/v2/internal"
43 )
44
45 func cmdStart(fl Flags) (int, error) {
46 configFlag := fl.String("config")
47 configAdapterFlag := fl.String("adapter")
48 pidfileFlag := fl.String("pidfile")
49 watchFlag := fl.Bool("watch")
50
51 var err error
52 var envfileFlag []string
53 envfileFlag, err = fl.GetStringSlice("envfile")
54 if err != nil {
55 return caddy.ExitCodeFailedStartup,
56 fmt.Errorf("reading envfile flag: %v", err)
57 }
58
59 // open a listener to which the child process will connect when
60 // it is ready to confirm that it has successfully started
61 ln, err := listenTCPForPingback(net.Listen)
62 if err != nil {
63 return caddy.ExitCodeFailedStartup,
64 fmt.Errorf("opening listener for success confirmation: %v", err)
65 }
66 defer ln.Close()
67
68 // craft the command with a pingback address and with a
69 // pipe for its stdin, so we can tell it our confirmation
70 // code that we expect so that some random port scan at
71 // the most unfortunate time won't fool us into thinking
72 // the child succeeded (i.e. the alternative is to just
73 // wait for any connection on our listener, but better to
74 // ensure it's the process we're expecting - we can be
75 // sure by giving it some random bytes and having it echo
76 // them back to us)
77 cmd := exec.Command(os.Args[0], "run", "--pingback", ln.Addr().String()) //nolint:gosec // no command injection that I can determine...
78 // we should be able to run caddy in relative paths
79 if errors.Is(cmd.Err, exec.ErrDot) {
80 cmd.Err = nil
81 }
82 if configFlag != "" {
83 cmd.Args = append(cmd.Args, "--config", configFlag)
84 }
85
86 for _, envfile := range envfileFlag {
87 cmd.Args = append(cmd.Args, "--envfile", envfile)
88 }
89 if configAdapterFlag != "" {
90 cmd.Args = append(cmd.Args, "--adapter", configAdapterFlag)
91 }
92 if watchFlag {
93 cmd.Args = append(cmd.Args, "--watch")
94 }
95 if pidfileFlag != "" {
96 cmd.Args = append(cmd.Args, "--pidfile", pidfileFlag)
97 }
98 stdinPipe, err := cmd.StdinPipe()
99 if err != nil {
100 return caddy.ExitCodeFailedStartup,
101 fmt.Errorf("creating stdin pipe: %v", err)
102 }
103 cmd.Stdout = os.Stdout
104 cmd.Stderr = os.Stderr
105
106 // generate the random bytes we'll send to the child process
107 expect := make([]byte, 32)
108 _, err = rand.Read(expect)
109 if err != nil {
110 return caddy.ExitCodeFailedStartup,
111 fmt.Errorf("generating random confirmation bytes: %v", err)
112 }
113
114 // begin writing the confirmation bytes to the child's
115 // stdin; use a goroutine since the child hasn't been
116 // started yet, and writing synchronously would result
117 // in a deadlock
118 go func() {
119 _, _ = stdinPipe.Write(expect)
120 stdinPipe.Close()
121 }()
122
123 // start the process
124 err = cmd.Start()
125 if err != nil {
126 return caddy.ExitCodeFailedStartup,
127 fmt.Errorf("starting caddy process: %v", err)
128 }
129
130 // there are two ways we know we're done: either
131 // the process will connect to our listener, or
132 // it will exit with an error
133 success, exit := make(chan struct{}), make(chan error)
134
135 // in one goroutine, we await the success of the child process
136 go func() {
137 for {
138 conn, err := ln.Accept()
139 if err != nil {
140 if !errors.Is(err, net.ErrClosed) {
141 log.Println(err)
142 }
143 break
144 }
145 err = handlePingbackConn(conn, expect)
146 if err == nil {
147 close(success)
148 break
149 }
150 log.Println(err)
151 }
152 }()
153
154 // in another goroutine, we await the failure of the child process
155 go func() {
156 err := cmd.Wait() // don't send on this line! Wait blocks, but send starts before it unblocks
157 exit <- err // sending on separate line ensures select won't trigger until after Wait unblocks
158 }()
159
160 // when one of the goroutines unblocks, we're done and can exit
161 select {
162 case <-success:
163 fmt.Printf("Successfully started Caddy (pid=%d) - Caddy is running in the background\n", cmd.Process.Pid)
164 case err := <-exit:
165 return caddy.ExitCodeFailedStartup,
166 fmt.Errorf("caddy process exited with error: %v", err)
167 }
168
169 return caddy.ExitCodeSuccess, nil
170 }
171
172 type tcpListenFunc func(network, address string) (net.Listener, error)
173
174 func listenTCPForPingback(listen tcpListenFunc) (net.Listener, error) {
175 ln, ipv4Err := listen("tcp4", "127.0.0.1:0")
176 if ipv4Err == nil {
177 return ln, nil
178 }
179
180 ln, ipv6Err := listen("tcp6", "[::1]:0")
181 if ipv6Err == nil {
182 return ln, nil
183 }
184
185 return nil, fmt.Errorf("listen on 127.0.0.1:0: %v; listen on [::1]:0: %v", ipv4Err, ipv6Err)
186 }
187
188 func cmdRun(fl Flags) (int, error) {
189 caddy.TrapSignals()
190
191 // set up buffered logging for early startup
192 // so that we can hold onto logs until after
193 // the config is loaded (or fails to load)
194 // so that we can write the logs to the user's
195 // configured output. we must be sure to flush
196 // on any error before the config is loaded.
197 logger, defaultLogger, logBuffer := caddy.BufferedLog()
198
199 undoMaxProcs := setResourceLimits(logger)
200 defer undoMaxProcs()
201 // release the local reference to the undo function so it can be GC'd;
202 // the deferred call above has already captured the actual function value.
203 undoMaxProcs = nil //nolint:ineffassign,wastedassign
204
205 configFlag := fl.String("config")
206 configAdapterFlag := fl.String("adapter")
207 resumeFlag := fl.Bool("resume")
208 printEnvFlag := fl.Bool("environ")
209 watchFlag := fl.Bool("watch")
210 pidfileFlag := fl.String("pidfile")
211 pingbackFlag := fl.String("pingback")
212
213 // load all additional envs as soon as possible
214 err := handleEnvFileFlag(fl)
215 if err != nil {
216 logBuffer.FlushTo(defaultLogger)
217 return caddy.ExitCodeFailedStartup, err
218 }
219
220 // if we are supposed to print the environment, do that first
221 if printEnvFlag {
222 printEnvironment()
223 }
224
225 // load the config, depending on flags
226 var config []byte
227 if resumeFlag {
228 config, err = os.ReadFile(caddy.ConfigAutosavePath)
229 if errors.Is(err, fs.ErrNotExist) {
230 // not a bad error; just can't resume if autosave file doesn't exist
231 logger.Info("no autosave file exists", zap.String("autosave_file", caddy.ConfigAutosavePath))
232 resumeFlag = false
233 } else if err != nil {
234 logBuffer.FlushTo(defaultLogger)
235 return caddy.ExitCodeFailedStartup, err
236 } else {
237 if configFlag == "" {
238 logger.Info("resuming from last configuration",
239 zap.String("autosave_file", caddy.ConfigAutosavePath))
240 } else {
241 // if they also specified a config file, user should be aware that we're not
242 // using it (doing so could lead to data/config loss by overwriting!)
243 logger.Warn("--config and --resume flags were used together; ignoring --config and resuming from last configuration",
244 zap.String("autosave_file", caddy.ConfigAutosavePath))
245 }
246 }
247 }
248 // we don't use 'else' here since this value might have been changed in 'if' block; i.e. not mutually exclusive
249 var configFile string
250 var adapterUsed string
251 if !resumeFlag {
252 config, configFile, adapterUsed, err = LoadConfig(configFlag, configAdapterFlag)
253 if err != nil {
254 logBuffer.FlushTo(defaultLogger)
255 return caddy.ExitCodeFailedStartup, err
256 }
257 }
258
259 // create pidfile now, in case loading config takes a while (issue #5477)
260 if pidfileFlag != "" {
261 err := caddy.PIDFile(pidfileFlag)
262 if err != nil {
263 logger.Error("unable to write PID file",
264 zap.String("pidfile", pidfileFlag),
265 zap.Error(err))
266 }
267 }
268
269 // If we have a source config file (we're running via 'caddy run --config ...'),
270 // record it so SIGUSR1 can reload from the same file. Also provide a callback
271 // that knows how to load/adapt that source when requested by the main process.
272 if configFile != "" {
273 caddy.SetLastConfig(configFile, adapterUsed, func(file, adapter string) error {
274 cfg, _, _, err := LoadConfig(file, adapter)
275 if err != nil {
276 return err
277 }
278 return caddy.Load(cfg, true)
279 })
280 }
281
282 // run the initial config
283 err = caddy.Load(config, true)
284 if err != nil {
285 logBuffer.FlushTo(defaultLogger)
286 return caddy.ExitCodeFailedStartup, fmt.Errorf("loading initial config: %v", err)
287 }
288 // release the reference to the config so it can be GC'd
289 config = nil //nolint:ineffassign,wastedassign
290
291 // at this stage the config will have replaced the
292 // default logger to the configured one, so we can
293 // log normally, now that the config is running.
294 // also clear our ref to the buffer so it can get GC'd
295 logger = caddy.Log()
296 defaultLogger = nil //nolint:ineffassign,wastedassign
297 logBuffer = nil //nolint:wastedassign,ineffassign
298 logger.Info("serving initial configuration")
299
300 // if we are to report to another process the successful start
301 // of the server, do so now by echoing back contents of stdin
302 if pingbackFlag != "" {
303 confirmationBytes, err := io.ReadAll(os.Stdin)
304 if err != nil {
305 return caddy.ExitCodeFailedStartup,
306 fmt.Errorf("reading confirmation bytes from stdin: %v", err)
307 }
308 conn, err := net.Dial("tcp", pingbackFlag)
309 if err != nil {
310 return caddy.ExitCodeFailedStartup,
311 fmt.Errorf("dialing confirmation address: %v", err)
312 }
313 _, err = conn.Write(confirmationBytes)
314 if err != nil {
315 return caddy.ExitCodeFailedStartup,
316 fmt.Errorf("writing confirmation bytes to %s: %v", pingbackFlag, err)
317 }
318 // close (non-defer because we `select {}` below)
319 // and release references so they can be GC'd
320 conn.Close()
321 confirmationBytes = nil //nolint:ineffassign,wastedassign
322 conn = nil //nolint:wastedassign,ineffassign
323 }
324
325 // if enabled, reload config file automatically on changes
326 // (this better only be used in dev!)
327 if watchFlag {
328 go watchConfigFile(configFile, adapterUsed)
329 }
330
331 // warn if the environment does not provide enough information about the disk
332 hasXDG := os.Getenv("XDG_DATA_HOME") != "" &&
333 os.Getenv("XDG_CONFIG_HOME") != "" &&
334 os.Getenv("XDG_CACHE_HOME") != ""
335 switch runtime.GOOS {
336 case "windows":
337 if os.Getenv("HOME") == "" && os.Getenv("USERPROFILE") == "" && !hasXDG {
338 logger.Warn("neither HOME nor USERPROFILE environment variables are set - please fix; some assets might be stored in ./caddy")
339 }
340 case "plan9":
341 if os.Getenv("home") == "" && !hasXDG {
342 logger.Warn("$home environment variable is empty - please fix; some assets might be stored in ./caddy")
343 }
344 default:
345 if os.Getenv("HOME") == "" && !hasXDG {
346 logger.Warn("$HOME environment variable is empty - please fix; some assets might be stored in ./caddy")
347 }
348 }
349
350 // release the last local logger reference
351 logger = nil //nolint:wastedassign,ineffassign
352
353 select {}
354 }
355
356 func cmdStop(fl Flags) (int, error) {
357 addressFlag := fl.String("address")
358 configFlag := fl.String("config")
359 configAdapterFlag := fl.String("adapter")
360
361 adminAddr, err := DetermineAdminAPIAddress(addressFlag, nil, configFlag, configAdapterFlag)
362 if err != nil {
363 return caddy.ExitCodeFailedStartup, fmt.Errorf("couldn't determine admin API address: %v", err)
364 }
365
366 resp, err := AdminAPIRequest(adminAddr, http.MethodPost, "/stop", nil, nil)
367 if err != nil {
368 caddy.Log().Warn("failed using API to stop instance", zap.Error(err))
369 return caddy.ExitCodeFailedStartup, err
370 }
371 defer resp.Body.Close()
372
373 return caddy.ExitCodeSuccess, nil
374 }
375
376 func cmdReload(fl Flags) (int, error) {
377 configFlag := fl.String("config")
378 configAdapterFlag := fl.String("adapter")
379 addressFlag := fl.String("address")
380 forceFlag := fl.Bool("force")
381
382 // get the config in caddy's native format
383 config, configFile, adapterUsed, err := LoadConfig(configFlag, configAdapterFlag)
384 if err != nil {
385 return caddy.ExitCodeFailedStartup, err
386 }
387 if configFile == "" {
388 return caddy.ExitCodeFailedStartup, fmt.Errorf("no config file to load")
389 }
390
391 adminAddr, err := DetermineAdminAPIAddress(addressFlag, config, configFile, configAdapterFlag)
392 if err != nil {
393 return caddy.ExitCodeFailedStartup, fmt.Errorf("couldn't determine admin API address: %v", err)
394 }
395
396 // optionally force a config reload
397 headers := make(http.Header)
398 if forceFlag {
399 headers.Set("Cache-Control", "must-revalidate")
400 }
401 // Provide the source file/adapter to the running process so it can
402 // preserve its last-config knowledge if this reload came from the same source.
403 headers.Set("Caddy-Config-Source-File", configFile)
404 headers.Set("Caddy-Config-Source-Adapter", adapterUsed)
405
406 resp, err := AdminAPIRequest(adminAddr, http.MethodPost, "/load", headers, bytes.NewReader(config))
407 if err != nil {
408 return caddy.ExitCodeFailedStartup, fmt.Errorf("sending configuration to instance: %v", err)
409 }
410 defer resp.Body.Close()
411
412 return caddy.ExitCodeSuccess, nil
413 }
414
415 func cmdVersion(_ Flags) (int, error) {
416 _, full := caddy.Version()
417 fmt.Println(full)
418 return caddy.ExitCodeSuccess, nil
419 }
420
421 func cmdBuildInfo(_ Flags) (int, error) {
422 bi, ok := debug.ReadBuildInfo()
423 if !ok {
424 return caddy.ExitCodeFailedStartup, fmt.Errorf("no build information")
425 }
426 fmt.Println(bi)
427 return caddy.ExitCodeSuccess, nil
428 }
429
430 // jsonModuleInfo holds metadata about a Caddy module for JSON output.
431 type jsonModuleInfo struct {
432 ModuleName string `json:"module_name"`
433 ModuleType string `json:"module_type"`
434 Version string `json:"version,omitempty"`
435 PackageURL string `json:"package_url,omitempty"`
436 }
437
438 func cmdListModules(fl Flags) (int, error) {
439 packages := fl.Bool("packages")
440 versions := fl.Bool("versions")
441 skipStandard := fl.Bool("skip-standard")
442 jsonOutput := fl.Bool("json")
443
444 // Organize modules by whether they come with the standard distribution
445 standard, nonstandard, unknown, err := getModules()
446 if err != nil {
447 // If module info can't be fetched, just print the IDs and exit
448 for _, m := range caddy.Modules() {
449 fmt.Println(m)
450 }
451 return caddy.ExitCodeSuccess, nil
452 }
453
454 // Logic for JSON output
455 if jsonOutput {
456 output := []jsonModuleInfo{}
457
458 // addToOutput is a helper to convert internal module info to the JSON-serializable struct
459 addToOutput := func(list []moduleInfo, moduleType string) {
460 for _, mi := range list {
461 item := jsonModuleInfo{
462 ModuleName: mi.caddyModuleID,
463 ModuleType: moduleType, // Mapping the type here
464 }
465 if mi.goModule != nil {
466 item.Version = mi.goModule.Version
467 item.PackageURL = mi.goModule.Path
468 }
469 output = append(output, item)
470 }
471 }
472
473 // Pass the respective type for each category
474 if !skipStandard {
475 addToOutput(standard, "standard")
476 }
477 addToOutput(nonstandard, "non-standard")
478 addToOutput(unknown, "unknown")
479
480 jsonBytes, err := json.MarshalIndent(output, "", " ")
481 if err != nil {
482 return caddy.ExitCodeFailedQuit, err
483 }
484 fmt.Println(string(jsonBytes))
485 return caddy.ExitCodeSuccess, nil
486 }
487
488 // Logic for Text output (Fallback)
489 printModuleInfo := func(mi moduleInfo) {
490 fmt.Print(mi.caddyModuleID)
491 if versions && mi.goModule != nil {
492 fmt.Print(" " + mi.goModule.Version)
493 }
494 if packages && mi.goModule != nil {
495 fmt.Print(" " + mi.goModule.Path)
496 if mi.goModule.Replace != nil {
497 fmt.Print(" => " + mi.goModule.Replace.Path)
498 }
499 }
500 if mi.err != nil {
501 fmt.Printf(" [%v]", mi.err)
502 }
503 fmt.Println()
504 }
505
506 // Standard modules (always shipped with Caddy)
507 if !skipStandard {
508 if len(standard) > 0 {
509 for _, mod := range standard {
510 printModuleInfo(mod)
511 }
512 }
513 fmt.Printf("\n Standard modules: %d\n", len(standard))
514 }
515
516 // Non-standard modules (third party plugins)
517 if len(nonstandard) > 0 {
518 if len(standard) > 0 && !skipStandard {
519 fmt.Println()
520 }
521 for _, mod := range nonstandard {
522 printModuleInfo(mod)
523 }
524 fmt.Printf("\n Non-standard modules: %d\n", len(nonstandard))
525 }
526
527 // Unknown modules (couldn't get Caddy module info)
528 if len(unknown) > 0 {
529 if (len(standard) > 0 && !skipStandard) || len(nonstandard) > 0 {
530 fmt.Println()
531 }
532 for _, mod := range unknown {
533 printModuleInfo(mod)
534 }
535 fmt.Printf("\n Unknown modules: %d\n", len(unknown))
536 }
537
538 return caddy.ExitCodeSuccess, nil
539 }
540
541 func cmdEnviron(fl Flags) (int, error) {
542 // load all additional envs as soon as possible
543 err := handleEnvFileFlag(fl)
544 if err != nil {
545 return caddy.ExitCodeFailedStartup, err
546 }
547
548 printEnvironment()
549 return caddy.ExitCodeSuccess, nil
550 }
551
552 func cmdAdaptConfig(fl Flags) (int, error) {
553 configFlag := fl.String("config")
554 adapterFlag := fl.String("adapter")
555 prettyFlag := fl.Bool("pretty")
556 validateFlag := fl.Bool("validate")
557
558 var err error
559 configFlag, err = configFileWithRespectToDefault(caddy.Log(), configFlag)
560 if err != nil {
561 return caddy.ExitCodeFailedStartup, err
562 }
563 if configFlag == "" {
564 return caddy.ExitCodeFailedStartup,
565 fmt.Errorf("input file required when there is no Caddyfile in current directory (use --config flag)")
566 }
567
568 // load all additional envs as soon as possible
569 err = handleEnvFileFlag(fl)
570 if err != nil {
571 return caddy.ExitCodeFailedStartup, err
572 }
573
574 if adapterFlag == "" {
575 return caddy.ExitCodeFailedStartup,
576 fmt.Errorf("adapter name is required (use --adapt flag or leave unspecified for default)")
577 }
578
579 cfgAdapter := caddyconfig.GetAdapter(adapterFlag)
580 if cfgAdapter == nil {
581 return caddy.ExitCodeFailedStartup,
582 fmt.Errorf("unrecognized config adapter: %s", adapterFlag)
583 }
584
585 var input []byte
586 // read from stdin if the file name is "-"
587 if configFlag == "-" {
588 input, err = io.ReadAll(os.Stdin)
589 } else {
590 input, err = os.ReadFile(configFlag)
591 }
592 if err != nil {
593 return caddy.ExitCodeFailedStartup,
594 fmt.Errorf("reading input file: %v", err)
595 }
596
597 opts := map[string]any{"filename": configFlag}
598
599 adaptedConfig, warnings, err := cfgAdapter.Adapt(input, opts)
600 if err != nil {
601 return caddy.ExitCodeFailedStartup, err
602 }
603
604 if prettyFlag {
605 var prettyBuf bytes.Buffer
606 err = json.Indent(&prettyBuf, adaptedConfig, "", "\t")
607 if err != nil {
608 return caddy.ExitCodeFailedStartup, err
609 }
610 adaptedConfig = prettyBuf.Bytes()
611 }
612
613 // print result to stdout
614 fmt.Println(string(adaptedConfig))
615
616 // print warnings to stderr
617 for _, warn := range warnings {
618 msg := warn.Message
619 if warn.Directive != "" {
620 msg = fmt.Sprintf("%s: %s", warn.Directive, warn.Message)
621 }
622 caddy.Log().Named(adapterFlag).Warn(msg,
623 zap.String("file", warn.File),
624 zap.Int("line", warn.Line))
625 }
626
627 // validate output if requested
628 if validateFlag {
629 var cfg *caddy.Config
630 err = caddy.StrictUnmarshalJSON(adaptedConfig, &cfg)
631 if err != nil {
632 return caddy.ExitCodeFailedStartup, fmt.Errorf("decoding config: %v", err)
633 }
634 err = caddy.Validate(cfg)
635 if err != nil {
636 return caddy.ExitCodeFailedStartup, fmt.Errorf("validation: %v", err)
637 }
638 }
639
640 return caddy.ExitCodeSuccess, nil
641 }
642
643 func cmdValidateConfig(fl Flags) (int, error) {
644 configFlag := fl.String("config")
645 adapterFlag := fl.String("adapter")
646
647 // load all additional envs as soon as possible
648 err := handleEnvFileFlag(fl)
649 if err != nil {
650 return caddy.ExitCodeFailedStartup, err
651 }
652
653 // use default config and ensure a config file is specified
654 configFlag, err = configFileWithRespectToDefault(caddy.Log(), configFlag)
655 if err != nil {
656 return caddy.ExitCodeFailedStartup, err
657 }
658 if configFlag == "" {
659 return caddy.ExitCodeFailedStartup,
660 fmt.Errorf("input file required when there is no Caddyfile in current directory (use --config flag)")
661 }
662
663 input, _, _, err := LoadConfig(configFlag, adapterFlag)
664 if err != nil {
665 return caddy.ExitCodeFailedStartup, err
666 }
667 input = caddy.RemoveMetaFields(input)
668
669 var cfg *caddy.Config
670 err = caddy.StrictUnmarshalJSON(input, &cfg)
671 if err != nil {
672 return caddy.ExitCodeFailedStartup, fmt.Errorf("decoding config: %v", err)
673 }
674
675 err = caddy.Validate(cfg)
676 if err != nil {
677 return caddy.ExitCodeFailedStartup, err
678 }
679
680 fmt.Println("Valid configuration")
681
682 return caddy.ExitCodeSuccess, nil
683 }
684
685 func cmdFmt(fl Flags) (int, error) {
686 configFile := fl.Arg(0)
687 configFlag := fl.String("config")
688 if (len(fl.Args()) > 1) || (configFlag != "" && configFile != "") {
689 return caddy.ExitCodeFailedStartup, fmt.Errorf("fmt does not support multiple files %s %s", configFlag, strings.Join(fl.Args(), " "))
690 }
691 if configFile == "" && configFlag == "" {
692 configFile = "Caddyfile"
693 } else if configFile == "" {
694 configFile = configFlag
695 }
696 // as a special case, read from stdin if the file name is "-"
697 if configFile == "-" {
698 input, err := io.ReadAll(os.Stdin)
699 if err != nil {
700 return caddy.ExitCodeFailedStartup,
701 fmt.Errorf("reading stdin: %v", err)
702 }
703 fmt.Print(string(caddyfile.Format(input)))
704 return caddy.ExitCodeSuccess, nil
705 }
706
707 input, err := os.ReadFile(configFile)
708 if err != nil {
709 return caddy.ExitCodeFailedStartup,
710 fmt.Errorf("reading input file: %v", err)
711 }
712
713 output := caddyfile.Format(input)
714
715 if fl.Bool("overwrite") {
716 if err := os.WriteFile(configFile, output, 0o600); err != nil { //nolint:gosec // path traversal is not really a thing here, this is either "Caddyfile" or admin-controlled
717 return caddy.ExitCodeFailedStartup, fmt.Errorf("overwriting formatted file: %v", err)
718 }
719 return caddy.ExitCodeSuccess, nil
720 }
721
722 if fl.Bool("diff") {
723 diff := difflib.Diff(
724 strings.Split(string(input), "\n"),
725 strings.Split(string(output), "\n"))
726 for _, d := range diff {
727 switch d.Delta {
728 case difflib.Common:
729 fmt.Printf(" %s\n", d.Payload)
730 case difflib.LeftOnly:
731 fmt.Printf("- %s\n", d.Payload)
732 case difflib.RightOnly:
733 fmt.Printf("+ %s\n", d.Payload)
734 }
735 }
736 } else {
737 fmt.Print(string(output))
738 }
739
740 if warning, diff := caddyfile.FormattingDifference(configFile, input); diff {
741 return caddy.ExitCodeFailedStartup, fmt.Errorf(`%s:%d: Caddyfile input is not formatted; Tip: use '--overwrite' to update your Caddyfile in-place instead of previewing it. Consult '--help' for more options`,
742 warning.File,
743 warning.Line,
744 )
745 }
746
747 return caddy.ExitCodeSuccess, nil
748 }
749
750 // handleEnvFileFlag loads the environment variables from the given --envfile
751 // flag if specified. This should be called as early in the command function.
752 func handleEnvFileFlag(fl Flags) error {
753 var err error
754 var envfileFlag []string
755 envfileFlag, err = fl.GetStringSlice("envfile")
756 if err != nil {
757 return fmt.Errorf("reading envfile flag: %v", err)
758 }
759
760 for _, envfile := range envfileFlag {
761 if err := loadEnvFromFile(envfile); err != nil {
762 return fmt.Errorf("loading additional environment variables: %v", err)
763 }
764 }
765
766 return nil
767 }
768
769 // AdminAPIRequest makes an API request according to the CLI flags given,
770 // with the given HTTP method and request URI. If body is non-nil, it will
771 // be assumed to be Content-Type application/json. The caller should close
772 // the response body. Should only be used by Caddy CLI commands which
773 // need to interact with a running instance of Caddy via the admin API.
774 func AdminAPIRequest(adminAddr, method, uri string, headers http.Header, body io.Reader) (*http.Response, error) {
775 parsedAddr, err := caddy.ParseNetworkAddress(adminAddr)
776 if err != nil || parsedAddr.PortRangeSize() > 1 {
777 return nil, fmt.Errorf("invalid admin address %s: %v", adminAddr, err)
778 }
779 origin := "http://" + parsedAddr.JoinHostPort(0)
780 if parsedAddr.IsUnixNetwork() {
781 origin = "http://127.0.0.1" // bogus host is a hack so that http.NewRequest() is happy
782
783 // the unix address at this point might still contain the optional
784 // unix socket permissions, which are part of the address/host.
785 // those need to be removed first, as they aren't part of the
786 // resulting unix file path
787 addr, _, err := internal.SplitUnixSocketPermissionsBits(parsedAddr.Host)
788 if err != nil {
789 return nil, err
790 }
791 parsedAddr.Host = addr
792 } else if parsedAddr.IsFdNetwork() {
793 origin = "http://127.0.0.1"
794 }
795
796 // form the request
797 req, err := http.NewRequest(method, origin+uri, body)
798 if err != nil {
799 return nil, fmt.Errorf("making request: %v", err)
800 }
801 if parsedAddr.IsUnixNetwork() || parsedAddr.IsFdNetwork() {
802 // We used to conform to RFC 2616 Section 14.26 which requires
803 // an empty host header when there is no host, as is the case
804 // with unix sockets and socket fds. However, Go required a
805 // Host value so we used a hack of a space character as the host
806 // (it would see the Host was non-empty, then trim the space later).
807 // As of Go 1.20.6 (July 2023), this hack no longer works. See:
808 // https://github.com/golang/go/issues/60374
809 // See also the discussion here:
810 // https://github.com/golang/go/issues/61431
811 //
812 // After that, we now require a Host value of either 127.0.0.1
813 // or ::1 if one is set. Above I choose to use 127.0.0.1. Even
814 // though the value should be completely irrelevant (it could be
815 // "srldkjfsd"), if for some reason the Host *is* used, at least
816 // we can have some reasonable assurance it will stay on the local
817 // machine and that browsers, if they ever allow access to unix
818 // sockets, can still enforce CORS, ensuring it is still coming
819 // from the local machine.
820 } else {
821 req.Header.Set("Origin", origin)
822 }
823 if body != nil {
824 req.Header.Set("Content-Type", "application/json")
825 }
826 maps.Copy(req.Header, headers)
827
828 // make an HTTP client that dials our network type, since admin
829 // endpoints aren't always TCP, which is what the default transport
830 // expects; reuse is not of particular concern here
831 client := http.Client{
832 Transport: &http.Transport{
833 DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
834 return net.Dial(parsedAddr.Network, parsedAddr.JoinHostPort(0))
835 },
836 },
837 }
838
839 resp, err := client.Do(req) //nolint:gosec // the only SSRF here would be self-sabatoge I think
840 if err != nil {
841 return nil, fmt.Errorf("performing request: %v", err)
842 }
843
844 // if it didn't work, let the user know
845 if resp.StatusCode >= 400 {
846 respBody, err := io.ReadAll(io.LimitReader(resp.Body, 1024*1024*2))
847 if err != nil {
848 return nil, fmt.Errorf("HTTP %d: reading error message: %v", resp.StatusCode, err)
849 }
850 return nil, fmt.Errorf("caddy responded with error: HTTP %d: %s", resp.StatusCode, respBody)
851 }
852
853 return resp, nil
854 }
855
856 // DetermineAdminAPIAddress determines which admin API endpoint address should
857 // be used based on the inputs. By priority: if `address` is specified, then
858 // it is returned; if `config` is specified, then that config will be used for
859 // finding the admin address; if `configFile` (and `configAdapter`) are specified,
860 // then that config will be loaded to find the admin address; otherwise, the
861 // default admin listen address will be returned.
862 func DetermineAdminAPIAddress(address string, config []byte, configFile, configAdapter string) (string, error) {
863 // Prefer the address if specified and non-empty
864 if address != "" {
865 return address, nil
866 }
867
868 // Try to load the config from file if specified, with the given adapter name
869 if configFile != "" {
870 var loadedConfigFile string
871 var err error
872
873 // use the provided loaded config if non-empty
874 // otherwise, load it from the specified file/adapter
875 loadedConfig := config
876 if len(loadedConfig) == 0 {
877 // get the config in caddy's native format
878 loadedConfig, loadedConfigFile, _, err = LoadConfig(configFile, configAdapter)
879 if err != nil {
880 return "", err
881 }
882 if loadedConfigFile == "" {
883 return "", fmt.Errorf("no config file to load; either use --config flag or ensure Caddyfile exists in current directory")
884 }
885 }
886
887 // get the address of the admin listener from the config
888 if len(loadedConfig) > 0 {
889 var tmpStruct struct {
890 Admin caddy.AdminConfig `json:"admin"`
891 }
892 err := json.Unmarshal(loadedConfig, &tmpStruct)
893 if err != nil {
894 return "", fmt.Errorf("unmarshaling admin listener address from config: %v", err)
895 }
896 if tmpStruct.Admin.Listen != "" {
897 return tmpStruct.Admin.Listen, nil
898 }
899 }
900 }
901
902 // Fallback to the default listen address otherwise
903 return caddy.DefaultAdminListen, nil
904 }
905
906 // configFileWithRespectToDefault returns the filename to use for loading the config, based
907 // on whether a config file is already specified and a supported default config file exists.
908 func configFileWithRespectToDefault(logger *zap.Logger, configFile string) (string, error) {
909 const defaultCaddyfile = "Caddyfile"
910
911 // if no input file was specified, try a default Caddyfile if the Caddyfile adapter is plugged in
912 if configFile == "" && caddyconfig.GetAdapter("caddyfile") != nil {
913 _, err := os.Stat(defaultCaddyfile)
914 if err == nil {
915 // default Caddyfile exists
916 if logger != nil {
917 logger.Info("using adjacent Caddyfile")
918 }
919 return defaultCaddyfile, nil
920 }
921 if !errors.Is(err, fs.ErrNotExist) {
922 // problem checking
923 return configFile, fmt.Errorf("checking if default Caddyfile exists: %v", err)
924 }
925 }
926
927 // default config file does not exist or is irrelevant
928 return configFile, nil
929 }
930
931 type moduleInfo struct {
932 caddyModuleID string
933 goModule *debug.Module
934 err error
935 }