Commit Graph
101 Commits
Author SHA1 Message Date
Indra Gunawan d588d5c8f0 cmd: unbuffer default logger on startup failure (#8180)
* cmd: unbuffer default logger on startup failure

Restore default logger to unbuffered console logger on cmdRun error so WrapCommandFuncForCobra can output the error.

* add regression tests
2026-10-09 21:22:40 +00:00
4f45ded755 caddyconfig: unify Caddyfile lexer/parser/formatter (token-based formatter) (#7880)
* docs: add Caddyfile lexer/parser/formatter unification design spec

Design for unifying the Caddyfile lexer/parser and the standalone formatter
by making the token pipeline drive formatting: raw-source-span capture,
comment tokens, separator-kind metadata, follow-imports and (default-off)
braced-wrap modes. Includes adversarial-review hardening and empirically-found
intentional improvements over the legacy formatter.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: add phased implementation plan for Caddyfile formatter unification

Task-by-task TDD plan: Phase 1 (token model + formatter rewrite + fuzz
invariants + legacy oracle), Phase 2 (follow-imports mode + caddy fmt
--imports), Phase 3 (default-off braced-wrap).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test: vendor legacy Caddyfile formatter as differential oracle

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: add format-mode Token fields and accessors

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: add Lex and LexOptions; Tokenize delegates to Lex

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: capture verbatim raw source spans in format mode

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: emit comment tokens in format mode

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: record token separator kind in format mode

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: split structural braces in format mode

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: rewrite Format as a token-based renderer (core layout)

Replace the rune-by-rune state machine with a renderer that consumes the
format-mode token stream (Lex with Comments+Raw). Adds FormatWithOptions and
FormatOptions{WrapUnbracedSite}; Format keeps its signature. Comment
placement, continuations, empty-block expansion, and the import/}-glue rules
land in Tasks 9-11; the six dependent TestFormatter cases are temporarily
skipped with annotations.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: token renderer comments (I1/I3) and continuations (D1)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: token renderer empty blocks (I2) and post-} break (I4)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: import-brace exception, drop nesting cap, drop < quirk

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: fix formatter idempotency/semantic bugs, retire legacy oracle

Fix two fuzz-found bugs plus several related idempotency issues in the
token-based Caddyfile formatter, and retire the legacy byte-scanner
formatter used as a test oracle.

Bug B (formatter.go): a stray "}" at nesting 0 was glued to an unquoted
predecessor because precededBySpace is unreliable after an unquoted token.
Only suppress the separating space for an inline close brace when the
previous token is quoted (same guard as comment gluing), so "0 }" no longer
merges into "0}".

Bug A (lexer.go): an empty-bodied heredoc hitting EOF with no closing marker
was silently dropped, breaking Format idempotency. Surface it as an
"incomplete heredoc" error ONLY in format mode (opts.Comments || opts.Raw);
Tokenize/Parse keep the exact prior silent-drop behavior. Format then falls
back to preserving the trimmed input.

Additional format-mode-only fixes surfaced by property fuzzing: correct
line-break accounting for empty-bodied heredocs and continuation-framed
quoted tokens; normalize the raw slice / clear continuation on split and
standalone structural braces; guard the address/comment/brace fold so a
next-line "{" is not folded onto a comment trailing an opening brace; and a
fallback + idempotency backstop in FormatWithOptions for degenerate tokens
(ambiguous heredoc openers, unterminated/escaped quotes, dangling escapes,
messy/leading line continuations). The parse path is unchanged.

Property fuzz targets (formatter_test.go): keep FuzzFormatIdempotent,
FuzzFormatNoPanic, and a redesigned FuzzFormatSemanticPreserve that asserts
format-mode token-text preservation (robust to the parser's lenient grouping
of ambiguous brace layouts). Add regression tests
TestFormatStrayCloseBraceKeepsTokens and TestFormatIncompleteHeredocIdempotent.
Remove FuzzFormatParity, containsParityExclusion, maxNesting and delete
formatter_legacy_test.go (legacyFormat oracle + TestLegacyOracleMatchesCurrent).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: seed corpus and FormattingDifference stability tests

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: extract pure import-glob resolution helper

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: import discovery for follow-imports formatting

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: FormatImports formats root plus imported files

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* cmd: add 'caddy fmt --imports' to format imported files

