Debian Codegraph @

cmd/main.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 "bufio"
19 "bytes"
20 "encoding/json"
21 "errors"
22 "flag"
23 "fmt"
24 "io"
25 "io/fs"
26 "log"
27 "log/slog"
28 "net"
29 "os"
30 "path/filepath"
31 "runtime"
32 "runtime/debug"
33 "strconv"
34 "strings"
35 "time"
36
37 "github.com/KimMachineGun/automemlimit/memlimit"
38 "github.com/caddyserver/certmagic"
39 "github.com/spf13/pflag"
40 "go.uber.org/automaxprocs/maxprocs"
41 "go.uber.org/zap"
42 "go.uber.org/zap/exp/zapslog"
43
44 "github.com/caddyserver/caddy/v2"
45 "github.com/caddyserver/caddy/v2/caddyconfig"
46 )
47
48 func init() {
49 // set a fitting User-Agent for ACME requests
50 version, _ := caddy.Version()
51 cleanModVersion := strings.TrimPrefix(version, "v")
52 ua := "Caddy/" + cleanModVersion
53 if uaEnv, ok := os.LookupEnv("USERAGENT"); ok {
54 ua = uaEnv + " " + ua
55 }
56 certmagic.UserAgent = ua
57
58 // by using Caddy, user indicates agreement to CA terms
59 // (very important, as Caddy is often non-interactive
60 // and thus ACME account creation will fail!)
61 certmagic.DefaultACME.Agreed = true
62 }
63
64 // Main implements the main function of the caddy command.
65 // Call this if Caddy is to be the main() of your program.
66 func Main() {
67 if len(os.Args) == 0 {
68 fmt.Printf("[FATAL] no arguments provided by OS; args[0] must be command\n")
69 os.Exit(caddy.ExitCodeFailedStartup)
70 }
71
72 if err := defaultFactory.Build().Execute(); err != nil {
73 var exitError *exitError
74 if errors.As(err, &exitError) {
75 os.Exit(exitError.ExitCode)
76 }
77 os.Exit(1)
78 }
79 }
80
81 // handlePingbackConn reads from conn and ensures it matches
82 // the bytes in expect, or returns an error if it doesn't.
83 func handlePingbackConn(conn net.Conn, expect []byte) error {
84 defer conn.Close()
85 confirmationBytes, err := io.ReadAll(io.LimitReader(conn, 32))
86 if err != nil {
87 return err
88 }
89 if !bytes.Equal(confirmationBytes, expect) {
90 return fmt.Errorf("wrong confirmation: %x", confirmationBytes)
91 }
92 return nil
93 }
94
95 // LoadConfig loads the config from configFile and adapts it
96 // using adapterName. If adapterName is specified, configFile
97 // must be also. If no configFile is specified, it tries
98 // loading a default config file. The lack of a config file is
99 // not treated as an error, but false will be returned if
100 // there is no config available. It prints any warnings to stderr,
101 // and returns the resulting JSON config bytes along with
102 // the name of the loaded config file (if any).
103 // The return values are:
104 // - config bytes (nil if no config)
105 // - config file used ("" if none)
106 // - adapter used ("" if none)
107 // - error, if any
108 func LoadConfig(configFile, adapterName string) ([]byte, string, string, error) {
109 return loadConfigWithLogger(caddy.Log(), configFile, adapterName)
110 }
111
112 func isCaddyfile(configFile, adapterName string) (bool, error) {
113 if adapterName == "caddyfile" {
114 return true, nil
115 }
116
117 // as a special case, if a config file starts with "caddyfile" or
118 // has a ".caddyfile" extension, and no adapter is specified, and
119 // no adapter module name matches the extension, assume
120 // caddyfile adapter for convenience
121 baseConfig := strings.ToLower(filepath.Base(configFile))
122 baseConfigExt := filepath.Ext(baseConfig)
123 startsOrEndsInCaddyfile := strings.HasPrefix(baseConfig, "caddyfile") || strings.HasSuffix(baseConfig, ".caddyfile")
124
125 if baseConfigExt == ".json" {
126 return false, nil
127 }
128
129 // If the adapter is not specified,
130 // the config file starts with "caddyfile",
131 // the config file has an extension,
132 // and isn't a JSON file (e.g. Caddyfile.yaml),
133 // then we don't know what the config format is.
134 if adapterName == "" && startsOrEndsInCaddyfile {
135 return true, nil
136 }
137
138 // adapter is not empty,
139 // adapter is not "caddyfile",
140 // extension is not ".json",
141 // extension is not ".caddyfile"
142 // file does not start with "Caddyfile"
143 return false, nil
144 }
145
146 func loadConfigWithLogger(logger *zap.Logger, configFile, adapterName string) ([]byte, string, string, error) {
147 // if no logger is provided, use a nop logger
148 // just so we don't have to check for nil
149 if logger == nil {
150 logger = zap.NewNop()
151 }
152
153 // specifying an adapter without a config file is ambiguous
154 if adapterName != "" && configFile == "" {
155 return nil, "", "", fmt.Errorf("cannot adapt config without config file (use --config)")
156 }
157
158 // load initial config and adapter
159 var config []byte
160 var cfgAdapter caddyconfig.Adapter
161 var err error
162 if configFile != "" {
163 if configFile == "-" {
164 config, err = io.ReadAll(os.Stdin)
165 if err != nil {
166 return nil, "", "", fmt.Errorf("reading config from stdin: %v", err)
167 }
168 logger.Info("using config from stdin")
169 } else {
170 config, err = os.ReadFile(configFile)
171 if err != nil {
172 return nil, "", "", fmt.Errorf("reading config from file: %v", err)
173 }
174 logger.Info("using config from file", zap.String("file", configFile))
175 }
176 } else if adapterName == "" {
177 // if the Caddyfile adapter is plugged in, we can try using an
178 // adjacent Caddyfile by default
179 cfgAdapter = caddyconfig.GetAdapter("caddyfile")
180 if cfgAdapter != nil {
181 config, err = os.ReadFile("Caddyfile")
182 if errors.Is(err, fs.ErrNotExist) {
183 // okay, no default Caddyfile; pretend like this never happened
184 cfgAdapter = nil
185 } else if err != nil {
186 // default Caddyfile exists, but error reading it
187 return nil, "", "", fmt.Errorf("reading default Caddyfile: %v", err)
188 } else {
189 // success reading default Caddyfile
190 configFile = "Caddyfile"
191 logger.Info("using adjacent Caddyfile")
192 }
193 }
194 }
195
196 if yes, err := isCaddyfile(configFile, adapterName); yes {
197 adapterName = "caddyfile"
198 } else if err != nil {
199 return nil, "", "", err
200 }
201
202 // load config adapter
203 if adapterName != "" {
204 cfgAdapter = caddyconfig.GetAdapter(adapterName)
205 if cfgAdapter == nil {
206 return nil, "", "", fmt.Errorf("unrecognized config adapter: %s", adapterName)
207 }
208 }
209
210 // adapt config
211 if cfgAdapter != nil {
212 adaptedConfig, warnings, err := cfgAdapter.Adapt(config, map[string]any{
213 "filename": configFile,
214 })
215 if err != nil {
216 return nil, "", "", fmt.Errorf("adapting config using %s: %v", adapterName, err)
217 }
218 logger.Info("adapted config to JSON", zap.String("adapter", adapterName))
219 for _, warn := range warnings {
220 msg := warn.Message
221 if warn.Directive != "" {
222 msg = fmt.Sprintf("%s: %s", warn.Directive, warn.Message)
223 }
224 logger.Warn(msg,
225 zap.String("adapter", adapterName),
226 zap.String("file", warn.File),
227 zap.Int("line", warn.Line))
228 }
229 config = adaptedConfig
230 } else if len(config) != 0 {
231 // validate that the config is at least valid JSON
232 err = json.Unmarshal(config, new(any))
233 if err != nil {
234 if jsonErr, ok := err.(*json.SyntaxError); ok {
235 return nil, "", "", fmt.Errorf("config is not valid JSON: %w, at offset %d; did you mean to use a config adapter (the --adapter flag)?", err, jsonErr.Offset)
236 }
237 return nil, "", "", fmt.Errorf("config is not valid JSON: %w; did you mean to use a config adapter (the --adapter flag)?", err)
238 }
239 }
240
241 return config, configFile, adapterName, nil
242 }
243
244 // watchConfigFile watches the config file at filename for changes
245 // and reloads the config if the file was updated. This function
246 // blocks indefinitely; it only quits if the poller has errors for
247 // long enough time. The filename passed in must be the actual
248 // config file used, not one to be discovered.
249 // Each second the config files is loaded and parsed into an object
250 // and is compared to the last config object that was loaded
251 func watchConfigFile(filename, adapterName string) {
252 defer func() {
253 if err := recover(); err != nil {
254 log.Printf("[PANIC] watching config file: %v\n%s", err, debug.Stack())
255 }
256 }()
257
258 // make our logger; since config reloads can change the
259 // default logger, we need to get it dynamically each time
260 logger := func() *zap.Logger {
261 return caddy.Log().
262 Named("watcher").
263 With(zap.String("config_file", filename))
264 }
265
266 // get current config
267 lastCfg, _, _, err := loadConfigWithLogger(nil, filename, adapterName)
268 if err != nil {
269 logger().Error("unable to load latest config", zap.Error(err))
270 return
271 }
272
273 logger().Info("watching config file for changes")
274
275 // begin poller
276 //nolint:staticcheck
277 for range time.Tick(1 * time.Second) {
278 // get current config
279 newCfg, _, _, err := loadConfigWithLogger(nil, filename, adapterName)
280 if err != nil {
281 logger().Error("unable to load latest config", zap.Error(err))
282 return
283 }
284
285 // if it hasn't changed, nothing to do
286 if bytes.Equal(lastCfg, newCfg) {
287 continue
288 }
289 logger().Info("config file changed; reloading")
290
291 // remember the current config
292 lastCfg = newCfg
293
294 // apply the updated config
295 err = caddy.Load(lastCfg, false)
296 if err != nil {
297 logger().Error("applying latest config", zap.Error(err))
298 continue
299 }
300 }
301 }
302
303 // Flags wraps a FlagSet so that typed values
304 // from flags can be easily retrieved.
305 type Flags struct {
306 *pflag.FlagSet
307 }
308
309 // String returns the string representation of the
310 // flag given by name. It panics if the flag is not
311 // in the flag set.
312 func (f Flags) String(name string) string {
313 return f.FlagSet.Lookup(name).Value.String()
314 }
315
316 // Bool returns the boolean representation of the
317 // flag given by name. It returns false if the flag
318 // is not a boolean type. It panics if the flag is
319 // not in the flag set.
320 func (f Flags) Bool(name string) bool {
321 val, _ := strconv.ParseBool(f.String(name))
322 return val
323 }
324
325 // Int returns the integer representation of the
326 // flag given by name. It returns 0 if the flag
327 // is not an integer type. It panics if the flag is
328 // not in the flag set.
329 func (f Flags) Int(name string) int {
330 val, _ := strconv.ParseInt(f.String(name), 0, strconv.IntSize)
331 return int(val)
332 }
333
334 // Float64 returns the float64 representation of the
335 // flag given by name. It returns false if the flag
336 // is not a float64 type. It panics if the flag is
337 // not in the flag set.
338 func (f Flags) Float64(name string) float64 {
339 val, _ := strconv.ParseFloat(f.String(name), 64)
340 return val
341 }
342
343 // Duration returns the duration representation of the
344 // flag given by name. It returns false if the flag
345 // is not a duration type. It panics if the flag is
346 // not in the flag set.
347 func (f Flags) Duration(name string) time.Duration {
348 val, _ := caddy.ParseDuration(f.String(name))
349 return val
350 }
351
352 func loadEnvFromFile(envFile string) error {
353 file, err := os.Open(envFile)
354 if err != nil {
355 return fmt.Errorf("reading environment file: %v", err)
356 }
357 defer file.Close()
358
359 envMap, err := parseEnvFile(file)
360 if err != nil {
361 return fmt.Errorf("parsing environment file: %v", err)
362 }
363
364 for k, v := range envMap {
365 // do not overwrite existing environment variables
366 _, exists := os.LookupEnv(k)
367 if !exists {
368 if err := os.Setenv(k, v); err != nil {
369 return fmt.Errorf("setting environment variables: %v", err)
370 }
371 }
372 }
373
374 // Update the storage paths to ensure they have the proper
375 // value after loading a specified env file.
376 caddy.ConfigAutosavePath = filepath.Join(caddy.AppConfigDir(), "autosave.json")
377 caddy.DefaultStorage = &certmagic.FileStorage{Path: caddy.AppDataDir()}
378
379 return nil
380 }
381
382 // parseEnvFile parses an env file from KEY=VALUE format.
383 // It's pretty naive. Limited value quotation is supported,
384 // but variable and command expansions are not supported.
385 func parseEnvFile(envInput io.Reader) (map[string]string, error) {
386 envMap := make(map[string]string)
387
388 scanner := bufio.NewScanner(envInput)
389 var lineNumber int
390
391 for scanner.Scan() {
392 line := strings.TrimSpace(scanner.Text())
393 lineNumber++
394
395 // skip empty lines and lines starting with comment
396 if line == "" || strings.HasPrefix(line, "#") {
397 continue
398 }
399
400 // split line into key and value
401 before, after, isCut := strings.Cut(line, "=")
402 if !isCut {
403 return nil, fmt.Errorf("can't parse line %d; line should be in KEY=VALUE format", lineNumber)
404 }
405 key, val := before, after
406
407 // sometimes keys are prefixed by "export " so file can be sourced in bash; ignore it here
408 key = strings.TrimPrefix(key, "export ")
409
410 // validate key and value
411 if key == "" {
412 return nil, fmt.Errorf("missing or empty key on line %d", lineNumber)
413 }
414 if strings.Contains(key, " ") {
415 return nil, fmt.Errorf("invalid key on line %d: contains whitespace: %s", lineNumber, key)
416 }
417 if strings.HasPrefix(val, " ") || strings.HasPrefix(val, "\t") {
418 return nil, fmt.Errorf("invalid value on line %d: whitespace before value: '%s'", lineNumber, val)
419 }
420
421 // remove any trailing comment after value
422 if commentStart, _, found := strings.Cut(val, "#"); found {
423 val = strings.TrimRight(commentStart, " \t")
424 }
425
426 // quoted value: support newlines
427 if strings.HasPrefix(val, `"`) || strings.HasPrefix(val, "'") {
428 quote := string(val[0])
429 for !strings.HasSuffix(line, quote) || strings.HasSuffix(line, `\`+quote) {
430 val = strings.ReplaceAll(val, `\`+quote, quote)
431 if !scanner.Scan() {
432 break
433 }
434 lineNumber++
435 line = strings.ReplaceAll(scanner.Text(), `\`+quote, quote)
436 val += "\n" + line
437 }
438 val = strings.TrimPrefix(val, quote)
439 val = strings.TrimSuffix(val, quote)
440 }
441
442 envMap[key] = val
443 }
444
445 if err := scanner.Err(); err != nil {
446 return nil, err
447 }
448
449 return envMap, nil
450 }
451
452 func printEnvironment() {
453 _, version := caddy.Version()
454 fmt.Printf("caddy.HomeDir=%s\n", caddy.HomeDir())
455 fmt.Printf("caddy.AppDataDir=%s\n", caddy.AppDataDir())
456 fmt.Printf("caddy.AppConfigDir=%s\n", caddy.AppConfigDir())
457 fmt.Printf("caddy.ConfigAutosavePath=%s\n", caddy.ConfigAutosavePath)
458 fmt.Printf("caddy.Version=%s\n", version)
459 fmt.Printf("runtime.GOOS=%s\n", runtime.GOOS)
460 fmt.Printf("runtime.GOARCH=%s\n", runtime.GOARCH)
461 fmt.Printf("runtime.Compiler=%s\n", runtime.Compiler)
462 fmt.Printf("runtime.NumCPU=%d\n", runtime.NumCPU())
463 fmt.Printf("runtime.GOMAXPROCS=%d\n", runtime.GOMAXPROCS(0))
464 fmt.Printf("runtime.Version=%s\n", runtime.Version())
465 cwd, err := os.Getwd()
466 if err != nil {
467 cwd = fmt.Sprintf("<error: %v>", err)
468 }
469 fmt.Printf("os.Getwd=%s\n\n", cwd)
470 for _, v := range os.Environ() {
471 fmt.Println(v)
472 }
473 }
474
475 func setResourceLimits(logger *zap.Logger) func() {
476 // Configure the maximum number of CPUs to use to match the Linux container quota (if any)
477 // See https://pkg.go.dev/runtime#GOMAXPROCS
478 undo, err := maxprocs.Set(maxprocs.Logger(logger.Sugar().Infof))
479 if err != nil {
480 logger.Warn("failed to set GOMAXPROCS", zap.Error(err))
481 }
482
483 // Configure the maximum memory to use to match the Linux container quota (if any) or system memory
484 // See https://pkg.go.dev/runtime/debug#SetMemoryLimit
485 _, _ = memlimit.SetGoMemLimitWithOpts(
486 memlimit.WithLogger(
487 slog.New(zapslog.NewHandler(
488 logger.Core(),
489 zapslog.WithName("memlimit"),
490 // the default enables traces at ERROR level, this disables
491 // them by setting it to a level higher than any other level
492 zapslog.AddStacktraceAt(slog.Level(127)),
493 )),
494 ),
495 memlimit.WithProvider(
496 memlimit.ApplyFallback(
497 memlimit.FromCgroup,
498 memlimit.FromSystem,
499 ),
500 ),
501 )
502
503 return undo
504 }
505
506 // StringSlice is a flag.Value that enables repeated use of a string flag.
507 type StringSlice []string
508
509 func (ss StringSlice) String() string { return "[" + strings.Join(ss, ", ") + "]" }
510
511 func (ss *StringSlice) Set(value string) error {
512 *ss = append(*ss, value)
513 return nil
514 }
515
516 // Interface guard
517 var _ flag.Value = (*StringSlice)(nil)