Adds a --imports flag to 'caddy fmt' that calls caddyfile.FormatImports
to format the root Caddyfile and all files it references via import
directives. Rejects --imports with stdin (no source directory to resolve
against). With --overwrite each file is written back; otherwise each
file's output is printed to stdout with a '# <path>' header, with
optional per-file diff via --diff.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: detect single unbraced site block

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: implement default-off unbraced->braced site wrapping

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: make WrapUnbracedSite decision on normalized stream (idempotency fix)

FormatWithOptions wrapped before formatting, deciding on the raw token
stream. isSingleUnbracedSite uses source-line gaps, but formatTokens
removes blank lines and folds dangling braces, so a shape read as "not a
single site" on pass 1 could read as a single unbraced site on pass 2 and
get wrapped, breaking Format(Format(x)) == Format(x).

Decide the wrap on the already-normalized stream instead: normalize, re-lex,
and wrap only if isSingleUnbracedSite holds there. tokens becomes the wrapped
stream so the backstop still compares like-for-like; once wrapped the output
is braced, so no double-wrap on re-runs. Format (zero options) still never
wraps.

Adds a regression reproducer and FuzzWrapUnbracedSiteIdempotent.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: satisfy golangci-lint (rangeint + De Morgan)

Modernize three index loops to range-over-int and simplify a negated
boolean per staticcheck QF1001. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: modernize remaining index loops (rangeint)

Convert the remaining for-i index loops to range-over-int per golangci-lint
modernize. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* caddyfile: fix formatter and import correctness issues (#7881)

* caddyfile: fix formatter and import correctness issues

* noot

* noot

* caddyfile: document parser-driven import discovery

* test: make formatter import tests portable (#7882)

* caddyfile: propagate import observer into named route blocks

Named route blocks expand their imports through a separate parser built in
expandImportsInBlock, which copied only definedSnippets and importGraph. The
importObserver hook was left nil, so FormatImports never saw files imported
from inside a &(name) { ... } block and "caddy fmt --imports" silently skipped
them.

Carry the observer into that parser and cover it with a discovery test.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* caddyfile: detect end-of-input-swallowing tokens from token shape

hasUnformattableToken documented an unterminated quote/backtick as a shape
that cannot be rendered idempotently, but never implemented the check. The
condition was only caught dynamically by trailingNewlineChangesTokens, which
returns early for input that already ends in a newline. That early return is
wrong for a token that swallowed the newline: once Format's mandatory trailing
newline sits inside an unterminated quote, appending another one no longer
changes the stream, so the second pass rendered what the first pass had
preserved verbatim.

    Format(`"""`)   => `"""`     (fallback, preserved)
    Format(`"""` + newline) => `"" "` (rendered, space inserted)

Decide it from the token instead: a non-quoted token whose verbatim source
ends in a newline swallowed it, since a newline otherwise terminates a token.
This also covers an escaped quote ("\"") running to end-of-input, which has
the same shape. A lone "\r" is kept in raw but does not terminate a token, so
it is deliberately excluded; heredoc tokens carry wasQuoted == '<'.

Master's rune-based formatter was idempotent on these inputs, so this restores
parity. Found by FuzzFormatIdempotent; the inputs are added as portable seeds
and table cases rather than testdata/fuzz files.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* caddyfile: stop Format from mutating its input buffer

The three fallback paths returned append(bytes.TrimSpace(input), '\n').
TrimSpace returns a subslice sharing the caller's backing array, so the append
wrote the newline into the caller's buffer. os.ReadFile returns a slice with
one byte of spare capacity, which is exactly what the append needs, so this
reached real callers:

    $ printf 'foo "unterminated  \n\n' > Caddyfile
    $ caddy fmt --diff
      foo "unterminated      <- reported unchanged; its trailing
    -                           whitespace was in fact stripped

cmd/commandfuncs.go compares input against output after calling Format, and by
then input had been overwritten to match. The same aliasing corrupted
FuzzFormatIdempotent, which reported failures whose recorded inputs did not
reproduce.

Copy into a fresh buffer instead, and assert both non-mutation and
non-aliasing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* caddyfile: preserve repeated import expansions during formatting

Deduplicate formatted files without skipping imports with different arguments,
block substitutions, or lexical aliases. Track active physical-file ancestry
to prevent symlink cycles, including snippet and block expansion contexts.

Add regression coverage and align the upstream glued-brace expectation with
the token-based formatter's literal-token behavior.

Validation: go test -race -short ./..., go build ./..., and golangci-lint run
--timeout 10m all pass.

AI assistance: OpenAI Codex (GPT-6) assisted with implementation and testing.

* docs: remove formatter implementation plan and design spec

* caddyfile: require whitespace before line continuations

Preserve attached trailing backslashes as literal text, including Windows root paths. Require a space or tab before an unquoted continuation backslash, and preserve significant leading whitespace in formatter fallback output.

Add lexer, formatter, CRLF, adapter, and fuzz regression coverage. Validated with race tests, build, lint, formatter fuzzing, and the 165-example forum corpus.

AI assistance: OpenAI Codex (GPT-6) assisted with implementation, regression tests, and validation.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: a <a@tuxpa.in>
2026-10-07 17:14:16 -04:00
futurehua 93c0721156 chore: fix sabotage spelling in nolint comments (#7892)
Signed-off-by: futurehua <futurehua@outlook.com>
2026-07-18 08:14:38 +00:00
Zen Dodd 6628c4a9de cmd: support caddy start on IPv6-only hosts (#7744) 2026-05-20 10:17:34 -04:00
Matthew Holt 1fbb28720b Fix lint errors
Use VerifyConnection instead of VerifyPeerCertificate; the other 2 fixes are "meh" not really a big deal or an issue at all.
2026-03-11 13:33:59 -06:00
Matt HoltandFrancis Lavoie cd9e1660aa cmd: Pass configFile, not configFlag, for reload command (#7532)
* cmd: Pass configFile, not configFlag, for reload command

This *should* fix #7528.

* Remove debug log line

---------

Co-authored-by: Francis Lavoie <lavofr@gmail.com>
2026-02-27 15:24:05 -07:00
Matt Holt 95941a71e8 chore: Add nolints to work around haywire linters (#7493)
* chore: Add nolints to work around haywire linters

* More lint wrangling
2026-02-17 16:52:54 -07:00
Paulo Henrique 9eabd443cb cmd: Add --json flag to list-modules command (#7409) 2025-12-26 12:32:03 -05:00
Francis Lavoie 65e0ddc221 core: Reloading with SIGUSR1 if config never changed via admin (#7258) 2025-09-26 16:50:15 +00:00
Francis Lavoie 39ace450de logging: Adjustments to BufferedLog to keep logs in the correct order (#7257)
* logging: Adjustments to BufferedLog to keep logs in the correct order

* Ignore lints
2025-09-15 09:29:50 -06:00
Francis Lavoie 012b4b3d40 logging: Buffer the logs before config is loaded (#7245) 2025-09-10 16:03:52 +00:00
Bobby Dhillon 19ff47a63b cmd: Allow caddy adapt to read from stdin (#7163) 2025-08-06 20:04:28 -04:00
eveneast a76d005a94 Use maps.Copy for simpler map handling (#7009)
Signed-off-by: eveneast <qcqs@foxmail.com>
2025-05-13 15:16:47 -06:00
Matthew Holt 19876208c7 cmd: Promote undo maxProcs func to caller 2025-03-06 16:47:02 -07:00
Matthew Holt a686f7c346 cmd: Only set memory/CPU limits on run (fix #6879) 2025-03-06 15:11:38 -07:00
Aziz Rmadi fb72793269 cmd: Reject multiple configs for fmt command (#6717) 2024-12-04 05:43:52 -07:00
Matt Holt c8adb1b553 cmd: Better error handling when reloading (#6601)
* caddyhttp: Limit auto-HTTPS error logs to 100 domains

* Improve error message and increase error size limit
2024-10-01 20:31:30 -06:00
Aaron Paterson 4b1a9b6cc1 core: Implement socket activation listeners (#6573)
* caddy adapt for listen_protocols

* adapt listen_socket

* allow multiple listen sockets for port ranges and readd socket fd listen logic

* readd logic to start servers according to listener protocols

* gofmt

* adapt caddytest

* gosec

* fmt and rename listen to listenWithSocket

* fmt and rename listen to listenWithSocket

* more consistent error msg

* non unix listenReusableWithSocketFile

* remove unused func

* doc comment typo

* nonosec

* commit

* doc comments

* more doc comments

* comment was misleading, cardinality did not change

* addressesWithProtocols

* update test

* fd/ and fdgram/

* rm addr

* actually write...

* i guess we doin' "skip": now

* wrong var in placeholder

* wrong var in placeholder II

* update param name in comment

* dont save nil file pointers

* windows

* key -> parsedKey

* osx

* multiple default_bind with protocols

* check for h1 and h2 listener netw
2024-09-30 10:55:03 -06:00
WeidiDengandMohammed Al Sahaf 9ddb78fadc cmd: ignore exec.ErrDot when starting caddy in background (#6512)
Co-authored-by: Mohammed Al Sahaf <msaa1990@gmail.com>
2024-08-12 20:26:20 -06:00
Mohammed Al Sahaf 787f6b257f chore: check against errors of io/fs instead of os (#6011)
* chore: replace `os.ErrNotExist` with `fs.ErrNotExist`

* check against permission error from `io/fs` package
2024-01-02 08:48:55 +03:00
Francis LavoieandMohammed Al Sahaf 9c419f1e1a cmd: Fix exiting with custom status code, add caddy -v (#5874)
* Simplify variables for commands

* Add --envfile support for adapt command

* Carry custom status code for commands to os.Exit()

* cmd: add `-v` and `--version` to root caddy command

* Add `--envfile` to `caddy environ`, extract flag parsing to func

---------

Co-authored-by: Mohammed Al Sahaf <msaa1990@gmail.com>
2023-10-11 09:46:18 -06:00
Evan Van DamandFrancis Lavoie f2ab7099db cmd: Prevent overwriting existing env vars with --envfile (#5803)
Co-authored-by: Francis Lavoie <lavofr@gmail.com>
2023-09-07 02:19:24 +00:00
Jacob Gadikian d6f86cccf5 ci: use gci linter (#5708)
* use gofmput to format code

* use gci to format imports

* reconfigure gci

* linter autofixes

* rearrange imports a little

* export GOOS=windows golangci-lint run ./... --fix
2023-08-14 09:41:15 -06:00
d8135505d3 cmd: Require config for caddy validate (fix #5612) (#5614)
* Require config for caddy validate - fixes #5612

Signed-off-by: Pistasj <hi@pistasjis.net>

* Try making adjacent Caddyfile check its own function

Signed-off-by: Pistasj <hi@pistasjis.net>

* add Francis' suggestion

Co-authored-by: Francis Lavoie <lavofr@gmail.com>

* Refactor

* Fix borked commit, sigh

---------

Signed-off-by: Pistasj <hi@pistasjis.net>
Co-authored-by: Francis Lavoie <lavofr@gmail.com>
Co-authored-by: Matthew Holt <mholt@users.noreply.github.com>
2023-08-09 17:40:37 +00:00
Jacob Gadikian b32f265eca ci: Use gofumpt to format code (#5707) 2023-08-07 19:40:31 +00:00
EmilyandMatthew Holt 8d304a4566 cmd: Split unix sockets for admin endpoint addresses (#5696)
* cmd: fix cli when admin endpoint uses new unix socket permission format

Fixes a bug where the following Caddyfile

```Caddyfile
{
	admin unix/admin.sock|0660
}
```

and `caddy reload --config Caddyfile`
would throw the following error instead of reloading it:

```
INFO    using provided configuration    {"config_file": "Caddyfile", "config_adapter": ""}
Error: sending configuration to instance: performing request: Post "http://127.0.0.1/load": dial unix admin.sock|0660: connect: no such file or directory
[ERROR] exit status 1
```

---

This bug also affected `caddy start` and `caddy stop`.

* Move splitter function to internal

---------

Co-authored-by: Matthew Holt <mholt@users.noreply.github.com>
2023-08-06 00:09:16 +00:00
Matt Holt f66493efef core: Allow loopback hosts for admin endpoint (fix #5650) (#5664) 2023-08-02 11:13:52 -06:00
Matthew Holt 508cf2aa22 cmd: Create pidfile before config load (close #5477) 2023-04-03 11:57:16 -06:00
Francis Lavoie 79de6df93d cmd: Strict unmarshal for validate (#5383) 2023-02-22 11:39:40 -07:00
Emily Lange bf54892a73 cmd: make caddy fmt hints more clear (#5378) 2023-02-16 16:34:12 -07:00
Amis Shokoohi 94b8d56096 cmd: Add --envfile flag to validate command (#5350)
Fixes https://github.com/caddyserver/caddy/issues/5346
2023-01-31 16:27:35 -05:00
Amis Shokoohi 8c0b49bf03 cmd: fmt exit successfully after overwriting config file (#5351)
Fixes https://github.com/caddyserver/caddy/issues/5349
2023-01-31 11:24:44 -05:00
Y.Horie 5805b3ca11 cmd: caddy fmt return code is 1 if not formatted (#5297)
* cmd: Fix caddy fmt if input isn't formatted

* Fixes #5294
* return exit 1 with an error message

* cmd: Use formattingDifference for caddy fmt

* #5294
* expose caddyfile.formattingDifference
2023-01-21 21:28:37 -07:00
Matthew Holt 62b0685375 cmd: Improve error message if config missing 2022-09-14 23:24:16 -06:00
Mohammed Al Sahaf 258bc82b69 cmd: Migrate to spf13/cobra, remove single-dash arg support (#4565)
* cmd: migrate to spf13/cobra

* add `manpage` command

* limit Caddy tagline to root `help` only

* hard-code the manpage section to 8
2022-08-30 22:38:38 +00:00
Matt Holt 17ae5acaba cmd: Use newly-available version information (#4931) 2022-08-04 11:16:59 -06:00
Francis Lavoie 141872ed80 chore: Bump up to Go 1.19, minimum 1.18 (#4925) 2022-08-02 16:39:09 -04:00
Matthew Holt 07ed3e7c30 Minor docs clarification
Related to #4565
2022-07-29 16:56:02 -06:00
Francis Lavoie abad9bc256 cmd: Fix reload with stdin (#4900) 2022-07-20 18:14:33 -06:00
Francis Lavoie 2e4c09155a cmd: Fix unix socket addresses for admin API requests (#4742)
Fixes a regression in c2327161f7
2022-04-28 08:31:59 -06:00
Francis Lavoie 3a1e0dbf47 httpcaddyfile: Deprecate paths in site addresses; use zap logs (#4728) 2022-04-25 10:12:10 -06:00
Francis Lavoie 6512832f9f cmd: Add --diff option for caddy fmt (#4695) 2022-04-12 14:49:19 -04:00
Francis Lavoie 22d8edb984 cmd: Fix defaulting admin address if empty in config, fixes reload (#4674) 2022-04-03 12:04:33 -04:00
Matthew Holt c2327161f7 cmd: Set Origin header properly on API requests
Ref. https://caddy.community/t/bug-in-enforce-origin/15417
2022-03-19 22:51:32 -06:00
Francis Lavoie bbad6931e3 pki: Implement API endpoints for certs and caddy trust (#4443)
* admin: Implement /pki/certificates/<id> API

* pki: Lower "skip_install_trust" log level to INFO

See https://github.com/caddyserver/caddy/issues/4058#issuecomment-976132935

It's not necessary to warn about this, because this was an option explicitly configured by the user. Still useful to log, but we don't need to be so loud about it.

* cmd: Export functions needed for PKI app, return API response to caller

* pki: Rewrite `caddy trust` command to use new admin endpoint instead

* pki: Rewrite `caddy untrust` command to support using admin endpoint

* Refactor cmd and pki packages for determining admin API endpoint
2022-03-02 11:08:36 -07:00
Matthew Holt 1a7a78a1f2 cmd: Print error if fmt overwrite fails (fix #4524) 2022-01-16 17:30:14 -07:00
Francis Lavoie 062657d0d8 caddycmd: Add --skip-standard to list-modules command, quieter output (#4386)
* caddycmd: Add --skip-standard to list-modules command, quieter output

* caddycmd: Also quiet `caddy upgrade` output, redundant information
2021-10-18 12:19:04 -06:00
KallyDev c48fadc4a7 Move from deprecated ioutil to os and io packages (#4364) 2021-09-29 11:17:48 -06:00
peymaneh 9f6393c64c cmd: export CaddyVersion(), Commands() (#4316)
* cmd: Export CaddyVersion()

* cmd: Add getter Commands()
2021-09-01 18:08:02 -06:00
M. Ángel Jimeno 9e333c39da cmd: use net.ErrClosed for matching returned error (#4289)
Implements #3805
2021-08-18 12:58:19 -06:00