mirror of
https://github.com/caddyserver/caddy.git
synced 2026-05-25 16:22:36 -04:00
Compare commits
255 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a8cc5d1a7d | |||
| 8d304a4566 | |||
| 65e33fc1ee | |||
| 9f34383c02 | |||
| b07b198764 | |||
| 51b1bfb125 | |||
| c049bab458 | |||
| e2fc08bd34 | |||
| 4aa4f3ac70 | |||
| 1913930783 | |||
| cd486c25d1 | |||
| e198c605bd | |||
| f66493efef | |||
| 5c51c1db2c | |||
| da23501457 | |||
| 94749e119a | |||
| d7d16360d4 | |||
| 4df27a20c8 | |||
| 18c309b5fa | |||
| e041962b66 | |||
| f45a6de20d | |||
| b51dc5d5d0 | |||
| f857b32d65 | |||
| 4e36b4c9d1 | |||
| 27bc16abed | |||
| bbe1952a59 | |||
| 0e2c7e1d35 | |||
| 7ceef91295 | |||
| 5dec11f2a0 | |||
| 66114cb155 | |||
| 7914ba3573 | |||
| dfe17c33ef | |||
| 710824c3ce | |||
| d8ae801068 | |||
| 119e8794bc | |||
| 22927e278d | |||
| 7a69ae7571 | |||
| 2b2addebb8 | |||
| 9563666bfb | |||
| 806341e089 | |||
| 0468508e92 | |||
| 415d1e7b6f | |||
| 1a36b06cd4 | |||
| 398c12ae9b | |||
| 361946eb0c | |||
| 424ae0f420 | |||
| 4548b7de8e | |||
| 3b19aa2b5a | |||
| 6a41b62e70 | |||
| 2ddb717144 | |||
| 56af1ceb32 | |||
| 4ba03c9d38 | |||
| 078f130a51 | |||
| 9c180a5988 | |||
| 467b7e3a9c | |||
| 31d75acc9c | |||
| 9cde715525 | |||
| 942fbb37ec | |||
| cee4441cb1 | |||
| 5bd9c49042 | |||
| cdd3884b32 | |||
| 2615c9c524 | |||
| 5336bc0fb6 | |||
| 29452647d8 | |||
| bd34cb6b4e | |||
| 2d236ead3e | |||
| 38cb587e0f | |||
| ca14b6edd9 | |||
| cbf16f6d9e | |||
| 13a37688dc | |||
| e8352aef38 | |||
| 36546cd8b9 | |||
| 75b690d248 | |||
| 52d7335c2b | |||
| 96919acc9d | |||
| e96aafe1ca | |||
| a02ecb0f88 | |||
| 5ebb7d496d | |||
| cfc85ae8ca | |||
| faf0399e80 | |||
| 808b05c3b4 | |||
| 12b2f22092 | |||
| 571fc034d3 | |||
| bef1a739db | |||
| 0de6064c3b | |||
| 774f228868 | |||
| b19946f6af | |||
| 335cd2e8a4 | |||
| 48598e1f2a | |||
| cdce452edc | |||
| f3e8b9d95f | |||
| c8032867b1 | |||
| 3f20a7c9f3 | |||
| 1af419e7ec | |||
| f0e3981774 | |||
| 1c9ea0113d | |||
| 2b04e09fa7 | |||
| 3443a8a056 | |||
| 2943c41884 | |||
| 53b6fab125 | |||
| c6ac350a3b | |||
| b301a3df70 | |||
| 998c6e06a7 | |||
| 4636109ce1 | |||
| 205b142614 | |||
| ff35ba9ec3 | |||
| d8d87a378f | |||
| f8b59e77f8 | |||
| 508cf2aa22 | |||
| f9bd2d3e92 | |||
| b1366c7e46 | |||
| b6fe5d4b41 | |||
| 66e571e687 | |||
| 2b3046de36 | |||
| 1aef807c71 | |||
| e16a886814 | |||
| dd86171d67 | |||
| f5a13a4ab4 | |||
| 10b265d252 | |||
| 05e9974570 | |||
| 330be2d8c7 | |||
| 0cc49c053f | |||
| a7db0cfe55 | |||
| 2182270a2c | |||
| a7af7c486e | |||
| b97c76fb47 | |||
| 6cc3cbbc69 | |||
| 9e943319b4 | |||
| b420561737 | |||
| c05e3898b9 | |||
| b3f0cea2c3 | |||
| 94d41a9d86 | |||
| 99d47050e9 | |||
| 85375861f6 | |||
| f6bab8ba85 | |||
| 941eae5f61 | |||
| 096971e313 | |||
| f3379f650a | |||
| 960150bb03 | |||
| 9e6919550b | |||
| 167981d258 | |||
| 8cb1bb4af3 | |||
| e3909cc385 | |||
| be53e432fc | |||
| 79de6df93d | |||
| 8bc05e598d | |||
| bf54892a73 | |||
| 5ded580444 | |||
| 0db29e2ce9 | |||
| 4b119a475f | |||
| 90798f3eea | |||
| 536c28d4dc | |||
| c77a6bea66 | |||
| 12bcbe2c49 | |||
| f6f1d8fc89 | |||
| 8d3a1b8bcb | |||
| ac83b7e218 | |||
| e62b5fb586 | |||
| 94b8d56096 | |||
| 8c0b49bf03 | |||
| 201b9b41f9 | |||
| 0a3efd1641 | |||
| d73660f7c3 | |||
| 7f2a93e6c3 | |||
| e9d95ab29f | |||
| 962310204f | |||
| 98867ac346 | |||
| 5805b3ca11 | |||
| d6d7511699 | |||
| 8d6870fd06 | |||
| c38a040e85 | |||
| e8ad9b32c9 | |||
| 62e8b21724 | |||
| 223cbe3d0b | |||
| 66ce0c5c63 | |||
| 845bc4d50b | |||
| e450a7377b | |||
| d74f6fd967 | |||
| 55035d327a | |||
| 4e9ad50f65 | |||
| 05a4637489 | |||
| bd74f94496 | |||
| b40548ff61 | |||
| 4e54e48409 | |||
| b166b90083 | |||
| dac7cacd4d | |||
| af93517c2d | |||
| 3b724a2082 | |||
| 329af5ced9 | |||
| cd49847edb | |||
| d3d76d6ac2 | |||
| c3b5b1811c | |||
| 4fe5e64e46 | |||
| e10ed7b00d | |||
| fac35db9dc | |||
| bfaf2a8201 | |||
| fef9cb3e05 | |||
| d4a7d89f56 | |||
| ae77a56ac8 | |||
| 762b02789a | |||
| 6f8fe01da1 | |||
| ac96455a9a | |||
| ee7c92ec9b | |||
| 33fdea8f26 | |||
| 6efd1b3bb1 | |||
| 087f126cf4 | |||
| 1fa4cb7ba1 | |||
| f20a8e7aa0 | |||
| 798c4a3ba4 | |||
| 817470dd66 | |||
| bbe3663167 | |||
| ed503118dd | |||
| a3ae146cbd | |||
| 4bf6cb4199 | |||
| 72e7edda1f | |||
| a999b70727 | |||
| 1cd594963e | |||
| 6bad878a22 | |||
| 3e1fd2a8d4 | |||
| 33f60da9f2 | |||
| b4e28af953 | |||
| d46ba2e27f | |||
| 498f32bab9 | |||
| ed118f2b09 | |||
| 99ffe93388 | |||
| e07a267276 | |||
| e4fac1294f | |||
| 2153a81ec8 | |||
| ea58d51907 | |||
| 9e1d964bd6 | |||
| 2be56c526c | |||
| 01e192edc9 | |||
| 2808de1e30 | |||
| 253d97c93d | |||
| c28cd29fe7 | |||
| da24f57dac | |||
| b1d04f5b39 | |||
| fe91de67b6 | |||
| 9873ff9918 | |||
| 5e52bbb136 | |||
| fcdbc69fab | |||
| 2a8c458ffe | |||
| 037dc23cad | |||
| ab720fb768 | |||
| e2991eb019 | |||
| 897a38958c | |||
| 61822f129b | |||
| e3e8aabbcf | |||
| 013b510352 | |||
| d0556929a4 | |||
| b5727b9c44 | |||
| 7041970059 | |||
| e747a9bb12 | |||
| f7c1a51efb | |||
| eead00f54a |
+16
-6
@@ -1,7 +1,7 @@
|
||||
Contributing to Caddy
|
||||
=====================
|
||||
|
||||
Welcome! Thank you for choosing to be a part of our community. Caddy wouldn't be great without your involvement!
|
||||
Welcome! Thank you for choosing to be a part of our community. Caddy wouldn't be nearly as excellent without your involvement!
|
||||
|
||||
For starters, we invite you to join [the Caddy forum](https://caddy.community) where you can hang out with other Caddy users and developers.
|
||||
|
||||
@@ -35,19 +35,29 @@ Here are some of the expectations we have of contributors:
|
||||
|
||||
- **Keep related commits together in a PR.** We do want pull requests to be small, but you should also keep multiple related commits in the same PR if they rely on each other.
|
||||
|
||||
- **Write tests.** Tests are essential! Written properly, they ensure your change works, and that other changes in the future won't break your change. CI checks should pass.
|
||||
- **Write tests.** Good, automated tests are very valuable! Written properly, they ensure your change works, and that other changes in the future won't break your change. CI checks should pass.
|
||||
|
||||
- **Benchmarks should be included for optimizations.** Optimizations sometimes make code harder to read or have changes that are less than obvious. They should be proven with benchmarks or profiling.
|
||||
- **Benchmarks should be included for optimizations.** Optimizations sometimes make code harder to read or have changes that are less than obvious. They should be proven with benchmarks and profiling.
|
||||
|
||||
- **[Squash](http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html) insignificant commits.** Every commit should be significant. Commits which merely rewrite a comment or fix a typo can be combined into another commit that has more substance. Interactive rebase can do this, or a simpler way is `git reset --soft <diverging-commit>` then `git commit -s`.
|
||||
|
||||
- **Own your contributions.** Caddy is a growing project, and it's much better when individual contributors help maintain their change after it is merged.
|
||||
- **Be responsible for and maintain your contributions.** Caddy is a growing project, and it's much better when individual contributors help maintain their change after it is merged.
|
||||
|
||||
- **Use comments properly.** We expect good godoc comments for package-level functions, types, and values. Comments are also useful whenever the purpose for a line of code is not obvious.
|
||||
|
||||
- **Pull requests may still get closed.** The longer a PR stays open and idle, the more likely it is to be closed. If we haven't reviewed it in a while, it probably means the change is not a priority. Please don't take this personally, we're trying to balance a lot of tasks! If nobody else has commented or reacted to the PR, it likely means your change is useful only to you. The reality is this happens quite a bit. We don't tend to accept PRs that aren't generally helpful. For these reasons or others, the PR may get closed even after a review. We are not obligated to accept all proposed changes, even if the best justification we can give is something vague like, "It doesn't sit right." Sometimes PRs are just the wrong thing or the wrong time. Because it is open source, you can always build your own modified version of Caddy with a change you need, even if we reject it in the official repo.
|
||||
- **Pull requests may still get closed.** The longer a PR stays open and idle, the more likely it is to be closed. If we haven't reviewed it in a while, it probably means the change is not a priority. Please don't take this personally, we're trying to balance a lot of tasks! If nobody else has commented or reacted to the PR, it likely means your change is useful only to you. The reality is this happens quite a lot. We don't tend to accept PRs that aren't generally helpful. For these reasons or others, the PR may get closed even after a review. We are not obligated to accept all proposed changes, even if the best justification we can give is something vague like, "It doesn't sit right." Sometimes PRs are just the wrong thing or the wrong time. Because it is open source, you can always build your own modified version of Caddy with a change you need, even if we reject it in the official repo. Plus, because Caddy is extensible, it's possible your feature could make a great plugin instead!
|
||||
|
||||
We often grant [collaborator status](#collaborator-instructions) to contributors who author one or more significant, high-quality PRs that are merged into the code base!
|
||||
- **You certify that you wrote and comprehend the code you submit.** The Caddy project welcomes original contributions that comply with [our CLA](https://cla-assistant.io/caddyserver/caddy), meaning that authors must be able to certify that they created or have rights to the code they are contributing. In addition, we require that code is not simply copy-pasted from Q/A sites or AI language models without full comprehension and rigorous testing. In other words: contributors are allowed to refer to communities for assistance and use AI tools such as language models for inspiration, but code which originates from or is assisted by these resources MUST be:
|
||||
|
||||
- Licensed for you to freely share
|
||||
- Fully comprehended by you (be able to explain every line of code)
|
||||
- Verified by automated tests when feasible, or thorough manual tests otherwise
|
||||
|
||||
We have found that current language models (LLMs, like ChatGPT) may understand code syntax and even problem spaces to an extent, but often fail in subtle ways to convey true knowledge and produce correct algorithms. Integrated tools such as GitHub Copilot and Sourcegraph Cody may be used for inspiration, but code generated by these tools still needs to meet our criteria for licensing, human comprehension, and testing. These tools may be used to help write code comments and tests as long as you can certify they are accurate and correct. Note that it is often more trouble than it's worth to certify that Copilot (for example) is not giving you code that is possibly plagiarised, unlicensed, or licensed with incompatible terms -- as the Caddy project cannot accept such contributions. If that's too difficult for you (or impossible), then we recommend using these resources only for inspiration and write your own code. Ultimately, you (the contributor) are responsible for the code you're submitting.
|
||||
|
||||
As a courtesy to reviewers, we kindly ask that you disclose when contributing code that was generated by an AI tool or copied from another website so we can be aware of what to look for in code review.
|
||||
|
||||
We often grant [collaborator status](#collaborator-instructions) to contributors who author one or more significant, high-quality PRs that are merged into the code base.
|
||||
|
||||
|
||||
#### HOW TO MAKE A PULL REQUEST TO CADDY
|
||||
|
||||
+3
-3
@@ -7,7 +7,7 @@ The Caddy project would like to make sure that it stays on top of all practicall
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| 2.x | :white_check_mark: |
|
||||
| 2.x | ✔️ |
|
||||
| 1.x | :x: |
|
||||
| < 1.x | :x: |
|
||||
|
||||
@@ -24,7 +24,7 @@ We do not accept reports if the steps imply or require a compromised system or t
|
||||
|
||||
Client-side exploits are out of scope. In other words, it is not a bug in Caddy if the web browser does something unsafe, even if the downloaded content was served by Caddy. (Those kinds of exploits can generally be mitigated by proper configuration of HTTP headers.) As a general rule, the content served by Caddy is not considered in scope because content is configurable by the site owner or the associated web application.
|
||||
|
||||
Security bugs in code dependencies are out of scope. Instead, if a dependency has patched a relevant security bug, please feel free to open a public issue or pull request to update that dependency in our code.
|
||||
Security bugs in code dependencies (including Go's standard library) are out of scope. Instead, if a dependency has patched a relevant security bug, please feel free to open a public issue or pull request to update that dependency in our code.
|
||||
|
||||
|
||||
## Reporting a Vulnerability
|
||||
@@ -42,7 +42,7 @@ We'll need enough information to verify the bug and make a patch. To speed thing
|
||||
- Specific minimal steps to reproduce the issue from scratch
|
||||
- A working patch
|
||||
|
||||
Please DO NOT use containers, VMs, cloud instances or services, or any other complex infrastructure in your steps. Always prefer `curl` instead of web browsers.
|
||||
Please DO NOT use containers, VMs, cloud instances or services, or any other complex infrastructure in your steps. Always prefer `curl -v` instead of web browsers.
|
||||
|
||||
We consider publicly-registered domain names to be public information. This necessary in order to maintain the integrity of certificate transparency, public DNS, and other public trust systems. Do not redact domain names from your reports. The actual content of your domain name affects Caddy's behavior, so we need the exact domain name(s) to reproduce with, or your report will be ignored.
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
+27
-38
@@ -18,17 +18,22 @@ jobs:
|
||||
# Default is true, cancels jobs for other platforms in the matrix if one fails
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ ubuntu-latest, macos-latest, windows-latest ]
|
||||
go: [ '1.18', '1.19' ]
|
||||
os:
|
||||
- ubuntu-latest
|
||||
- macos-latest
|
||||
- windows-latest
|
||||
go:
|
||||
- '1.20'
|
||||
# - '1.21'
|
||||
|
||||
include:
|
||||
# Set the minimum Go patch version for the given Go minor
|
||||
# Usable via ${{ matrix.GO_SEMVER }}
|
||||
- go: '1.18'
|
||||
GO_SEMVER: '~1.18.4'
|
||||
- go: '1.20'
|
||||
GO_SEMVER: '~1.20.6'
|
||||
|
||||
- go: '1.19'
|
||||
GO_SEMVER: '~1.19.0'
|
||||
# - go: '1.21'
|
||||
# GO_SEMVER: '~1.21.0'
|
||||
|
||||
# Set some variables per OS, usable via ${{ matrix.VAR }}
|
||||
# CADDY_BIN_PATH: the path to the compiled Caddy binary, for artifact publishing
|
||||
@@ -48,15 +53,15 @@ jobs:
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Install Go
|
||||
uses: actions/setup-go@v3
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: ${{ matrix.GO_SEMVER }}
|
||||
check-latest: true
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# These tools would be useful if we later decide to reinvestigate
|
||||
# publishing test/coverage reports to some tool for easier consumption
|
||||
# - name: Install test and coverage analysis tools
|
||||
@@ -64,7 +69,7 @@ jobs:
|
||||
# go get github.com/axw/gocov/gocov
|
||||
# go get github.com/AlekSi/gocov-xml
|
||||
# go get -u github.com/jstemmer/go-junit-report
|
||||
# echo "::add-path::$(go env GOPATH)/bin"
|
||||
# echo "$(go env GOPATH)/bin" >> $GITHUB_PATH
|
||||
|
||||
- name: Print Go version and environment
|
||||
id: vars
|
||||
@@ -77,24 +82,7 @@ jobs:
|
||||
env
|
||||
printf "Git version: $(git version)\n\n"
|
||||
# Calculate the short SHA1 hash of the git commit
|
||||
echo "::set-output name=short_sha::$(git rev-parse --short HEAD)"
|
||||
|
||||
- name: Cache the build cache
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
# In order:
|
||||
# * Module download cache
|
||||
# * Build cache (Linux)
|
||||
# * Build cache (Mac)
|
||||
# * Build cache (Windows)
|
||||
path: |
|
||||
~/go/pkg/mod
|
||||
~/.cache/go-build
|
||||
~/Library/Caches/go-build
|
||||
~\AppData\Local\go-build
|
||||
key: ${{ runner.os }}-${{ matrix.go }}-go-ci-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-${{ matrix.go }}-go-ci
|
||||
echo "short_sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Get dependencies
|
||||
run: |
|
||||
@@ -109,7 +97,7 @@ jobs:
|
||||
go build -trimpath -ldflags="-w -s" -v
|
||||
|
||||
- name: Publish Build Artifact
|
||||
uses: actions/upload-artifact@v1
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: caddy_${{ runner.os }}_go${{ matrix.go }}_${{ steps.vars.outputs.short_sha }}
|
||||
path: ${{ matrix.CADDY_BIN_PATH }}
|
||||
@@ -123,7 +111,7 @@ jobs:
|
||||
run: |
|
||||
# (go test -v -coverprofile=cover-profile.out -race ./... 2>&1) > test-results/test-result.out
|
||||
go test -v -coverprofile="cover-profile.out" -short -race ./...
|
||||
# echo "::set-output name=status::$?"
|
||||
# echo "status=$?" >> $GITHUB_OUTPUT
|
||||
|
||||
# Relevant step if we reinvestigate publishing test/coverage reports
|
||||
# - name: Prepare coverage reports
|
||||
@@ -143,10 +131,10 @@ jobs:
|
||||
s390x-test:
|
||||
name: test (s390x on IBM Z)
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event.pull_request.head.repo.full_name == github.repository
|
||||
if: github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]'
|
||||
continue-on-error: true # August 2020: s390x VM is down due to weather and power issues
|
||||
steps:
|
||||
- name: Checkout code into the Go module directory
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
- name: Run Tests
|
||||
run: |
|
||||
@@ -156,25 +144,26 @@ jobs:
|
||||
short_sha=$(git rev-parse --short HEAD)
|
||||
|
||||
# The environment is fresh, so there's no point in keeping accepting and adding the key.
|
||||
rsync -arz -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" --progress --delete --exclude '.git' . caddy-ci@ci-s390x.caddyserver.com:/var/tmp/"$short_sha"
|
||||
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -t caddy-ci@ci-s390x.caddyserver.com "cd /var/tmp/$short_sha; go version; go env; printf "\n\n";CGO_ENABLED=0 go test -v ./..."
|
||||
rsync -arz -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" --progress --delete --exclude '.git' . "$CI_USER"@ci-s390x.caddyserver.com:/var/tmp/"$short_sha"
|
||||
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -t "$CI_USER"@ci-s390x.caddyserver.com "cd /var/tmp/$short_sha; go version; go env; printf "\n\n";CGO_ENABLED=0 go test -v ./..."
|
||||
test_result=$?
|
||||
|
||||
# There's no need leaving the files around
|
||||
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null caddy-ci@ci-s390x.caddyserver.com "rm -rf /var/tmp/'$short_sha'"
|
||||
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null "$CI_USER"@ci-s390x.caddyserver.com "rm -rf /var/tmp/'$short_sha'"
|
||||
|
||||
echo "Test exit code: $test_result"
|
||||
exit $test_result
|
||||
env:
|
||||
SSH_KEY: ${{ secrets.S390X_SSH_KEY }}
|
||||
CI_USER: ${{ secrets.CI_USER }}
|
||||
|
||||
goreleaser-check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- uses: goreleaser/goreleaser-action@v2
|
||||
- uses: goreleaser/goreleaser-action@v4
|
||||
with:
|
||||
version: latest
|
||||
args: check
|
||||
|
||||
@@ -15,20 +15,35 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
goos: ['android', 'linux', 'solaris', 'illumos', 'dragonfly', 'freebsd', 'openbsd', 'plan9', 'windows', 'darwin', 'netbsd']
|
||||
go: [ '1.19' ]
|
||||
goos:
|
||||
- 'android'
|
||||
- 'linux'
|
||||
- 'solaris'
|
||||
- 'illumos'
|
||||
- 'dragonfly'
|
||||
- 'freebsd'
|
||||
- 'openbsd'
|
||||
- 'plan9'
|
||||
- 'windows'
|
||||
- 'darwin'
|
||||
- 'netbsd'
|
||||
go:
|
||||
- '1.20'
|
||||
|
||||
include:
|
||||
# Set the minimum Go patch version for the given Go minor
|
||||
# Usable via ${{ matrix.GO_SEMVER }}
|
||||
- go: '1.19'
|
||||
GO_SEMVER: '~1.19.0'
|
||||
- go: '1.20'
|
||||
GO_SEMVER: '~1.20.6'
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
continue-on-error: true
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Install Go
|
||||
uses: actions/setup-go@v3
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: ${{ matrix.GO_SEMVER }}
|
||||
check-latest: true
|
||||
@@ -43,22 +58,6 @@ jobs:
|
||||
printf "\n\nSystem environment:\n\n"
|
||||
env
|
||||
|
||||
- name: Cache the build cache
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
# In order:
|
||||
# * Module download cache
|
||||
# * Build cache (Linux)
|
||||
path: |
|
||||
~/go/pkg/mod
|
||||
~/.cache/go-build
|
||||
key: cross-build-go${{ matrix.go }}-${{ matrix.goos }}-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
cross-build-go${{ matrix.go }}-${{ matrix.goos }}
|
||||
|
||||
- name: Checkout code into the Go module directory
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Run Build
|
||||
env:
|
||||
CGO_ENABLED: 0
|
||||
|
||||
@@ -10,26 +10,43 @@ on:
|
||||
- master
|
||||
- 2.*
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
# From https://github.com/golangci/golangci-lint-action
|
||||
golangci:
|
||||
permissions:
|
||||
contents: read # for actions/checkout to fetch code
|
||||
pull-requests: read # for golangci/golangci-lint-action to fetch pull requests
|
||||
name: lint
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
os:
|
||||
- ubuntu-latest
|
||||
- macos-latest
|
||||
- windows-latest
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-go@v3
|
||||
- uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: '~1.18.4'
|
||||
go-version: '~1.20.6'
|
||||
check-latest: true
|
||||
|
||||
# Workaround for https://github.com/golangci/golangci-lint-action/issues/135
|
||||
skip-pkg-cache: true
|
||||
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v3
|
||||
with:
|
||||
version: v1.47
|
||||
version: v1.53
|
||||
|
||||
# Workaround for https://github.com/golangci/golangci-lint-action/issues/135
|
||||
skip-pkg-cache: true
|
||||
|
||||
# Windows times out frequently after about 5m50s if we don't set a longer timeout.
|
||||
args: --timeout 10m
|
||||
|
||||
# Optional: show only new issues if it's a pull request. The default value is `false`.
|
||||
# only-new-issues: true
|
||||
|
||||
@@ -10,14 +10,16 @@ jobs:
|
||||
name: Release
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ ubuntu-latest ]
|
||||
go: [ '1.19' ]
|
||||
os:
|
||||
- ubuntu-latest
|
||||
go:
|
||||
- '1.20'
|
||||
|
||||
include:
|
||||
# Set the minimum Go patch version for the given Go minor
|
||||
# Usable via ${{ matrix.GO_SEMVER }}
|
||||
- go: '1.19'
|
||||
GO_SEMVER: '~1.19.0'
|
||||
- go: '1.20'
|
||||
GO_SEMVER: '~1.20.6'
|
||||
|
||||
runs-on: ${{ matrix.os }}
|
||||
# https://github.com/sigstore/cosign/issues/1258#issuecomment-1002251233
|
||||
@@ -29,17 +31,17 @@ jobs:
|
||||
contents: write
|
||||
|
||||
steps:
|
||||
- name: Install Go
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: ${{ matrix.GO_SEMVER }}
|
||||
check-latest: true
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install Go
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: ${{ matrix.GO_SEMVER }}
|
||||
check-latest: true
|
||||
|
||||
# Force fetch upstream tags -- because 65 minutes
|
||||
# tl;dr: actions/checkout@v3 runs this line:
|
||||
# git -c protocol.version=2 fetch --no-tags --prune --progress --no-recurse-submodules --depth=1 origin +ebc278ec98bb24f2852b61fde2a9bf2e3d83818b:refs/tags/
|
||||
@@ -61,8 +63,8 @@ jobs:
|
||||
go env
|
||||
printf "\n\nSystem environment:\n\n"
|
||||
env
|
||||
echo "::set-output name=version_tag::${GITHUB_REF/refs\/tags\//}"
|
||||
echo "::set-output name=short_sha::$(git rev-parse --short HEAD)"
|
||||
echo "version_tag=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_OUTPUT
|
||||
echo "short_sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
|
||||
|
||||
# Add "pip install" CLI tools to PATH
|
||||
echo ~/.local/bin >> $GITHUB_PATH
|
||||
@@ -74,10 +76,10 @@ jobs:
|
||||
TAG_MINOR=`echo ${TAG#v} | sed -e "s#$SEMVER_RE#\2#"`
|
||||
TAG_PATCH=`echo ${TAG#v} | sed -e "s#$SEMVER_RE#\3#"`
|
||||
TAG_SPECIAL=`echo ${TAG#v} | sed -e "s#$SEMVER_RE#\4#"`
|
||||
echo "::set-output name=tag_major::${TAG_MAJOR}"
|
||||
echo "::set-output name=tag_minor::${TAG_MINOR}"
|
||||
echo "::set-output name=tag_patch::${TAG_PATCH}"
|
||||
echo "::set-output name=tag_special::${TAG_SPECIAL}"
|
||||
echo "tag_major=${TAG_MAJOR}" >> $GITHUB_OUTPUT
|
||||
echo "tag_minor=${TAG_MINOR}" >> $GITHUB_OUTPUT
|
||||
echo "tag_patch=${TAG_PATCH}" >> $GITHUB_OUTPUT
|
||||
echo "tag_special=${TAG_SPECIAL}" >> $GITHUB_OUTPUT
|
||||
|
||||
# Cloudsmith CLI tooling for pushing releases
|
||||
# See https://help.cloudsmith.io/docs/cli
|
||||
@@ -94,18 +96,6 @@ jobs:
|
||||
# tags are only accepted if signed by Matt's key
|
||||
git verify-tag "${{ steps.vars.outputs.version_tag }}" || exit 1
|
||||
|
||||
- name: Cache the build cache
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
# In order:
|
||||
# * Module download cache
|
||||
# * Build cache (Linux)
|
||||
path: |
|
||||
~/go/pkg/mod
|
||||
~/.cache/go-build
|
||||
key: ${{ runner.os }}-go${{ matrix.go }}-release-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-go${{ matrix.go }}-release
|
||||
- name: Install Cosign
|
||||
uses: sigstore/cosign-installer@main
|
||||
- name: Cosign version
|
||||
@@ -116,10 +106,10 @@ jobs:
|
||||
run: syft version
|
||||
# GoReleaser will take care of publishing those artifacts into the release
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v2
|
||||
uses: goreleaser/goreleaser-action@v4
|
||||
with:
|
||||
version: latest
|
||||
args: release --rm-dist
|
||||
args: release --clean --timeout 60m
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAG: ${{ steps.vars.outputs.version_tag }}
|
||||
|
||||
@@ -10,14 +10,15 @@ jobs:
|
||||
name: Release Published
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ ubuntu-latest ]
|
||||
os:
|
||||
- ubuntu-latest
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
steps:
|
||||
|
||||
# See https://github.com/peter-evans/repository-dispatch
|
||||
- name: Trigger event on caddyserver/dist
|
||||
uses: peter-evans/repository-dispatch@v1
|
||||
uses: peter-evans/repository-dispatch@v2
|
||||
with:
|
||||
token: ${{ secrets.REPO_DISPATCH_TOKEN }}
|
||||
repository: caddyserver/dist
|
||||
@@ -25,7 +26,7 @@ jobs:
|
||||
client-payload: '{"tag": "${{ github.event.release.tag_name }}"}'
|
||||
|
||||
- name: Trigger event on caddyserver/caddy-docker
|
||||
uses: peter-evans/repository-dispatch@v1
|
||||
uses: peter-evans/repository-dispatch@v2
|
||||
with:
|
||||
token: ${{ secrets.REPO_DISPATCH_TOKEN }}
|
||||
repository: caddyserver/caddy-docker
|
||||
|
||||
@@ -11,6 +11,7 @@ Caddyfile.*
|
||||
# build artifacts and helpers
|
||||
cmd/caddy/caddy
|
||||
cmd/caddy/caddy.exe
|
||||
cmd/caddy/tmp/*.exe
|
||||
|
||||
# mac specific
|
||||
.DS_Store
|
||||
|
||||
+4
-3
@@ -7,7 +7,6 @@ linters:
|
||||
disable-all: true
|
||||
enable:
|
||||
- bodyclose
|
||||
- deadcode
|
||||
- errcheck
|
||||
- gofmt
|
||||
- goimports
|
||||
@@ -18,11 +17,9 @@ linters:
|
||||
- misspell
|
||||
- prealloc
|
||||
- staticcheck
|
||||
- structcheck
|
||||
- typecheck
|
||||
- unconvert
|
||||
- unused
|
||||
- varcheck
|
||||
# these are implicitly disabled:
|
||||
# - asciicheck
|
||||
# - depguard
|
||||
@@ -96,3 +93,7 @@ issues:
|
||||
text: "G404" # G404: Insecure random number source (rand)
|
||||
linters:
|
||||
- gosec
|
||||
- path: modules/caddyhttp/reverseproxy/streaming.go
|
||||
text: "G404" # G404: Insecure random number source (rand)
|
||||
linters:
|
||||
- gosec
|
||||
|
||||
+55
-6
@@ -4,6 +4,9 @@ before:
|
||||
# This is so we can run goreleaser on tag without Git complaining of being dirty. The main.go in cmd/caddy directory
|
||||
# cannot be built within that directory due to changes necessary for the build causing Git to be dirty, which
|
||||
# subsequently causes gorleaser to refuse running.
|
||||
- rm -rf caddy-build caddy-dist vendor
|
||||
# vendor Caddy deps
|
||||
- go mod vendor
|
||||
- mkdir -p caddy-build
|
||||
- cp cmd/caddy/main.go caddy-build/main.go
|
||||
- /bin/sh -c 'cd ./caddy-build && go mod init caddy'
|
||||
@@ -13,6 +16,8 @@ before:
|
||||
# as of Go 1.16, `go` commands no longer automatically change go.{mod,sum}. We now have to explicitly
|
||||
# run `go mod tidy`. The `/bin/sh -c '...'` is because goreleaser can't find cd in PATH without shell invocation.
|
||||
- /bin/sh -c 'cd ./caddy-build && go mod tidy'
|
||||
# vendor the deps of the prepared to-build module
|
||||
- /bin/sh -c 'cd ./caddy-build && go mod vendor'
|
||||
- git clone --depth 1 https://github.com/caddyserver/dist caddy-dist
|
||||
- mkdir -p caddy-dist/man
|
||||
- go mod download
|
||||
@@ -65,24 +70,69 @@ builds:
|
||||
- -mod=readonly
|
||||
ldflags:
|
||||
- -s -w
|
||||
|
||||
signs:
|
||||
- cmd: cosign
|
||||
signature: "${artifact}.sig"
|
||||
certificate: '{{ trimsuffix (trimsuffix .Env.artifact ".zip") ".tar.gz" }}.pem'
|
||||
args: ["sign-blob", "--output-signature=${signature}", "--output-certificate", "${certificate}", "${artifact}"]
|
||||
args: ["sign-blob", "--yes", "--output-signature=${signature}", "--output-certificate", "${certificate}", "${artifact}"]
|
||||
artifacts: all
|
||||
|
||||
sboms:
|
||||
- artifacts: binary
|
||||
documents:
|
||||
- '{{ .Binary }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}{{if .Arm}}v{{ .Arm }}{{end}}.sbom'
|
||||
- >-
|
||||
{{ .ProjectName }}_
|
||||
{{- .Version }}_
|
||||
{{- if eq .Os "darwin" }}mac{{ else }}{{ .Os }}{{ end }}_
|
||||
{{- .Arch }}
|
||||
{{- with .Arm }}v{{ . }}{{ end }}
|
||||
{{- with .Mips }}_{{ . }}{{ end }}
|
||||
{{- if not (eq .Amd64 "v1") }}{{ .Amd64 }}{{ end }}.sbom
|
||||
cmd: syft
|
||||
args: ["$artifact", "--file", "${document}", "--output", "cyclonedx-json"]
|
||||
|
||||
archives:
|
||||
- format_overrides:
|
||||
- id: default
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
format: zip
|
||||
replacements:
|
||||
darwin: mac
|
||||
name_template: >-
|
||||
{{ .ProjectName }}_
|
||||
{{- .Version }}_
|
||||
{{- if eq .Os "darwin" }}mac{{ else }}{{ .Os }}{{ end }}_
|
||||
{{- .Arch }}
|
||||
{{- with .Arm }}v{{ . }}{{ end }}
|
||||
{{- with .Mips }}_{{ . }}{{ end }}
|
||||
{{- if not (eq .Amd64 "v1") }}{{ .Amd64 }}{{ end }}
|
||||
|
||||
# packge the 'caddy-build' directory into a tarball,
|
||||
# allowing users to build the exact same set of files as ours.
|
||||
- id: source
|
||||
meta: true
|
||||
name_template: "{{ .ProjectName }}_{{ .Version }}_buildable-artifact"
|
||||
files:
|
||||
- src: LICENSE
|
||||
dst: ./LICENSE
|
||||
- src: README.md
|
||||
dst: ./README.md
|
||||
- src: AUTHORS
|
||||
dst: ./AUTHORS
|
||||
- src: ./caddy-build
|
||||
dst: ./
|
||||
|
||||
source:
|
||||
enabled: true
|
||||
name_template: '{{ .ProjectName }}_{{ .Version }}_src'
|
||||
format: 'tar.gz'
|
||||
|
||||
# Additional files/template/globs you want to add to the source archive.
|
||||
#
|
||||
# Default: empty.
|
||||
files:
|
||||
- vendor
|
||||
|
||||
|
||||
checksum:
|
||||
algorithm: sha512
|
||||
|
||||
@@ -127,7 +177,6 @@ nfpms:
|
||||
preremove: ./caddy-dist/scripts/preremove.sh
|
||||
postremove: ./caddy-dist/scripts/postremove.sh
|
||||
|
||||
|
||||
release:
|
||||
github:
|
||||
owner: caddyserver
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
<p align="center">
|
||||
<a href="https://caddyserver.com"><img src="https://user-images.githubusercontent.com/1128849/36338535-05fb646a-136f-11e8-987b-e6901e717d5a.png" alt="Caddy" width="450"></a>
|
||||
<a href="https://caddyserver.com">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://user-images.githubusercontent.com/1128849/210187358-e2c39003-9a5e-4dd5-a783-6deb6483ee72.svg">
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://user-images.githubusercontent.com/1128849/210187356-dfb7f1c5-ac2e-43aa-bb23-fc014280ae1f.svg">
|
||||
<img src="https://user-images.githubusercontent.com/1128849/210187356-dfb7f1c5-ac2e-43aa-bb23-fc014280ae1f.svg" alt="Caddy" width="550">
|
||||
</picture>
|
||||
</a>
|
||||
<br>
|
||||
<h3 align="center">a <a href="https://zerossl.com"><img src="https://caddyserver.com/resources/images/zerossl-logo.svg" height="28" valign="middle"></a> project</h3>
|
||||
<h3 align="center">a <a href="https://zerossl.com"><img src="https://user-images.githubusercontent.com/55066419/208327323-2770dc16-ec09-43a0-9035-c5b872c2ad7f.svg" height="28" style="vertical-align: -7.7px" valign="middle"></a> project</h3>
|
||||
</p>
|
||||
<hr>
|
||||
<h3 align="center">Every site on HTTPS</h3>
|
||||
<p align="center">Caddy is an extensible server platform that uses TLS by default.</p>
|
||||
<p align="center">
|
||||
<a href="https://github.com/caddyserver/caddy/actions?query=workflow%3ACross-Platform"><img src="https://github.com/caddyserver/caddy/workflows/Cross-Platform/badge.svg"></a>
|
||||
<a href="https://github.com/caddyserver/caddy/actions/workflows/ci.yml"><img src="https://github.com/caddyserver/caddy/actions/workflows/ci.yml/badge.svg"></a>
|
||||
<a href="https://pkg.go.dev/github.com/caddyserver/caddy/v2"><img src="https://img.shields.io/badge/godoc-reference-%23007d9c.svg"></a>
|
||||
<br>
|
||||
<a href="https://twitter.com/caddyserver" title="@caddyserver on Twitter"><img src="https://img.shields.io/badge/twitter-@caddyserver-55acee.svg" alt="@caddyserver on Twitter"></a>
|
||||
@@ -40,7 +46,13 @@
|
||||
<p align="center">
|
||||
<b>Powered by</b>
|
||||
<br>
|
||||
<a href="https://github.com/caddyserver/certmagic"><img src="https://user-images.githubusercontent.com/1128849/49704830-49d37200-fbd5-11e8-8385-767e0cd033c3.png" alt="CertMagic" width="250"></a>
|
||||
<a href="https://github.com/caddyserver/certmagic">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://user-images.githubusercontent.com/55066419/206946718-740b6371-3df3-4d72-a822-47e4c48af999.png">
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://user-images.githubusercontent.com/1128849/49704830-49d37200-fbd5-11e8-8385-767e0cd033c3.png">
|
||||
<img src="https://user-images.githubusercontent.com/1128849/49704830-49d37200-fbd5-11e8-8385-767e0cd033c3.png" alt="CertMagic" width="250">
|
||||
</picture>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
|
||||
@@ -58,7 +70,7 @@
|
||||
- **Stays up when other servers go down** due to TLS/OCSP/certificate-related issues
|
||||
- **Production-ready** after serving trillions of requests and managing millions of TLS certificates
|
||||
- **Scales to hundreds of thousands of sites** as proven in production
|
||||
- **HTTP/1.1, HTTP/2, and HTTP/3** supported all by default
|
||||
- **HTTP/1.1, HTTP/2, and HTTP/3** all supported by default
|
||||
- **Highly extensible** [modular architecture](https://caddyserver.com/docs/architecture) lets Caddy do anything without bloat
|
||||
- **Runs anywhere** with **no external dependencies** (not even libc)
|
||||
- Written in Go, a language with higher **memory safety guarantees** than other servers
|
||||
@@ -75,10 +87,10 @@ See [our online documentation](https://caddyserver.com/docs/install) for other i
|
||||
|
||||
Requirements:
|
||||
|
||||
- [Go 1.18 or newer](https://golang.org/dl/)
|
||||
- [Go 1.20 or newer](https://golang.org/dl/)
|
||||
|
||||
### For development
|
||||
|
||||
|
||||
_**Note:** These steps [will not embed proper version information](https://github.com/golang/go/issues/29228). For that, please follow the instructions in the next section._
|
||||
|
||||
```bash
|
||||
@@ -185,4 +197,4 @@ Matthew Holt began developing Caddy in 2014 while studying computer science at B
|
||||
|
||||
Caddy is a project of [ZeroSSL](https://zerossl.com), a Stack Holdings company.
|
||||
|
||||
Debian package repository hosting is graciously provided by [Cloudsmith](https://cloudsmith.com). Cloudsmith is the only fully hosted, cloud-native, universal package management solution, that enables your organization to create, store and share packages in any format, to any place, with total confidence.
|
||||
Debian package repository hosting is graciously provided by [Cloudsmith](https://cloudsmith.com). Cloudsmith is the only fully hosted, cloud-native, universal package management solution, that enables your organization to create, store and share packages in any format, to any place, with total confidence.
|
||||
|
||||
@@ -46,6 +46,17 @@ import (
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
func init() {
|
||||
// The hard-coded default `DefaultAdminListen` can be overidden
|
||||
// by setting the `CADDY_ADMIN` environment variable.
|
||||
// The environment variable may be used by packagers to change
|
||||
// the default admin address to something more appropriate for
|
||||
// that platform. See #5317 for discussion.
|
||||
if env, exists := os.LookupEnv("CADDY_ADMIN"); exists {
|
||||
DefaultAdminListen = env
|
||||
}
|
||||
}
|
||||
|
||||
// AdminConfig configures Caddy's API endpoint, which is used
|
||||
// to manage Caddy while it is running.
|
||||
type AdminConfig struct {
|
||||
@@ -57,7 +68,14 @@ type AdminConfig struct {
|
||||
|
||||
// The address to which the admin endpoint's listener should
|
||||
// bind itself. Can be any single network address that can be
|
||||
// parsed by Caddy. Default: localhost:2019
|
||||
// parsed by Caddy. Accepts placeholders.
|
||||
// Default: the value of the `CADDY_ADMIN` environment variable,
|
||||
// or `localhost:2019` otherwise.
|
||||
//
|
||||
// Remember: When changing this value through a config reload,
|
||||
// be sure to use the `--address` CLI flag to specify the current
|
||||
// admin address if the currently-running admin endpoint is not
|
||||
// the default address.
|
||||
Listen string `json:"listen,omitempty"`
|
||||
|
||||
// If true, CORS headers will be emitted, and requests to the
|
||||
@@ -156,7 +174,7 @@ type IdentityConfig struct {
|
||||
//
|
||||
// EXPERIMENTAL: Subject to change.
|
||||
type RemoteAdmin struct {
|
||||
// The address on which to start the secure listener.
|
||||
// The address on which to start the secure listener. Accepts placeholders.
|
||||
// Default: :2021
|
||||
Listen string `json:"listen,omitempty"`
|
||||
|
||||
@@ -300,7 +318,32 @@ func (admin AdminConfig) allowedOrigins(addr NetworkAddress) []*url.URL {
|
||||
// messages. If the requested URI does not include an Internet host
|
||||
// name for the service being requested, then the Host header field MUST
|
||||
// be given with an empty value."
|
||||
//
|
||||
// UPDATE July 2023: Go broke this by patching a minor security bug in 1.20.6.
|
||||
// Understandable, but frustrating. See:
|
||||
// https://github.com/golang/go/issues/60374
|
||||
// See also the discussion here:
|
||||
// https://github.com/golang/go/issues/61431
|
||||
//
|
||||
// We can no longer conform to RFC 2616 Section 14.26 from either Go or curl
|
||||
// in purity. (Curl allowed no host between 7.40 and 7.50, but now requires a
|
||||
// bogus host; see https://superuser.com/a/925610.) If we disable Host/Origin
|
||||
// security checks, the infosec community assures me that it is secure to do
|
||||
// so, because:
|
||||
// 1) Browsers do not allow access to unix sockets
|
||||
// 2) DNS is irrelevant to unix sockets
|
||||
//
|
||||
// I am not quite ready to trust either of those external factors, so instead
|
||||
// of disabling Host/Origin checks, we now allow specific Host values when
|
||||
// accessing the admin endpoint over unix sockets. I definitely don't trust
|
||||
// DNS (e.g. I don't trust 'localhost' to always resolve to the local host),
|
||||
// and IP shouldn't even be used, but if it is for some reason, I think we can
|
||||
// at least be reasonably assured that 127.0.0.1 and ::1 route to the local
|
||||
// machine, meaning that a hypothetical browser origin would have to be on the
|
||||
// local machine as well.
|
||||
uniqueOrigins[""] = struct{}{}
|
||||
uniqueOrigins["127.0.0.1"] = struct{}{}
|
||||
uniqueOrigins["::1"] = struct{}{}
|
||||
} else {
|
||||
uniqueOrigins[net.JoinHostPort("localhost", addr.port())] = struct{}{}
|
||||
uniqueOrigins[net.JoinHostPort("::1", addr.port())] = struct{}{}
|
||||
@@ -382,7 +425,7 @@ func replaceLocalAdminServer(cfg *Config) error {
|
||||
|
||||
handler := cfg.Admin.newAdminHandler(addr, false)
|
||||
|
||||
ln, err := Listen(addr.Network, addr.JoinHostPort(0))
|
||||
ln, err := addr.Listen(context.TODO(), 0, net.ListenConfig{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -403,7 +446,7 @@ func replaceLocalAdminServer(cfg *Config) error {
|
||||
serverMu.Lock()
|
||||
server := localAdminServer
|
||||
serverMu.Unlock()
|
||||
if err := server.Serve(ln); !errors.Is(err, http.ErrServerClosed) {
|
||||
if err := server.Serve(ln.(net.Listener)); !errors.Is(err, http.ErrServerClosed) {
|
||||
adminLogger.Error("admin server shutdown for unknown reason", zap.Error(err))
|
||||
}
|
||||
}()
|
||||
@@ -549,10 +592,11 @@ func replaceRemoteAdminServer(ctx Context, cfg *Config) error {
|
||||
serverMu.Unlock()
|
||||
|
||||
// start listener
|
||||
ln, err := Listen(addr.Network, addr.JoinHostPort(0))
|
||||
lnAny, err := addr.Listen(ctx, 0, net.ListenConfig{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ln := lnAny.(net.Listener)
|
||||
ln = tls.NewListener(ln, tlsConfig)
|
||||
|
||||
go func() {
|
||||
@@ -571,12 +615,13 @@ func replaceRemoteAdminServer(ctx Context, cfg *Config) error {
|
||||
}
|
||||
|
||||
func (ident *IdentityConfig) certmagicConfig(logger *zap.Logger, makeCache bool) *certmagic.Config {
|
||||
var cmCfg *certmagic.Config
|
||||
if ident == nil {
|
||||
// user might not have configured identity; that's OK, we can still make a
|
||||
// certmagic config, although it'll be mostly useless for remote management
|
||||
ident = new(IdentityConfig)
|
||||
}
|
||||
cmCfg := &certmagic.Config{
|
||||
template := certmagic.Config{
|
||||
Storage: DefaultStorage, // do not act as part of a cluster (this is for the server's local identity)
|
||||
Logger: logger,
|
||||
Issuers: ident.issuers,
|
||||
@@ -586,9 +631,11 @@ func (ident *IdentityConfig) certmagicConfig(logger *zap.Logger, makeCache bool)
|
||||
GetConfigForCert: func(certmagic.Certificate) (*certmagic.Config, error) {
|
||||
return cmCfg, nil
|
||||
},
|
||||
Logger: logger.Named("cache"),
|
||||
})
|
||||
}
|
||||
return certmagic.New(identityCertCache, *cmCfg)
|
||||
cmCfg = certmagic.New(identityCertCache, template)
|
||||
return cmCfg
|
||||
}
|
||||
|
||||
// IdentityCredentials returns this instance's configured, managed identity credentials
|
||||
@@ -994,9 +1041,9 @@ func handleConfigID(w http.ResponseWriter, r *http.Request) error {
|
||||
id := parts[2]
|
||||
|
||||
// map the ID to the expanded path
|
||||
currentCtxMu.RLock()
|
||||
rawCfgMu.RLock()
|
||||
expanded, ok := rawCfgIndex[id]
|
||||
defer currentCtxMu.RUnlock()
|
||||
rawCfgMu.RUnlock()
|
||||
if !ok {
|
||||
return APIError{
|
||||
HTTPStatus: http.StatusNotFound,
|
||||
@@ -1246,7 +1293,10 @@ func (e APIError) Error() string {
|
||||
// parseAdminListenAddr extracts a singular listen address from either addr
|
||||
// or defaultAddr, returning the network and the address of the listener.
|
||||
func parseAdminListenAddr(addr string, defaultAddr string) (NetworkAddress, error) {
|
||||
input := addr
|
||||
input, err := NewReplacer().ReplaceOrErr(addr, true, true)
|
||||
if err != nil {
|
||||
return NetworkAddress{}, fmt.Errorf("replacing listen address: %v", err)
|
||||
}
|
||||
if input == "" {
|
||||
input = defaultAddr
|
||||
}
|
||||
|
||||
@@ -156,8 +156,8 @@ func changeConfig(method, path string, input []byte, ifMatchHeader string, force
|
||||
return fmt.Errorf("method not allowed")
|
||||
}
|
||||
|
||||
currentCtxMu.Lock()
|
||||
defer currentCtxMu.Unlock()
|
||||
rawCfgMu.Lock()
|
||||
defer rawCfgMu.Unlock()
|
||||
|
||||
if ifMatchHeader != "" {
|
||||
// expect the first and last character to be quotes
|
||||
@@ -257,8 +257,8 @@ func changeConfig(method, path string, input []byte, ifMatchHeader string, force
|
||||
// readConfig traverses the current config to path
|
||||
// and writes its JSON encoding to out.
|
||||
func readConfig(path string, out io.Writer) error {
|
||||
currentCtxMu.RLock()
|
||||
defer currentCtxMu.RUnlock()
|
||||
rawCfgMu.RLock()
|
||||
defer rawCfgMu.RUnlock()
|
||||
return unsyncedConfigAccess(http.MethodGet, path, nil, out)
|
||||
}
|
||||
|
||||
@@ -305,7 +305,7 @@ func indexConfigObjects(ptr any, configPath string, index map[string]string) err
|
||||
// it as the new config, replacing any other current config.
|
||||
// It does NOT update the raw config state, as this is a
|
||||
// lower-level function; most callers will want to use Load
|
||||
// instead. A write lock on currentCtxMu is required! If
|
||||
// instead. A write lock on rawCfgMu is required! If
|
||||
// allowPersist is false, it will not be persisted to disk,
|
||||
// even if it is configured to.
|
||||
func unsyncedDecodeAndRun(cfgJSON []byte, allowPersist bool) error {
|
||||
@@ -314,7 +314,7 @@ func unsyncedDecodeAndRun(cfgJSON []byte, allowPersist bool) error {
|
||||
strippedCfgJSON := RemoveMetaFields(cfgJSON)
|
||||
|
||||
var newCfg *Config
|
||||
err := strictUnmarshalJSON(strippedCfgJSON, &newCfg)
|
||||
err := StrictUnmarshalJSON(strippedCfgJSON, &newCfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -340,8 +340,10 @@ func unsyncedDecodeAndRun(cfgJSON []byte, allowPersist bool) error {
|
||||
}
|
||||
|
||||
// swap old context (including its config) with the new one
|
||||
currentCtxMu.Lock()
|
||||
oldCtx := currentCtx
|
||||
currentCtx = ctx
|
||||
currentCtxMu.Unlock()
|
||||
|
||||
// Stop, Cleanup each old app
|
||||
unsyncedStop(oldCtx)
|
||||
@@ -627,22 +629,35 @@ type ConfigLoader interface {
|
||||
// stop the others. Stop should only be called
|
||||
// if not replacing with a new config.
|
||||
func Stop() error {
|
||||
currentCtxMu.RLock()
|
||||
ctx := currentCtx
|
||||
currentCtxMu.RUnlock()
|
||||
|
||||
rawCfgMu.Lock()
|
||||
unsyncedStop(ctx)
|
||||
|
||||
currentCtxMu.Lock()
|
||||
defer currentCtxMu.Unlock()
|
||||
unsyncedStop(currentCtx)
|
||||
currentCtx = Context{}
|
||||
currentCtxMu.Unlock()
|
||||
|
||||
rawCfgJSON = nil
|
||||
rawCfgIndex = nil
|
||||
rawCfg[rawConfigKey] = nil
|
||||
rawCfgMu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// unsyncedStop stops cfg from running, but has
|
||||
// no locking around cfg. It is a no-op if cfg is
|
||||
// nil. If any app returns an error when stopping,
|
||||
// unsyncedStop stops ctx from running, but has
|
||||
// no locking around ctx. It is a no-op if ctx has a
|
||||
// nil cfg. If any app returns an error when stopping,
|
||||
// it is logged and the function continues stopping
|
||||
// the next app. This function assumes all apps in
|
||||
// cfg were successfully started first.
|
||||
// ctx were successfully started first.
|
||||
//
|
||||
// A lock on rawCfgMu is required, even though this
|
||||
// function does not access rawCfg, that lock
|
||||
// synchronizes the stop/start of apps.
|
||||
func unsyncedStop(ctx Context) {
|
||||
if ctx.cfg == nil {
|
||||
return
|
||||
@@ -824,6 +839,20 @@ func InstanceID() (uuid.UUID, error) {
|
||||
return uuid.ParseBytes(uuidFileBytes)
|
||||
}
|
||||
|
||||
// CustomVersion is an optional string that overrides Caddy's
|
||||
// reported version. It can be helpful when downstream packagers
|
||||
// need to manually set Caddy's version. If no other version
|
||||
// information is available, the short form version (see
|
||||
// Version()) will be set to CustomVersion, and the full version
|
||||
// will include CustomVersion at the beginning.
|
||||
//
|
||||
// Set this variable during `go build` with `-ldflags`:
|
||||
//
|
||||
// -ldflags '-X github.com/caddyserver/caddy/v2.CustomVersion=v2.6.2'
|
||||
//
|
||||
// for example.
|
||||
var CustomVersion string
|
||||
|
||||
// Version returns the Caddy version in a simple/short form, and
|
||||
// a full version string. The short form will not have spaces and
|
||||
// is intended for User-Agent strings and similar, but may be
|
||||
@@ -833,8 +862,10 @@ func InstanceID() (uuid.UUID, error) {
|
||||
// build info provided by go.mod dependencies; then it tries to
|
||||
// get info from embedded VCS information, which requires having
|
||||
// built Caddy from a git repository. If no version is available,
|
||||
// this function returns "(devel)" becaise Go uses that, but for
|
||||
// the simple form we change it to "unknown".
|
||||
// this function returns "(devel)" because Go uses that, but for
|
||||
// the simple form we change it to "unknown". If still no version
|
||||
// is available (e.g. no VCS repo), then it will use CustomVersion;
|
||||
// CustomVersion is always prepended to the full version string.
|
||||
//
|
||||
// See relevant Go issues: https://github.com/golang/go/issues/29228
|
||||
// and https://github.com/golang/go/issues/50603.
|
||||
@@ -848,13 +879,21 @@ func Version() (simple, full string) {
|
||||
// bi.Main... hopefully.
|
||||
var module *debug.Module
|
||||
bi, ok := debug.ReadBuildInfo()
|
||||
if ok {
|
||||
// find the Caddy module in the dependency list
|
||||
for _, dep := range bi.Deps {
|
||||
if dep.Path == ImportPath {
|
||||
module = dep
|
||||
break
|
||||
}
|
||||
if !ok {
|
||||
if CustomVersion != "" {
|
||||
full = CustomVersion
|
||||
simple = CustomVersion
|
||||
return
|
||||
}
|
||||
full = "unknown"
|
||||
simple = "unknown"
|
||||
return
|
||||
}
|
||||
// find the Caddy module in the dependency list
|
||||
for _, dep := range bi.Deps {
|
||||
if dep.Path == ImportPath {
|
||||
module = dep
|
||||
break
|
||||
}
|
||||
}
|
||||
if module != nil {
|
||||
@@ -910,8 +949,22 @@ func Version() (simple, full string) {
|
||||
}
|
||||
}
|
||||
|
||||
if full == "" {
|
||||
if CustomVersion != "" {
|
||||
full = CustomVersion
|
||||
} else {
|
||||
full = "unknown"
|
||||
}
|
||||
} else if CustomVersion != "" {
|
||||
full = CustomVersion + " " + full
|
||||
}
|
||||
|
||||
if simple == "" || simple == "(devel)" {
|
||||
simple = "unknown"
|
||||
if CustomVersion != "" {
|
||||
simple = CustomVersion
|
||||
} else {
|
||||
simple = "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
@@ -931,14 +984,12 @@ type CtxKey string
|
||||
|
||||
// This group of variables pertains to the current configuration.
|
||||
var (
|
||||
// currentCtxMu protects everything in this var block.
|
||||
currentCtxMu sync.RWMutex
|
||||
|
||||
// currentCtx is the root context for the currently-running
|
||||
// configuration, which can be accessed through this value.
|
||||
// If the Config contained in this value is not nil, then
|
||||
// a config is currently active/running.
|
||||
currentCtx Context
|
||||
currentCtx Context
|
||||
currentCtxMu sync.RWMutex
|
||||
|
||||
// rawCfg is the current, generic-decoded configuration;
|
||||
// we initialize it as a map with one field ("config")
|
||||
@@ -956,6 +1007,10 @@ var (
|
||||
// rawCfgIndex is the map of user-assigned ID to expanded
|
||||
// path, for converting /id/ paths to /config/ paths.
|
||||
rawCfgIndex map[string]string
|
||||
|
||||
// rawCfgMu protects all the rawCfg fields and also
|
||||
// essentially synchronizes config changes/reloads.
|
||||
rawCfgMu sync.RWMutex
|
||||
)
|
||||
|
||||
// errSameConfig is returned if the new config is the same
|
||||
|
||||
@@ -54,7 +54,7 @@ func (a Adapter) Adapt(body []byte, options map[string]any) ([]byte, []caddyconf
|
||||
|
||||
// lint check: see if input was properly formatted; sometimes messy files files parse
|
||||
// successfully but result in logical errors (the Caddyfile is a bad format, I'm sorry)
|
||||
if warning, different := formattingDifference(filename, body); different {
|
||||
if warning, different := FormattingDifference(filename, body); different {
|
||||
warnings = append(warnings, warning)
|
||||
}
|
||||
|
||||
@@ -63,10 +63,10 @@ func (a Adapter) Adapt(body []byte, options map[string]any) ([]byte, []caddyconf
|
||||
return result, warnings, err
|
||||
}
|
||||
|
||||
// formattingDifference returns a warning and true if the formatted version
|
||||
// FormattingDifference returns a warning and true if the formatted version
|
||||
// is any different from the input; empty warning and false otherwise.
|
||||
// TODO: also perform this check on imported files
|
||||
func formattingDifference(filename string, body []byte) (caddyconfig.Warning, bool) {
|
||||
func FormattingDifference(filename string, body []byte) (caddyconfig.Warning, bool) {
|
||||
// replace windows-style newlines to normalize comparison
|
||||
normalizedBody := bytes.Replace(body, []byte("\r\n"), []byte("\n"), -1)
|
||||
|
||||
@@ -88,7 +88,7 @@ func formattingDifference(filename string, body []byte) (caddyconfig.Warning, bo
|
||||
return caddyconfig.Warning{
|
||||
File: filename,
|
||||
Line: line,
|
||||
Message: "Caddyfile input is not formatted; run the 'caddy fmt' command to fix inconsistencies",
|
||||
Message: "Caddyfile input is not formatted; run 'caddy fmt --overwrite' to fix inconsistencies",
|
||||
}, true
|
||||
}
|
||||
|
||||
|
||||
@@ -101,12 +101,12 @@ func (d *Dispenser) nextOnSameLine() bool {
|
||||
d.cursor++
|
||||
return true
|
||||
}
|
||||
if d.cursor >= len(d.tokens) {
|
||||
if d.cursor >= len(d.tokens)-1 {
|
||||
return false
|
||||
}
|
||||
if d.cursor < len(d.tokens)-1 &&
|
||||
d.tokens[d.cursor].File == d.tokens[d.cursor+1].File &&
|
||||
d.tokens[d.cursor].Line+d.numLineBreaks(d.cursor) == d.tokens[d.cursor+1].Line {
|
||||
curr := d.tokens[d.cursor]
|
||||
next := d.tokens[d.cursor+1]
|
||||
if !isNextOnNewLine(curr, next) {
|
||||
d.cursor++
|
||||
return true
|
||||
}
|
||||
@@ -122,12 +122,12 @@ func (d *Dispenser) NextLine() bool {
|
||||
d.cursor++
|
||||
return true
|
||||
}
|
||||
if d.cursor >= len(d.tokens) {
|
||||
if d.cursor >= len(d.tokens)-1 {
|
||||
return false
|
||||
}
|
||||
if d.cursor < len(d.tokens)-1 &&
|
||||
(d.tokens[d.cursor].File != d.tokens[d.cursor+1].File ||
|
||||
d.tokens[d.cursor].Line+d.numLineBreaks(d.cursor) < d.tokens[d.cursor+1].Line) {
|
||||
curr := d.tokens[d.cursor]
|
||||
next := d.tokens[d.cursor+1]
|
||||
if isNextOnNewLine(curr, next) {
|
||||
d.cursor++
|
||||
return true
|
||||
}
|
||||
@@ -203,14 +203,17 @@ func (d *Dispenser) Val() string {
|
||||
}
|
||||
|
||||
// ValRaw gets the raw text of the current token (including quotes).
|
||||
// If the token was a heredoc, then the delimiter is not included,
|
||||
// because that is not relevant to any unmarshaling logic at this time.
|
||||
// If there is no token loaded, it returns empty string.
|
||||
func (d *Dispenser) ValRaw() string {
|
||||
if d.cursor < 0 || d.cursor >= len(d.tokens) {
|
||||
return ""
|
||||
}
|
||||
quote := d.tokens[d.cursor].wasQuoted
|
||||
if quote > 0 {
|
||||
return string(quote) + d.tokens[d.cursor].Text + string(quote) // string literal
|
||||
if quote > 0 && quote != '<' {
|
||||
// string literal
|
||||
return string(quote) + d.tokens[d.cursor].Text + string(quote)
|
||||
}
|
||||
return d.tokens[d.cursor].Text
|
||||
}
|
||||
@@ -396,7 +399,7 @@ func (d *Dispenser) ArgErr() error {
|
||||
// SyntaxErr creates a generic syntax error which explains what was
|
||||
// found and what was expected.
|
||||
func (d *Dispenser) SyntaxErr(expected string) error {
|
||||
msg := fmt.Sprintf("%s:%d - Syntax error: Unexpected token '%s', expecting '%s'", d.File(), d.Line(), d.Val(), expected)
|
||||
msg := fmt.Sprintf("%s:%d - Syntax error: Unexpected token '%s', expecting '%s', import chain: ['%s']", d.File(), d.Line(), d.Val(), expected, strings.Join(d.Token().imports, "','"))
|
||||
return errors.New(msg)
|
||||
}
|
||||
|
||||
@@ -418,7 +421,7 @@ func (d *Dispenser) Errf(format string, args ...any) error {
|
||||
|
||||
// WrapErr takes an existing error and adds the Caddyfile file and line number.
|
||||
func (d *Dispenser) WrapErr(err error) error {
|
||||
return fmt.Errorf("%s:%d - Error during parsing: %w", d.File(), d.Line(), err)
|
||||
return fmt.Errorf("%s:%d - Error during parsing: %w, import chain: ['%s']", d.File(), d.Line(), err, strings.Join(d.Token().imports, "','"))
|
||||
}
|
||||
|
||||
// Delete deletes the current token and returns the updated slice
|
||||
@@ -438,14 +441,14 @@ func (d *Dispenser) Delete() []Token {
|
||||
return d.tokens
|
||||
}
|
||||
|
||||
// numLineBreaks counts how many line breaks are in the token
|
||||
// value given by the token index tknIdx. It returns 0 if the
|
||||
// token does not exist or there are no line breaks.
|
||||
func (d *Dispenser) numLineBreaks(tknIdx int) int {
|
||||
if tknIdx < 0 || tknIdx >= len(d.tokens) {
|
||||
return 0
|
||||
// DeleteN is the same as Delete, but can delete many tokens at once.
|
||||
// If there aren't N tokens available to delete, none are deleted.
|
||||
func (d *Dispenser) DeleteN(amount int) []Token {
|
||||
if amount > 0 && d.cursor >= (amount-1) && d.cursor <= len(d.tokens)-1 {
|
||||
d.tokens = append(d.tokens[:d.cursor-(amount-1)], d.tokens[d.cursor+1:]...)
|
||||
d.cursor -= amount
|
||||
}
|
||||
return strings.Count(d.tokens[tknIdx].Text, "\n")
|
||||
return d.tokens
|
||||
}
|
||||
|
||||
// isNewLine determines whether the current token is on a different
|
||||
@@ -461,25 +464,7 @@ func (d *Dispenser) isNewLine() bool {
|
||||
|
||||
prev := d.tokens[d.cursor-1]
|
||||
curr := d.tokens[d.cursor]
|
||||
|
||||
// If the previous token is from a different file,
|
||||
// we can assume it's from a different line
|
||||
if prev.File != curr.File {
|
||||
return true
|
||||
}
|
||||
|
||||
// The previous token may contain line breaks if
|
||||
// it was quoted and spanned multiple lines. e.g:
|
||||
//
|
||||
// dir "foo
|
||||
// bar
|
||||
// baz"
|
||||
prevLineBreaks := d.numLineBreaks(d.cursor - 1)
|
||||
|
||||
// If the previous token (incl line breaks) ends
|
||||
// on a line earlier than the current token,
|
||||
// then the current token is on a new line
|
||||
return prev.Line+prevLineBreaks < curr.Line
|
||||
return isNextOnNewLine(prev, curr)
|
||||
}
|
||||
|
||||
// isNextOnNewLine determines whether the current token is on a different
|
||||
@@ -495,23 +480,5 @@ func (d *Dispenser) isNextOnNewLine() bool {
|
||||
|
||||
curr := d.tokens[d.cursor]
|
||||
next := d.tokens[d.cursor+1]
|
||||
|
||||
// If the next token is from a different file,
|
||||
// we can assume it's from a different line
|
||||
if curr.File != next.File {
|
||||
return true
|
||||
}
|
||||
|
||||
// The current token may contain line breaks if
|
||||
// it was quoted and spanned multiple lines. e.g:
|
||||
//
|
||||
// dir "foo
|
||||
// bar
|
||||
// baz"
|
||||
currLineBreaks := d.numLineBreaks(d.cursor)
|
||||
|
||||
// If the current token (incl line breaks) ends
|
||||
// on a line earlier than the next token,
|
||||
// then the next token is on a new line
|
||||
return curr.Line+currLineBreaks < next.Line
|
||||
return isNextOnNewLine(curr, next)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package caddyfile
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/caddyserver/caddy/v2"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// parseVariadic determines if the token is a variadic placeholder,
|
||||
// and if so, determines the index range (start/end) of args to use.
|
||||
// Returns a boolean signaling whether a variadic placeholder was found,
|
||||
// and the start and end indices.
|
||||
func parseVariadic(token Token, argCount int) (bool, int, int) {
|
||||
if !strings.HasPrefix(token.Text, "{args[") {
|
||||
return false, 0, 0
|
||||
}
|
||||
if !strings.HasSuffix(token.Text, "]}") {
|
||||
return false, 0, 0
|
||||
}
|
||||
|
||||
argRange := strings.TrimSuffix(strings.TrimPrefix(token.Text, "{args["), "]}")
|
||||
if argRange == "" {
|
||||
caddy.Log().Named("caddyfile").Warn(
|
||||
"Placeholder "+token.Text+" cannot have an empty index",
|
||||
zap.String("file", token.File+":"+strconv.Itoa(token.Line)), zap.Strings("import_chain", token.imports))
|
||||
return false, 0, 0
|
||||
}
|
||||
|
||||
start, end, found := strings.Cut(argRange, ":")
|
||||
|
||||
// If no ":" delimiter is found, this is not a variadic.
|
||||
// The replacer will pick this up.
|
||||
if !found {
|
||||
return false, 0, 0
|
||||
}
|
||||
|
||||
var (
|
||||
startIndex = 0
|
||||
endIndex = argCount
|
||||
err error
|
||||
)
|
||||
if start != "" {
|
||||
startIndex, err = strconv.Atoi(start)
|
||||
if err != nil {
|
||||
caddy.Log().Named("caddyfile").Warn(
|
||||
"Variadic placeholder "+token.Text+" has an invalid start index",
|
||||
zap.String("file", token.File+":"+strconv.Itoa(token.Line)), zap.Strings("import_chain", token.imports))
|
||||
return false, 0, 0
|
||||
}
|
||||
}
|
||||
if end != "" {
|
||||
endIndex, err = strconv.Atoi(end)
|
||||
if err != nil {
|
||||
caddy.Log().Named("caddyfile").Warn(
|
||||
"Variadic placeholder "+token.Text+" has an invalid end index",
|
||||
zap.String("file", token.File+":"+strconv.Itoa(token.Line)), zap.Strings("import_chain", token.imports))
|
||||
return false, 0, 0
|
||||
}
|
||||
}
|
||||
|
||||
// bound check
|
||||
if startIndex < 0 || startIndex > endIndex || endIndex > argCount {
|
||||
caddy.Log().Named("caddyfile").Warn(
|
||||
"Variadic placeholder "+token.Text+" indices are out of bounds, only "+strconv.Itoa(argCount)+" argument(s) exist",
|
||||
zap.String("file", token.File+":"+strconv.Itoa(token.Line)), zap.Strings("import_chain", token.imports))
|
||||
return false, 0, 0
|
||||
}
|
||||
return true, startIndex, endIndex
|
||||
}
|
||||
|
||||
// makeArgsReplacer prepares a Replacer which can replace
|
||||
// non-variadic args placeholders in imported tokens.
|
||||
func makeArgsReplacer(args []string) *caddy.Replacer {
|
||||
repl := caddy.NewEmptyReplacer()
|
||||
repl.Map(func(key string) (any, bool) {
|
||||
// TODO: Remove the deprecated {args.*} placeholder
|
||||
// support at some point in the future
|
||||
if matches := argsRegexpIndexDeprecated.FindStringSubmatch(key); len(matches) > 0 {
|
||||
// What's matched may be a substring of the key
|
||||
if matches[0] != key {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
value, err := strconv.Atoi(matches[1])
|
||||
if err != nil {
|
||||
caddy.Log().Named("caddyfile").Warn(
|
||||
"Placeholder {args." + matches[1] + "} has an invalid index")
|
||||
return nil, false
|
||||
}
|
||||
if value >= len(args) {
|
||||
caddy.Log().Named("caddyfile").Warn(
|
||||
"Placeholder {args." + matches[1] + "} index is out of bounds, only " + strconv.Itoa(len(args)) + " argument(s) exist")
|
||||
return nil, false
|
||||
}
|
||||
caddy.Log().Named("caddyfile").Warn(
|
||||
"Placeholder {args." + matches[1] + "} deprecated, use {args[" + matches[1] + "]} instead")
|
||||
return args[value], true
|
||||
}
|
||||
|
||||
// Handle args[*] form
|
||||
if matches := argsRegexpIndex.FindStringSubmatch(key); len(matches) > 0 {
|
||||
// What's matched may be a substring of the key
|
||||
if matches[0] != key {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if strings.Contains(matches[1], ":") {
|
||||
caddy.Log().Named("caddyfile").Warn(
|
||||
"Variadic placeholder {args[" + matches[1] + "]} must be a token on its own")
|
||||
return nil, false
|
||||
}
|
||||
value, err := strconv.Atoi(matches[1])
|
||||
if err != nil {
|
||||
caddy.Log().Named("caddyfile").Warn(
|
||||
"Placeholder {args[" + matches[1] + "]} has an invalid index")
|
||||
return nil, false
|
||||
}
|
||||
if value >= len(args) {
|
||||
caddy.Log().Named("caddyfile").Warn(
|
||||
"Placeholder {args[" + matches[1] + "]} index is out of bounds, only " + strconv.Itoa(len(args)) + " argument(s) exist")
|
||||
return nil, false
|
||||
}
|
||||
return args[value], true
|
||||
}
|
||||
|
||||
// Not an args placeholder, ignore
|
||||
return nil, false
|
||||
})
|
||||
return repl
|
||||
}
|
||||
|
||||
var (
|
||||
argsRegexpIndexDeprecated = regexp.MustCompile(`args\.(.+)`)
|
||||
argsRegexpIndex = regexp.MustCompile(`args\[(.+)]`)
|
||||
)
|
||||
+200
-32
@@ -17,7 +17,10 @@ package caddyfile
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
@@ -35,15 +38,41 @@ type (
|
||||
|
||||
// Token represents a single parsable unit.
|
||||
Token struct {
|
||||
File string
|
||||
Line int
|
||||
Text string
|
||||
wasQuoted rune // enclosing quote character, if any
|
||||
inSnippet bool
|
||||
snippetName string
|
||||
File string
|
||||
imports []string
|
||||
Line int
|
||||
Text string
|
||||
wasQuoted rune // enclosing quote character, if any
|
||||
heredocMarker string
|
||||
snippetName string
|
||||
}
|
||||
)
|
||||
|
||||
// Tokenize takes bytes as input and lexes it into
|
||||
// a list of tokens that can be parsed as a Caddyfile.
|
||||
// Also takes a filename to fill the token's File as
|
||||
// the source of the tokens, which is important to
|
||||
// determine relative paths for `import` directives.
|
||||
func Tokenize(input []byte, filename string) ([]Token, error) {
|
||||
l := lexer{}
|
||||
if err := l.load(bytes.NewReader(input)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var tokens []Token
|
||||
for {
|
||||
found, err := l.next()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !found {
|
||||
break
|
||||
}
|
||||
l.token.File = filename
|
||||
tokens = append(tokens, l.token)
|
||||
}
|
||||
return tokens, nil
|
||||
}
|
||||
|
||||
// load prepares the lexer to scan an input for tokens.
|
||||
// It discards any leading byte order mark.
|
||||
func (l *lexer) load(input io.Reader) error {
|
||||
@@ -75,28 +104,93 @@ func (l *lexer) load(input io.Reader) error {
|
||||
// may be escaped. The rest of the line is skipped
|
||||
// if a "#" character is read in. Returns true if
|
||||
// a token was loaded; false otherwise.
|
||||
func (l *lexer) next() bool {
|
||||
func (l *lexer) next() (bool, error) {
|
||||
var val []rune
|
||||
var comment, quoted, btQuoted, escaped bool
|
||||
var comment, quoted, btQuoted, inHeredoc, heredocEscaped, escaped bool
|
||||
var heredocMarker string
|
||||
|
||||
makeToken := func(quoted rune) bool {
|
||||
l.token.Text = string(val)
|
||||
l.token.wasQuoted = quoted
|
||||
l.token.heredocMarker = heredocMarker
|
||||
return true
|
||||
}
|
||||
|
||||
for {
|
||||
// Read a character in; if err then if we had
|
||||
// read some characters, make a token. If we
|
||||
// reached EOF, then no more tokens to read.
|
||||
// If no EOF, then we had a problem.
|
||||
ch, _, err := l.reader.ReadRune()
|
||||
if err != nil {
|
||||
if len(val) > 0 {
|
||||
return makeToken(0)
|
||||
if inHeredoc {
|
||||
return false, fmt.Errorf("incomplete heredoc <<%s on line #%d, expected ending marker %s", heredocMarker, l.line+l.skippedLines, heredocMarker)
|
||||
}
|
||||
|
||||
return makeToken(0), nil
|
||||
}
|
||||
if err == io.EOF {
|
||||
return false
|
||||
return false, nil
|
||||
}
|
||||
panic(err)
|
||||
return false, err
|
||||
}
|
||||
|
||||
// detect whether we have the start of a heredoc
|
||||
if !inHeredoc && !heredocEscaped && len(val) > 1 && string(val[:2]) == "<<" {
|
||||
if ch == '<' {
|
||||
return false, fmt.Errorf("too many '<' for heredoc on line #%d; only use two, for example <<END", l.line)
|
||||
}
|
||||
if ch == '\r' {
|
||||
continue
|
||||
}
|
||||
// after hitting a newline, we know that the heredoc marker
|
||||
// is the characters after the two << and the newline.
|
||||
// we reset the val because the heredoc is syntax we don't
|
||||
// want to keep.
|
||||
if ch == '\n' {
|
||||
heredocMarker = string(val[2:])
|
||||
if !heredocMarkerRegexp.Match([]byte(heredocMarker)) {
|
||||
return false, fmt.Errorf("heredoc marker on line #%d must contain only alpha-numeric characters, dashes and underscores; got '%s'", l.line, heredocMarker)
|
||||
}
|
||||
|
||||
inHeredoc = true
|
||||
l.skippedLines++
|
||||
val = nil
|
||||
continue
|
||||
}
|
||||
val = append(val, ch)
|
||||
continue
|
||||
}
|
||||
|
||||
// if we're in a heredoc, all characters are read as-is
|
||||
if inHeredoc {
|
||||
val = append(val, ch)
|
||||
|
||||
if ch == '\n' {
|
||||
l.skippedLines++
|
||||
}
|
||||
|
||||
// check if we're done, i.e. that the last few characters are the marker
|
||||
if len(val) > len(heredocMarker) && heredocMarker == string(val[len(val)-len(heredocMarker):]) {
|
||||
// set the final value
|
||||
val, err = l.finalizeHeredoc(val, heredocMarker)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// set the line counter, and make the token
|
||||
l.line += l.skippedLines
|
||||
l.skippedLines = 0
|
||||
return makeToken('<'), nil
|
||||
}
|
||||
|
||||
// stay in the heredoc until we find the ending marker
|
||||
continue
|
||||
}
|
||||
|
||||
// track whether we found an escape '\' for the next
|
||||
// iteration to be contextually aware
|
||||
if !escaped && !btQuoted && ch == '\\' {
|
||||
escaped = true
|
||||
continue
|
||||
@@ -111,26 +205,29 @@ func (l *lexer) next() bool {
|
||||
}
|
||||
escaped = false
|
||||
} else {
|
||||
if quoted && ch == '"' {
|
||||
return makeToken('"')
|
||||
}
|
||||
if btQuoted && ch == '`' {
|
||||
return makeToken('`')
|
||||
if (quoted && ch == '"') || (btQuoted && ch == '`') {
|
||||
return makeToken(ch), nil
|
||||
}
|
||||
}
|
||||
// allow quoted text to wrap continue on multiple lines
|
||||
if ch == '\n' {
|
||||
l.line += 1 + l.skippedLines
|
||||
l.skippedLines = 0
|
||||
}
|
||||
// collect this character as part of the quoted token
|
||||
val = append(val, ch)
|
||||
continue
|
||||
}
|
||||
|
||||
if unicode.IsSpace(ch) {
|
||||
// ignore CR altogether, we only actually care about LF (\n)
|
||||
if ch == '\r' {
|
||||
continue
|
||||
}
|
||||
// end of the line
|
||||
if ch == '\n' {
|
||||
// newlines can be escaped to chain arguments
|
||||
// onto multiple lines; else, increment the line count
|
||||
if escaped {
|
||||
l.skippedLines++
|
||||
escaped = false
|
||||
@@ -138,14 +235,18 @@ func (l *lexer) next() bool {
|
||||
l.line += 1 + l.skippedLines
|
||||
l.skippedLines = 0
|
||||
}
|
||||
// comments (#) are single-line only
|
||||
comment = false
|
||||
}
|
||||
// any kind of space means we're at the end of this token
|
||||
if len(val) > 0 {
|
||||
return makeToken(0)
|
||||
return makeToken(0), nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// comments must be at the start of a token,
|
||||
// in other words, preceded by space or newline
|
||||
if ch == '#' && len(val) == 0 {
|
||||
comment = true
|
||||
}
|
||||
@@ -166,7 +267,12 @@ func (l *lexer) next() bool {
|
||||
}
|
||||
|
||||
if escaped {
|
||||
val = append(val, '\\')
|
||||
// allow escaping the first < to skip the heredoc syntax
|
||||
if ch == '<' {
|
||||
heredocEscaped = true
|
||||
} else {
|
||||
val = append(val, '\\')
|
||||
}
|
||||
escaped = false
|
||||
}
|
||||
|
||||
@@ -174,24 +280,86 @@ func (l *lexer) next() bool {
|
||||
}
|
||||
}
|
||||
|
||||
// Tokenize takes bytes as input and lexes it into
|
||||
// a list of tokens that can be parsed as a Caddyfile.
|
||||
// Also takes a filename to fill the token's File as
|
||||
// the source of the tokens, which is important to
|
||||
// determine relative paths for `import` directives.
|
||||
func Tokenize(input []byte, filename string) ([]Token, error) {
|
||||
l := lexer{}
|
||||
if err := l.load(bytes.NewReader(input)); err != nil {
|
||||
return nil, err
|
||||
// finalizeHeredoc takes the runes read as the heredoc text and the marker,
|
||||
// and processes the text to strip leading whitespace, returning the final
|
||||
// value without the leading whitespace.
|
||||
func (l *lexer) finalizeHeredoc(val []rune, marker string) ([]rune, error) {
|
||||
stringVal := string(val)
|
||||
|
||||
// find the last newline of the heredoc, which is where the contents end
|
||||
lastNewline := strings.LastIndex(stringVal, "\n")
|
||||
|
||||
// collapse the content, then split into separate lines
|
||||
lines := strings.Split(stringVal[:lastNewline+1], "\n")
|
||||
|
||||
// figure out how much whitespace we need to strip from the front of every line
|
||||
// by getting the string that precedes the marker, on the last line
|
||||
paddingToStrip := stringVal[lastNewline+1 : len(stringVal)-len(marker)]
|
||||
|
||||
// iterate over each line and strip the whitespace from the front
|
||||
var out string
|
||||
for lineNum, lineText := range lines[:len(lines)-1] {
|
||||
// find an exact match for the padding
|
||||
index := strings.Index(lineText, paddingToStrip)
|
||||
|
||||
// if the padding doesn't match exactly at the start then we can't safely strip
|
||||
if index != 0 {
|
||||
return nil, fmt.Errorf("mismatched leading whitespace in heredoc <<%s on line #%d [%s], expected whitespace [%s] to match the closing marker", marker, l.line+lineNum+1, lineText, paddingToStrip)
|
||||
}
|
||||
|
||||
// strip, then append the line, with the newline, to the output.
|
||||
// also removes all "\r" because Windows.
|
||||
out += strings.ReplaceAll(lineText[len(paddingToStrip):]+"\n", "\r", "")
|
||||
}
|
||||
var tokens []Token
|
||||
for l.next() {
|
||||
l.token.File = filename
|
||||
tokens = append(tokens, l.token)
|
||||
|
||||
// Remove the trailing newline from the loop
|
||||
if len(out) > 0 && out[len(out)-1] == '\n' {
|
||||
out = out[:len(out)-1]
|
||||
}
|
||||
return tokens, nil
|
||||
|
||||
// return the final value
|
||||
return []rune(out), nil
|
||||
}
|
||||
|
||||
func (t Token) Quoted() bool {
|
||||
return t.wasQuoted > 0
|
||||
}
|
||||
|
||||
// NumLineBreaks counts how many line breaks are in the token text.
|
||||
func (t Token) NumLineBreaks() int {
|
||||
lineBreaks := strings.Count(t.Text, "\n")
|
||||
if t.wasQuoted == '<' {
|
||||
// heredocs have an extra linebreak because the opening
|
||||
// delimiter is on its own line and is not included in the
|
||||
// token Text itself, and the trailing newline is removed.
|
||||
lineBreaks += 2
|
||||
}
|
||||
return lineBreaks
|
||||
}
|
||||
|
||||
var heredocMarkerRegexp = regexp.MustCompile("^[A-Za-z0-9_-]+$")
|
||||
|
||||
// isNextOnNewLine tests whether t2 is on a different line from t1
|
||||
func isNextOnNewLine(t1, t2 Token) bool {
|
||||
// If the second token is from a different file,
|
||||
// we can assume it's from a different line
|
||||
if t1.File != t2.File {
|
||||
return true
|
||||
}
|
||||
|
||||
// If the second token is from a different import chain,
|
||||
// we can assume it's from a different line
|
||||
if len(t1.imports) != len(t2.imports) {
|
||||
return true
|
||||
}
|
||||
for i, im := range t1.imports {
|
||||
if im != t2.imports[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// If the first token (incl line breaks) ends
|
||||
// on a line earlier than the next token,
|
||||
// then the second token is on a new line
|
||||
return t1.Line+t1.NumLineBreaks() < t2.Line
|
||||
}
|
||||
|
||||
@@ -18,13 +18,13 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
type lexerTestCase struct {
|
||||
input []byte
|
||||
expected []Token
|
||||
}
|
||||
|
||||
func TestLexer(t *testing.T) {
|
||||
testCases := []lexerTestCase{
|
||||
testCases := []struct {
|
||||
input []byte
|
||||
expected []Token
|
||||
expectErr bool
|
||||
errorMessage string
|
||||
}{
|
||||
{
|
||||
input: []byte(`host:123`),
|
||||
expected: []Token{
|
||||
@@ -249,12 +249,178 @@ func TestLexer(t *testing.T) {
|
||||
{Line: 1, Text: `quotes`},
|
||||
},
|
||||
},
|
||||
{
|
||||
input: []byte(`heredoc <<EOF
|
||||
content
|
||||
EOF same-line-arg
|
||||
`),
|
||||
expected: []Token{
|
||||
{Line: 1, Text: `heredoc`},
|
||||
{Line: 1, Text: "content"},
|
||||
{Line: 3, Text: `same-line-arg`},
|
||||
},
|
||||
},
|
||||
{
|
||||
input: []byte(`heredoc <<VERY-LONG-MARKER
|
||||
content
|
||||
VERY-LONG-MARKER same-line-arg
|
||||
`),
|
||||
expected: []Token{
|
||||
{Line: 1, Text: `heredoc`},
|
||||
{Line: 1, Text: "content"},
|
||||
{Line: 3, Text: `same-line-arg`},
|
||||
},
|
||||
},
|
||||
{
|
||||
input: []byte(`heredoc <<EOF
|
||||
extra-newline
|
||||
|
||||
EOF same-line-arg
|
||||
`),
|
||||
expected: []Token{
|
||||
{Line: 1, Text: `heredoc`},
|
||||
{Line: 1, Text: "extra-newline\n"},
|
||||
{Line: 4, Text: `same-line-arg`},
|
||||
},
|
||||
},
|
||||
{
|
||||
input: []byte(`heredoc <<EOF
|
||||
EOF same-line-arg
|
||||
`),
|
||||
expected: []Token{
|
||||
{Line: 1, Text: `heredoc`},
|
||||
{Line: 1, Text: ""},
|
||||
{Line: 2, Text: `same-line-arg`},
|
||||
},
|
||||
},
|
||||
{
|
||||
input: []byte(`heredoc <<EOF
|
||||
content
|
||||
EOF same-line-arg
|
||||
`),
|
||||
expected: []Token{
|
||||
{Line: 1, Text: `heredoc`},
|
||||
{Line: 1, Text: "content"},
|
||||
{Line: 3, Text: `same-line-arg`},
|
||||
},
|
||||
},
|
||||
{
|
||||
input: []byte(`prev-line
|
||||
heredoc <<EOF
|
||||
multi
|
||||
line
|
||||
content
|
||||
EOF same-line-arg
|
||||
next-line
|
||||
`),
|
||||
expected: []Token{
|
||||
{Line: 1, Text: `prev-line`},
|
||||
{Line: 2, Text: `heredoc`},
|
||||
{Line: 2, Text: "\tmulti\n\tline\n\tcontent"},
|
||||
{Line: 6, Text: `same-line-arg`},
|
||||
{Line: 7, Text: `next-line`},
|
||||
},
|
||||
},
|
||||
{
|
||||
input: []byte(`heredoc <EOF
|
||||
content
|
||||
EOF same-line-arg
|
||||
`),
|
||||
expected: []Token{
|
||||
{Line: 1, Text: `heredoc`},
|
||||
{Line: 1, Text: `<EOF`},
|
||||
{Line: 2, Text: `content`},
|
||||
{Line: 3, Text: `EOF`},
|
||||
{Line: 3, Text: `same-line-arg`},
|
||||
},
|
||||
},
|
||||
{
|
||||
input: []byte(`heredoc <<s
|
||||
�
|
||||
s
|
||||
`),
|
||||
expected: []Token{
|
||||
{Line: 1, Text: `heredoc`},
|
||||
{Line: 1, Text: "�"},
|
||||
},
|
||||
},
|
||||
{
|
||||
input: []byte("\u000Aheredoc \u003C\u003C\u0073\u0073\u000A\u00BF\u0057\u0001\u0000\u00FF\u00FF\u00FF\u00FF\u00FF\u00FF\u00FF\u003D\u001F\u000A\u0073\u0073\u000A\u00BF\u0057\u0001\u0000\u00FF\u00FF\u00FF\u00FF\u00FF\u00FF\u00FF\u003D\u001F\u000A\u00BF\u00BF\u0057\u0001\u0000\u00FF\u00FF\u00FF\u00FF\u00FF\u00FF\u00FF\u003D\u001F"),
|
||||
expected: []Token{
|
||||
{
|
||||
Line: 2,
|
||||
Text: "heredoc",
|
||||
},
|
||||
{
|
||||
Line: 2,
|
||||
Text: "\u00BF\u0057\u0001\u0000\u00FF\u00FF\u00FF\u00FF\u00FF\u00FF\u00FF\u003D\u001F",
|
||||
},
|
||||
{
|
||||
Line: 5,
|
||||
Text: "\u00BF\u0057\u0001\u0000\u00FF\u00FF\u00FF\u00FF\u00FF\u00FF\u00FF\u003D\u001F",
|
||||
},
|
||||
{
|
||||
Line: 6,
|
||||
Text: "\u00BF\u00BF\u0057\u0001\u0000\u00FF\u00FF\u00FF\u00FF\u00FF\u00FF\u00FF\u003D\u001F",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
input: []byte(`heredoc <<HERE SAME LINE
|
||||
content
|
||||
HERE same-line-arg
|
||||
`),
|
||||
expectErr: true,
|
||||
errorMessage: "heredoc marker on line #1 must contain only alpha-numeric characters, dashes and underscores; got 'HERE SAME LINE'",
|
||||
},
|
||||
{
|
||||
input: []byte(`heredoc <<<EOF
|
||||
content
|
||||
EOF same-line-arg
|
||||
`),
|
||||
expectErr: true,
|
||||
errorMessage: "too many '<' for heredoc on line #1; only use two, for example <<END",
|
||||
},
|
||||
{
|
||||
input: []byte(`heredoc <<EOF
|
||||
content
|
||||
`),
|
||||
expectErr: true,
|
||||
errorMessage: "incomplete heredoc <<EOF on line #3, expected ending marker EOF",
|
||||
},
|
||||
{
|
||||
input: []byte(`heredoc <<EOF
|
||||
content
|
||||
EOF
|
||||
`),
|
||||
expectErr: true,
|
||||
errorMessage: "mismatched leading whitespace in heredoc <<EOF on line #2 [\tcontent], expected whitespace [\t\t] to match the closing marker",
|
||||
},
|
||||
{
|
||||
input: []byte(`heredoc <<EOF
|
||||
content
|
||||
EOF
|
||||
`),
|
||||
expectErr: true,
|
||||
errorMessage: "mismatched leading whitespace in heredoc <<EOF on line #2 [ content], expected whitespace [\t\t] to match the closing marker",
|
||||
},
|
||||
}
|
||||
|
||||
for i, testCase := range testCases {
|
||||
actual, err := Tokenize(testCase.input, "")
|
||||
if testCase.expectErr {
|
||||
if err == nil {
|
||||
t.Fatalf("expected error, got actual: %v", actual)
|
||||
continue
|
||||
}
|
||||
if err.Error() != testCase.errorMessage {
|
||||
t.Fatalf("expected error '%v', got: %v", testCase.errorMessage, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("%v", err)
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
lexerCompare(t, i, testCase.expected, actual)
|
||||
}
|
||||
@@ -262,17 +428,17 @@ func TestLexer(t *testing.T) {
|
||||
|
||||
func lexerCompare(t *testing.T, n int, expected, actual []Token) {
|
||||
if len(expected) != len(actual) {
|
||||
t.Errorf("Test case %d: expected %d token(s) but got %d", n, len(expected), len(actual))
|
||||
t.Fatalf("Test case %d: expected %d token(s) but got %d", n, len(expected), len(actual))
|
||||
}
|
||||
|
||||
for i := 0; i < len(actual) && i < len(expected); i++ {
|
||||
if actual[i].Line != expected[i].Line {
|
||||
t.Errorf("Test case %d token %d ('%s'): expected line %d but was line %d",
|
||||
t.Fatalf("Test case %d token %d ('%s'): expected line %d but was line %d",
|
||||
n, i, expected[i].Text, expected[i].Line, actual[i].Line)
|
||||
break
|
||||
}
|
||||
if actual[i].Text != expected[i].Text {
|
||||
t.Errorf("Test case %d token %d: expected text '%s' but was '%s'",
|
||||
t.Fatalf("Test case %d token %d: expected text '%s' but was '%s'",
|
||||
n, i, expected[i].Text, actual[i].Text)
|
||||
break
|
||||
}
|
||||
|
||||
+139
-39
@@ -20,7 +20,6 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/caddyserver/caddy/v2"
|
||||
@@ -61,20 +60,12 @@ func Parse(filename string, input []byte) ([]ServerBlock, error) {
|
||||
// It returns all the tokens from the input, unstructured
|
||||
// and in order. It may mutate input as it expands env vars.
|
||||
func allTokens(filename string, input []byte) ([]Token, error) {
|
||||
inputCopy, err := replaceEnvVars(input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tokens, err := Tokenize(inputCopy, filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tokens, nil
|
||||
return Tokenize(replaceEnvVars(input), filename)
|
||||
}
|
||||
|
||||
// replaceEnvVars replaces all occurrences of environment variables.
|
||||
// It mutates the underlying array and returns the updated slice.
|
||||
func replaceEnvVars(input []byte) ([]byte, error) {
|
||||
func replaceEnvVars(input []byte) []byte {
|
||||
var offset int
|
||||
for {
|
||||
begin := bytes.Index(input[offset:], spanOpen)
|
||||
@@ -115,7 +106,7 @@ func replaceEnvVars(input []byte) ([]byte, error) {
|
||||
// continue at the end of the replacement
|
||||
offset = begin + len(envVarBytes)
|
||||
}
|
||||
return input, nil
|
||||
return input
|
||||
}
|
||||
|
||||
type parser struct {
|
||||
@@ -157,7 +148,6 @@ func (p *parser) begin() error {
|
||||
}
|
||||
|
||||
err := p.addresses()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -168,6 +158,25 @@ func (p *parser) begin() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
if ok, name := p.isNamedRoute(); ok {
|
||||
// named routes only have one key, the route name
|
||||
p.block.Keys = []string{name}
|
||||
p.block.IsNamedRoute = true
|
||||
|
||||
// we just need a dummy leading token to ease parsing later
|
||||
nameToken := p.Token()
|
||||
nameToken.Text = name
|
||||
|
||||
// get all the tokens from the block, including the braces
|
||||
tokens, err := p.blockTokens(true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tokens = append([]Token{nameToken}, tokens...)
|
||||
p.block.Segments = []Segment{tokens}
|
||||
return nil
|
||||
}
|
||||
|
||||
if ok, name := p.isSnippet(); ok {
|
||||
if p.definedSnippets == nil {
|
||||
p.definedSnippets = map[string][]Token{}
|
||||
@@ -176,16 +185,15 @@ func (p *parser) begin() error {
|
||||
return p.Errf("redeclaration of previously declared snippet %s", name)
|
||||
}
|
||||
// consume all tokens til matched close brace
|
||||
tokens, err := p.snippetTokens()
|
||||
tokens, err := p.blockTokens(false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Just as we need to track which file the token comes from, we need to
|
||||
// keep track of which snippets do the tokens come from. This is helpful
|
||||
// in tracking import cycles across files/snippets by namespacing them. Without
|
||||
// this we end up with false-positives in cycle-detection.
|
||||
// keep track of which snippet the token comes from. This is helpful
|
||||
// in tracking import cycles across files/snippets by namespacing them.
|
||||
// Without this, we end up with false-positives in cycle-detection.
|
||||
for k, v := range tokens {
|
||||
v.inSnippet = true
|
||||
v.snippetName = name
|
||||
tokens[k] = v
|
||||
}
|
||||
@@ -206,7 +214,7 @@ func (p *parser) addresses() error {
|
||||
|
||||
// special case: import directive replaces tokens during parse-time
|
||||
if tkn == "import" && p.isNewLine() {
|
||||
err := p.doImport()
|
||||
err := p.doImport(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -306,7 +314,7 @@ func (p *parser) directives() error {
|
||||
|
||||
// special case: import directive replaces tokens during parse-time
|
||||
if p.Val() == "import" {
|
||||
err := p.doImport()
|
||||
err := p.doImport(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -332,7 +340,7 @@ func (p *parser) directives() error {
|
||||
// is on the token before where the import directive was. In
|
||||
// other words, call Next() to access the first token that was
|
||||
// imported.
|
||||
func (p *parser) doImport() error {
|
||||
func (p *parser) doImport(nesting int) error {
|
||||
// syntax checks
|
||||
if !p.NextArg() {
|
||||
return p.ArgErr()
|
||||
@@ -345,11 +353,8 @@ func (p *parser) doImport() error {
|
||||
// grab remaining args as placeholder replacements
|
||||
args := p.RemainingArgs()
|
||||
|
||||
// add args to the replacer
|
||||
repl := caddy.NewEmptyReplacer()
|
||||
for index, arg := range args {
|
||||
repl.Set("args."+strconv.Itoa(index), arg)
|
||||
}
|
||||
// set up a replacer for non-variadic args replacement
|
||||
repl := makeArgsReplacer(args)
|
||||
|
||||
// splice out the import directive and its arguments
|
||||
// (2 tokens, plus the length of args)
|
||||
@@ -397,6 +402,20 @@ func (p *parser) doImport() error {
|
||||
} else {
|
||||
return p.Errf("File to import not found: %s", importPattern)
|
||||
}
|
||||
} else {
|
||||
// See issue #5295 - should skip any files that start with a . when iterating over them.
|
||||
sep := string(filepath.Separator)
|
||||
segGlobPattern := strings.Split(globPattern, sep)
|
||||
if strings.HasPrefix(segGlobPattern[len(segGlobPattern)-1], "*") {
|
||||
var tmpMatches []string
|
||||
for _, m := range matches {
|
||||
seg := strings.Split(m, sep)
|
||||
if !strings.HasPrefix(seg[len(seg)-1], ".") {
|
||||
tmpMatches = append(tmpMatches, m)
|
||||
}
|
||||
}
|
||||
matches = tmpMatches
|
||||
}
|
||||
}
|
||||
|
||||
// collect all the imported tokens
|
||||
@@ -411,7 +430,7 @@ func (p *parser) doImport() error {
|
||||
}
|
||||
|
||||
nodeName := p.File()
|
||||
if p.Token().inSnippet {
|
||||
if p.Token().snippetName != "" {
|
||||
nodeName += fmt.Sprintf(":%s", p.Token().snippetName)
|
||||
}
|
||||
p.importGraph.addNode(nodeName)
|
||||
@@ -422,13 +441,69 @@ func (p *parser) doImport() error {
|
||||
}
|
||||
|
||||
// copy the tokens so we don't overwrite p.definedSnippets
|
||||
tokensCopy := make([]Token, len(importedTokens))
|
||||
copy(tokensCopy, importedTokens)
|
||||
tokensCopy := make([]Token, 0, len(importedTokens))
|
||||
|
||||
var (
|
||||
maybeSnippet bool
|
||||
maybeSnippetId bool
|
||||
index int
|
||||
)
|
||||
|
||||
// run the argument replacer on the tokens
|
||||
for index, token := range tokensCopy {
|
||||
token.Text = repl.ReplaceKnown(token.Text, "")
|
||||
tokensCopy[index] = token
|
||||
// golang for range slice return a copy of value
|
||||
// similarly, append also copy value
|
||||
for i, token := range importedTokens {
|
||||
// update the token's imports to refer to import directive filename, line number and snippet name if there is one
|
||||
if token.snippetName != "" {
|
||||
token.imports = append(token.imports, fmt.Sprintf("%s:%d (import %s)", p.File(), p.Line(), token.snippetName))
|
||||
} else {
|
||||
token.imports = append(token.imports, fmt.Sprintf("%s:%d (import)", p.File(), p.Line()))
|
||||
}
|
||||
|
||||
// naive way of determine snippets, as snippets definition can only follow name + block
|
||||
// format, won't check for nesting correctness or any other error, that's what parser does.
|
||||
if !maybeSnippet && nesting == 0 {
|
||||
// first of the line
|
||||
if i == 0 || isNextOnNewLine(tokensCopy[i-1], token) {
|
||||
index = 0
|
||||
} else {
|
||||
index++
|
||||
}
|
||||
|
||||
if index == 0 && len(token.Text) >= 3 && strings.HasPrefix(token.Text, "(") && strings.HasSuffix(token.Text, ")") {
|
||||
maybeSnippetId = true
|
||||
}
|
||||
}
|
||||
|
||||
switch token.Text {
|
||||
case "{":
|
||||
nesting++
|
||||
if index == 1 && maybeSnippetId && nesting == 1 {
|
||||
maybeSnippet = true
|
||||
maybeSnippetId = false
|
||||
}
|
||||
case "}":
|
||||
nesting--
|
||||
if nesting == 0 && maybeSnippet {
|
||||
maybeSnippet = false
|
||||
}
|
||||
}
|
||||
|
||||
if maybeSnippet {
|
||||
tokensCopy = append(tokensCopy, token)
|
||||
continue
|
||||
}
|
||||
|
||||
foundVariadic, startIndex, endIndex := parseVariadic(token, len(args))
|
||||
if foundVariadic {
|
||||
for _, arg := range args[startIndex:endIndex] {
|
||||
token.Text = arg
|
||||
tokensCopy = append(tokensCopy, token)
|
||||
}
|
||||
} else {
|
||||
token.Text = repl.ReplaceKnown(token.Text, "")
|
||||
tokensCopy = append(tokensCopy, token)
|
||||
}
|
||||
}
|
||||
|
||||
// splice the imported tokens in the place of the import statement
|
||||
@@ -459,6 +534,12 @@ func (p *parser) doSingleImport(importFile string) ([]Token, error) {
|
||||
return nil, p.Errf("Could not read imported file %s: %v", importFile, err)
|
||||
}
|
||||
|
||||
// only warning in case of empty files
|
||||
if len(input) == 0 || len(strings.TrimSpace(string(input))) == 0 {
|
||||
caddy.Log().Warn("Import file is empty", zap.String("file", importFile))
|
||||
return []Token{}, nil
|
||||
}
|
||||
|
||||
importedTokens, err := allTokens(importFile, input)
|
||||
if err != nil {
|
||||
return nil, p.Errf("Could not read tokens while importing %s: %v", importFile, err)
|
||||
@@ -497,6 +578,9 @@ func (p *parser) directive() error {
|
||||
if !p.isNextOnNewLine() && p.Token().wasQuoted == 0 {
|
||||
return p.Err("Unexpected next token after '{' on same line")
|
||||
}
|
||||
if p.isNewLine() {
|
||||
return p.Err("Unexpected '{' on a new line; did you mean to place the '{' on the previous line?")
|
||||
}
|
||||
} else if p.Val() == "{}" {
|
||||
if p.isNextOnNewLine() && p.Token().wasQuoted == 0 {
|
||||
return p.Err("Unexpected '{}' at end of line")
|
||||
@@ -509,7 +593,7 @@ func (p *parser) directive() error {
|
||||
} else if p.Val() == "}" && p.nesting == 0 {
|
||||
return p.Err("Unexpected '}' because no matching opening brace")
|
||||
} else if p.Val() == "import" && p.isNewLine() {
|
||||
if err := p.doImport(); err != nil {
|
||||
if err := p.doImport(1); err != nil {
|
||||
return err
|
||||
}
|
||||
p.cursor-- // cursor is advanced when we continue, so roll back one more
|
||||
@@ -550,6 +634,15 @@ func (p *parser) closeCurlyBrace() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *parser) isNamedRoute() (bool, string) {
|
||||
keys := p.block.Keys
|
||||
// A named route block is a single key with parens, prefixed with &.
|
||||
if len(keys) == 1 && strings.HasPrefix(keys[0], "&(") && strings.HasSuffix(keys[0], ")") {
|
||||
return true, strings.TrimSuffix(keys[0][2:], ")")
|
||||
}
|
||||
return false, ""
|
||||
}
|
||||
|
||||
func (p *parser) isSnippet() (bool, string) {
|
||||
keys := p.block.Keys
|
||||
// A snippet block is a single key with parens. Nothing else qualifies.
|
||||
@@ -560,18 +653,24 @@ func (p *parser) isSnippet() (bool, string) {
|
||||
}
|
||||
|
||||
// read and store everything in a block for later replay.
|
||||
func (p *parser) snippetTokens() ([]Token, error) {
|
||||
// snippet must have curlies.
|
||||
func (p *parser) blockTokens(retainCurlies bool) ([]Token, error) {
|
||||
// block must have curlies.
|
||||
err := p.openCurlyBrace()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nesting := 1 // count our own nesting in snippets
|
||||
nesting := 1 // count our own nesting
|
||||
tokens := []Token{}
|
||||
if retainCurlies {
|
||||
tokens = append(tokens, p.Token())
|
||||
}
|
||||
for p.Next() {
|
||||
if p.Val() == "}" {
|
||||
nesting--
|
||||
if nesting == 0 {
|
||||
if retainCurlies {
|
||||
tokens = append(tokens, p.Token())
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -591,9 +690,10 @@ func (p *parser) snippetTokens() ([]Token, error) {
|
||||
// head of the server block with tokens, which are
|
||||
// grouped by segments.
|
||||
type ServerBlock struct {
|
||||
HasBraces bool
|
||||
Keys []string
|
||||
Segments []Segment
|
||||
HasBraces bool
|
||||
Keys []string
|
||||
Segments []Segment
|
||||
IsNamedRoute bool
|
||||
}
|
||||
|
||||
// DispenseDirective returns a dispenser that contains
|
||||
|
||||
@@ -21,6 +21,88 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseVariadic(t *testing.T) {
|
||||
var args = make([]string, 10)
|
||||
for i, tc := range []struct {
|
||||
input string
|
||||
result bool
|
||||
}{
|
||||
{
|
||||
input: "",
|
||||
result: false,
|
||||
},
|
||||
{
|
||||
input: "{args[1",
|
||||
result: false,
|
||||
},
|
||||
{
|
||||
input: "1]}",
|
||||
result: false,
|
||||
},
|
||||
{
|
||||
input: "{args[:]}aaaaa",
|
||||
result: false,
|
||||
},
|
||||
{
|
||||
input: "aaaaa{args[:]}",
|
||||
result: false,
|
||||
},
|
||||
{
|
||||
input: "{args.}",
|
||||
result: false,
|
||||
},
|
||||
{
|
||||
input: "{args.1}",
|
||||
result: false,
|
||||
},
|
||||
{
|
||||
input: "{args[]}",
|
||||
result: false,
|
||||
},
|
||||
{
|
||||
input: "{args[:]}",
|
||||
result: true,
|
||||
},
|
||||
{
|
||||
input: "{args[:]}",
|
||||
result: true,
|
||||
},
|
||||
{
|
||||
input: "{args[0:]}",
|
||||
result: true,
|
||||
},
|
||||
{
|
||||
input: "{args[:0]}",
|
||||
result: true,
|
||||
},
|
||||
{
|
||||
input: "{args[-1:]}",
|
||||
result: false,
|
||||
},
|
||||
{
|
||||
input: "{args[:11]}",
|
||||
result: false,
|
||||
},
|
||||
{
|
||||
input: "{args[10:0]}",
|
||||
result: false,
|
||||
},
|
||||
{
|
||||
input: "{args[0:10]}",
|
||||
result: true,
|
||||
},
|
||||
} {
|
||||
token := Token{
|
||||
File: "test",
|
||||
Line: 1,
|
||||
Text: tc.input,
|
||||
}
|
||||
if v, _, _ := parseVariadic(token, len(args)); v != tc.result {
|
||||
t.Errorf("Test %d error expectation failed Expected: %t, got %t", i, tc.result, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllTokens(t *testing.T) {
|
||||
input := []byte("a b c\nd e")
|
||||
expected := []string{"a", "b", "c", "d", "e"}
|
||||
@@ -187,6 +269,23 @@ func TestParseOneAndImport(t *testing.T) {
|
||||
|
||||
{`import testdata/not_found.txt`, true, []string{}, []int{}},
|
||||
|
||||
// empty file should just log a warning, and result in no tokens
|
||||
{`import testdata/empty.txt`, false, []string{}, []int{}},
|
||||
|
||||
{`import testdata/only_white_space.txt`, false, []string{}, []int{}},
|
||||
|
||||
// import path/to/dir/* should skip any files that start with a . when iterating over them.
|
||||
{`localhost
|
||||
dir1 arg1
|
||||
import testdata/glob/*`, false, []string{
|
||||
"localhost",
|
||||
}, []int{2, 3, 1}},
|
||||
|
||||
// import path/to/dir/.* should continue to read all dotfiles in a dir.
|
||||
{`import testdata/glob/.*`, false, []string{
|
||||
"host1",
|
||||
}, []int{1, 2}},
|
||||
|
||||
{`""`, false, []string{}, []int{}},
|
||||
|
||||
{``, false, []string{}, []int{}},
|
||||
@@ -194,6 +293,14 @@ func TestParseOneAndImport(t *testing.T) {
|
||||
// Unexpected next token after '{' on same line
|
||||
{`localhost
|
||||
dir1 { a b }`, true, []string{"localhost"}, []int{}},
|
||||
|
||||
// Unexpected '{' on a new line
|
||||
{`localhost
|
||||
dir1
|
||||
{
|
||||
a b
|
||||
}`, true, []string{"localhost"}, []int{}},
|
||||
|
||||
// Workaround with quotes
|
||||
{`localhost
|
||||
dir1 "{" a b "}"`, false, []string{"localhost"}, []int{5}},
|
||||
@@ -604,16 +711,43 @@ func TestEnvironmentReplacement(t *testing.T) {
|
||||
expect: "}{$",
|
||||
},
|
||||
} {
|
||||
actual, err := replaceEnvVars([]byte(test.input))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actual := replaceEnvVars([]byte(test.input))
|
||||
if !bytes.Equal(actual, []byte(test.expect)) {
|
||||
t.Errorf("Test %d: Expected: '%s' but got '%s'", i, test.expect, actual)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportReplacementInJSONWithBrace(t *testing.T) {
|
||||
for i, test := range []struct {
|
||||
args []string
|
||||
input string
|
||||
expect string
|
||||
}{
|
||||
{
|
||||
args: []string{"123"},
|
||||
input: "{args[0]}",
|
||||
expect: "123",
|
||||
},
|
||||
{
|
||||
args: []string{"123"},
|
||||
input: `{"key":"{args[0]}"}`,
|
||||
expect: `{"key":"123"}`,
|
||||
},
|
||||
{
|
||||
args: []string{"123", "123"},
|
||||
input: `{"key":[{args[0]},{args[1]}]}`,
|
||||
expect: `{"key":[123,123]}`,
|
||||
},
|
||||
} {
|
||||
repl := makeArgsReplacer(test.args)
|
||||
actual := repl.ReplaceKnown(test.input, "")
|
||||
if actual != test.expect {
|
||||
t.Errorf("Test %d: Expected: '%s' but got '%s'", i, test.expect, actual)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnippets(t *testing.T) {
|
||||
p := testParser(`
|
||||
(common) {
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
host1 {
|
||||
dir1
|
||||
dir2 arg1
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
dir2 arg1 arg2
|
||||
dir3
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{args.0}
|
||||
{args[0]}
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{args.0} {args.1}
|
||||
{args[0]} {args[1]}
|
||||
@@ -0,0 +1,7 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/caddyserver/caddy/v2"
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||
@@ -47,6 +48,7 @@ func init() {
|
||||
RegisterHandlerDirective("route", parseRoute)
|
||||
RegisterHandlerDirective("handle", parseHandle)
|
||||
RegisterDirective("handle_errors", parseHandleErrors)
|
||||
RegisterHandlerDirective("invoke", parseInvoke)
|
||||
RegisterDirective("log", parseLog)
|
||||
RegisterHandlerDirective("skip_log", parseSkipLog)
|
||||
}
|
||||
@@ -75,16 +77,22 @@ func parseBind(h Helper) ([]ConfigValue, error) {
|
||||
// trusted_leaf_cert <base64_der>
|
||||
// trusted_leaf_cert_file <filename>
|
||||
// }
|
||||
// alpn <values...>
|
||||
// load <paths...>
|
||||
// ca <acme_ca_endpoint>
|
||||
// ca_root <pem_file>
|
||||
// dns <provider_name> [...]
|
||||
// alpn <values...>
|
||||
// load <paths...>
|
||||
// ca <acme_ca_endpoint>
|
||||
// ca_root <pem_file>
|
||||
// key_type [ed25519|p256|p384|rsa2048|rsa4096]
|
||||
// dns <provider_name> [...]
|
||||
// propagation_delay <duration>
|
||||
// propagation_timeout <duration>
|
||||
// resolvers <dns_servers...>
|
||||
// dns_ttl <duration>
|
||||
// dns_challenge_override_domain <domain>
|
||||
// on_demand
|
||||
// eab <key_id> <mac_key>
|
||||
// issuer <module_name> [...]
|
||||
// get_certificate <module_name> [...]
|
||||
// insecure_secrets_log <log_file>
|
||||
// eab <key_id> <mac_key>
|
||||
// issuer <module_name> [...]
|
||||
// get_certificate <module_name> [...]
|
||||
// insecure_secrets_log <log_file>
|
||||
// }
|
||||
func parseTLS(h Helper) ([]ConfigValue, error) {
|
||||
cp := new(caddytls.ConnectionPolicy)
|
||||
@@ -363,6 +371,75 @@ func parseTLS(h Helper) ([]ConfigValue, error) {
|
||||
}
|
||||
acmeIssuer.Challenges.DNS.Resolvers = args
|
||||
|
||||
case "propagation_delay":
|
||||
arg := h.RemainingArgs()
|
||||
if len(arg) != 1 {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
delayStr := arg[0]
|
||||
delay, err := caddy.ParseDuration(delayStr)
|
||||
if err != nil {
|
||||
return nil, h.Errf("invalid propagation_delay duration %s: %v", delayStr, err)
|
||||
}
|
||||
if acmeIssuer == nil {
|
||||
acmeIssuer = new(caddytls.ACMEIssuer)
|
||||
}
|
||||
if acmeIssuer.Challenges == nil {
|
||||
acmeIssuer.Challenges = new(caddytls.ChallengesConfig)
|
||||
}
|
||||
if acmeIssuer.Challenges.DNS == nil {
|
||||
acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig)
|
||||
}
|
||||
acmeIssuer.Challenges.DNS.PropagationDelay = caddy.Duration(delay)
|
||||
|
||||
case "propagation_timeout":
|
||||
arg := h.RemainingArgs()
|
||||
if len(arg) != 1 {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
timeoutStr := arg[0]
|
||||
var timeout time.Duration
|
||||
if timeoutStr == "-1" {
|
||||
timeout = time.Duration(-1)
|
||||
} else {
|
||||
var err error
|
||||
timeout, err = caddy.ParseDuration(timeoutStr)
|
||||
if err != nil {
|
||||
return nil, h.Errf("invalid propagation_timeout duration %s: %v", timeoutStr, err)
|
||||
}
|
||||
}
|
||||
if acmeIssuer == nil {
|
||||
acmeIssuer = new(caddytls.ACMEIssuer)
|
||||
}
|
||||
if acmeIssuer.Challenges == nil {
|
||||
acmeIssuer.Challenges = new(caddytls.ChallengesConfig)
|
||||
}
|
||||
if acmeIssuer.Challenges.DNS == nil {
|
||||
acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig)
|
||||
}
|
||||
acmeIssuer.Challenges.DNS.PropagationTimeout = caddy.Duration(timeout)
|
||||
|
||||
case "dns_ttl":
|
||||
arg := h.RemainingArgs()
|
||||
if len(arg) != 1 {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
ttlStr := arg[0]
|
||||
ttl, err := caddy.ParseDuration(ttlStr)
|
||||
if err != nil {
|
||||
return nil, h.Errf("invalid dns_ttl duration %s: %v", ttlStr, err)
|
||||
}
|
||||
if acmeIssuer == nil {
|
||||
acmeIssuer = new(caddytls.ACMEIssuer)
|
||||
}
|
||||
if acmeIssuer.Challenges == nil {
|
||||
acmeIssuer.Challenges = new(caddytls.ChallengesConfig)
|
||||
}
|
||||
if acmeIssuer.Challenges.DNS == nil {
|
||||
acmeIssuer.Challenges.DNS = new(caddytls.DNSChallengeConfig)
|
||||
}
|
||||
acmeIssuer.Challenges.DNS.TTL = caddy.Duration(ttl)
|
||||
|
||||
case "dns_challenge_override_domain":
|
||||
arg := h.RemainingArgs()
|
||||
if len(arg) != 1 {
|
||||
@@ -655,29 +732,20 @@ func parseError(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
||||
|
||||
// parseRoute parses the route directive.
|
||||
func parseRoute(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
||||
sr := new(caddyhttp.Subroute)
|
||||
|
||||
allResults, err := parseSegmentAsConfig(h)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, result := range allResults {
|
||||
switch handler := result.Value.(type) {
|
||||
case caddyhttp.Route:
|
||||
sr.Routes = append(sr.Routes, handler)
|
||||
case caddyhttp.Subroute:
|
||||
// directives which return a literal subroute instead of a route
|
||||
// means they intend to keep those handlers together without
|
||||
// them being reordered; we're doing that anyway since we're in
|
||||
// the route directive, so just append its handlers
|
||||
sr.Routes = append(sr.Routes, handler.Routes...)
|
||||
switch result.Value.(type) {
|
||||
case caddyhttp.Route, caddyhttp.Subroute:
|
||||
default:
|
||||
return nil, h.Errf("%s directive returned something other than an HTTP route or subroute: %#v (only handler directives can be used in routes)", result.directive, result.Value)
|
||||
}
|
||||
}
|
||||
|
||||
return sr, nil
|
||||
return buildSubroute(allResults, h.groupCounter, false)
|
||||
}
|
||||
|
||||
func parseHandle(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
||||
@@ -697,9 +765,31 @@ func parseHandleErrors(h Helper) ([]ConfigValue, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// parseInvoke parses the invoke directive.
|
||||
func parseInvoke(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
||||
h.Next() // consume directive
|
||||
if !h.NextArg() {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
for h.Next() || h.NextBlock(0) {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
|
||||
// remember that we're invoking this name
|
||||
// to populate the server with these named routes
|
||||
if h.State[namedRouteKey] == nil {
|
||||
h.State[namedRouteKey] = map[string]struct{}{}
|
||||
}
|
||||
h.State[namedRouteKey].(map[string]struct{})[h.Val()] = struct{}{}
|
||||
|
||||
// return the handler
|
||||
return &caddyhttp.Invoke{Name: h.Val()}, nil
|
||||
}
|
||||
|
||||
// parseLog parses the log directive. Syntax:
|
||||
//
|
||||
// log {
|
||||
// log <logger_name> {
|
||||
// hostnames <hostnames...>
|
||||
// output <writer_module> ...
|
||||
// format <encoder_module> ...
|
||||
// level <level>
|
||||
@@ -720,11 +810,13 @@ func parseLogHelper(h Helper, globalLogNames map[string]struct{}) ([]ConfigValue
|
||||
var configValues []ConfigValue
|
||||
for h.Next() {
|
||||
// Logic below expects that a name is always present when a
|
||||
// global option is being parsed.
|
||||
var globalLogName string
|
||||
// global option is being parsed; or an optional override
|
||||
// is supported for access logs.
|
||||
var logName string
|
||||
|
||||
if parseAsGlobalOption {
|
||||
if h.NextArg() {
|
||||
globalLogName = h.Val()
|
||||
logName = h.Val()
|
||||
|
||||
// Only a single argument is supported.
|
||||
if h.NextArg() {
|
||||
@@ -735,26 +827,47 @@ func parseLogHelper(h Helper, globalLogNames map[string]struct{}) ([]ConfigValue
|
||||
// reference the default logger. See the
|
||||
// setupNewDefault function in the logging
|
||||
// package for where this is configured.
|
||||
globalLogName = "default"
|
||||
logName = caddy.DefaultLoggerName
|
||||
}
|
||||
|
||||
// Verify this name is unused.
|
||||
_, used := globalLogNames[globalLogName]
|
||||
_, used := globalLogNames[logName]
|
||||
if used {
|
||||
return nil, h.Err("duplicate global log option for: " + globalLogName)
|
||||
return nil, h.Err("duplicate global log option for: " + logName)
|
||||
}
|
||||
globalLogNames[globalLogName] = struct{}{}
|
||||
globalLogNames[logName] = struct{}{}
|
||||
} else {
|
||||
// No arguments are supported for the server block log directive
|
||||
// An optional override of the logger name can be provided;
|
||||
// otherwise a default will be used, like "log0", "log1", etc.
|
||||
if h.NextArg() {
|
||||
return nil, h.ArgErr()
|
||||
logName = h.Val()
|
||||
|
||||
// Only a single argument is supported.
|
||||
if h.NextArg() {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cl := new(caddy.CustomLog)
|
||||
|
||||
// allow overriding the current site block's hostnames for this logger;
|
||||
// this is useful for setting up loggers per subdomain in a site block
|
||||
// with a wildcard domain
|
||||
customHostnames := []string{}
|
||||
|
||||
for h.NextBlock(0) {
|
||||
switch h.Val() {
|
||||
case "hostnames":
|
||||
if parseAsGlobalOption {
|
||||
return nil, h.Err("hostnames is not allowed in the log global options")
|
||||
}
|
||||
args := h.RemainingArgs()
|
||||
if len(args) == 0 {
|
||||
return nil, h.ArgErr()
|
||||
}
|
||||
customHostnames = append(customHostnames, args...)
|
||||
|
||||
case "output":
|
||||
if !h.NextArg() {
|
||||
return nil, h.ArgErr()
|
||||
@@ -813,18 +926,16 @@ func parseLogHelper(h Helper, globalLogNames map[string]struct{}) ([]ConfigValue
|
||||
}
|
||||
|
||||
case "include":
|
||||
// This configuration is only allowed in the global options
|
||||
if !parseAsGlobalOption {
|
||||
return nil, h.ArgErr()
|
||||
return nil, h.Err("include is not allowed in the log directive")
|
||||
}
|
||||
for h.NextArg() {
|
||||
cl.Include = append(cl.Include, h.Val())
|
||||
}
|
||||
|
||||
case "exclude":
|
||||
// This configuration is only allowed in the global options
|
||||
if !parseAsGlobalOption {
|
||||
return nil, h.ArgErr()
|
||||
return nil, h.Err("exclude is not allowed in the log directive")
|
||||
}
|
||||
for h.NextArg() {
|
||||
cl.Exclude = append(cl.Exclude, h.Val())
|
||||
@@ -836,24 +947,34 @@ func parseLogHelper(h Helper, globalLogNames map[string]struct{}) ([]ConfigValue
|
||||
}
|
||||
|
||||
var val namedCustomLog
|
||||
val.hostnames = customHostnames
|
||||
|
||||
isEmptyConfig := reflect.DeepEqual(cl, new(caddy.CustomLog))
|
||||
|
||||
// Skip handling of empty logging configs
|
||||
if !reflect.DeepEqual(cl, new(caddy.CustomLog)) {
|
||||
if parseAsGlobalOption {
|
||||
// Use indicated name for global log options
|
||||
val.name = globalLogName
|
||||
val.log = cl
|
||||
} else {
|
||||
|
||||
if parseAsGlobalOption {
|
||||
// Use indicated name for global log options
|
||||
val.name = logName
|
||||
} else {
|
||||
if logName != "" {
|
||||
val.name = logName
|
||||
} else if !isEmptyConfig {
|
||||
// Construct a log name for server log streams
|
||||
logCounter, ok := h.State["logCounter"].(int)
|
||||
if !ok {
|
||||
logCounter = 0
|
||||
}
|
||||
val.name = fmt.Sprintf("log%d", logCounter)
|
||||
cl.Include = []string{"http.log.access." + val.name}
|
||||
val.log = cl
|
||||
logCounter++
|
||||
h.State["logCounter"] = logCounter
|
||||
}
|
||||
if val.name != "" {
|
||||
cl.Include = []string{"http.log.access." + val.name}
|
||||
}
|
||||
}
|
||||
if !isEmptyConfig {
|
||||
val.log = cl
|
||||
}
|
||||
configValues = append(configValues, ConfigValue{
|
||||
Class: "custom_log",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package httpcaddyfile
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
||||
@@ -51,12 +52,13 @@ func TestLogDirectiveSyntax(t *testing.T) {
|
||||
},
|
||||
{
|
||||
input: `:8080 {
|
||||
log invalid {
|
||||
log name-override {
|
||||
output file foo.log
|
||||
}
|
||||
}
|
||||
`,
|
||||
expectError: true,
|
||||
output: `{"logging":{"logs":{"default":{"exclude":["http.log.access.name-override"]},"name-override":{"writer":{"filename":"foo.log","output":"file"},"include":["http.log.access.name-override"]}}},"apps":{"http":{"servers":{"srv0":{"listen":[":8080"],"logs":{"default_logger_name":"name-override"}}}}}}`,
|
||||
expectError: false,
|
||||
},
|
||||
} {
|
||||
|
||||
@@ -213,3 +215,139 @@ func TestRedirDirectiveSyntax(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportErrorLine(t *testing.T) {
|
||||
for i, tc := range []struct {
|
||||
input string
|
||||
errorFunc func(err error) bool
|
||||
}{
|
||||
{
|
||||
input: `(t1) {
|
||||
abort {args[:]}
|
||||
}
|
||||
:8080 {
|
||||
import t1
|
||||
import t1 true
|
||||
}`,
|
||||
errorFunc: func(err error) bool {
|
||||
return err != nil && strings.Contains(err.Error(), "Caddyfile:6 (import t1)")
|
||||
},
|
||||
},
|
||||
{
|
||||
input: `(t1) {
|
||||
abort {args[:]}
|
||||
}
|
||||
:8080 {
|
||||
import t1 true
|
||||
}`,
|
||||
errorFunc: func(err error) bool {
|
||||
return err != nil && strings.Contains(err.Error(), "Caddyfile:5 (import t1)")
|
||||
},
|
||||
},
|
||||
{
|
||||
input: `
|
||||
import testdata/import_variadic_snippet.txt
|
||||
:8080 {
|
||||
import t1 true
|
||||
}`,
|
||||
errorFunc: func(err error) bool {
|
||||
return err == nil
|
||||
},
|
||||
},
|
||||
{
|
||||
input: `
|
||||
import testdata/import_variadic_with_import.txt
|
||||
:8080 {
|
||||
import t1 true
|
||||
import t2 true
|
||||
}`,
|
||||
errorFunc: func(err error) bool {
|
||||
return err == nil
|
||||
},
|
||||
},
|
||||
} {
|
||||
adapter := caddyfile.Adapter{
|
||||
ServerType: ServerType{},
|
||||
}
|
||||
|
||||
_, _, err := adapter.Adapt([]byte(tc.input), nil)
|
||||
|
||||
if !tc.errorFunc(err) {
|
||||
t.Errorf("Test %d error expectation failed, got %s", i, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNestedImport(t *testing.T) {
|
||||
for i, tc := range []struct {
|
||||
input string
|
||||
errorFunc func(err error) bool
|
||||
}{
|
||||
{
|
||||
input: `(t1) {
|
||||
respond {args[0]} {args[1]}
|
||||
}
|
||||
|
||||
(t2) {
|
||||
import t1 {args[0]} 202
|
||||
}
|
||||
|
||||
:8080 {
|
||||
handle {
|
||||
import t2 "foobar"
|
||||
}
|
||||
}`,
|
||||
errorFunc: func(err error) bool {
|
||||
return err == nil
|
||||
},
|
||||
},
|
||||
{
|
||||
input: `(t1) {
|
||||
respond {args[:]}
|
||||
}
|
||||
|
||||
(t2) {
|
||||
import t1 {args[0]} {args[1]}
|
||||
}
|
||||
|
||||
:8080 {
|
||||
handle {
|
||||
import t2 "foobar" 202
|
||||
}
|
||||
}`,
|
||||
errorFunc: func(err error) bool {
|
||||
return err == nil
|
||||
},
|
||||
},
|
||||
{
|
||||
input: `(t1) {
|
||||
respond {args[0]} {args[1]}
|
||||
}
|
||||
|
||||
(t2) {
|
||||
import t1 {args[:]}
|
||||
}
|
||||
|
||||
:8080 {
|
||||
handle {
|
||||
import t2 "foobar" 202
|
||||
}
|
||||
}`,
|
||||
errorFunc: func(err error) bool {
|
||||
return err == nil
|
||||
},
|
||||
},
|
||||
} {
|
||||
adapter := caddyfile.Adapter{
|
||||
ServerType: ServerType{},
|
||||
}
|
||||
|
||||
_, _, err := adapter.Adapt([]byte(tc.input), nil)
|
||||
|
||||
if !tc.errorFunc(err) {
|
||||
t.Errorf("Test %d error expectation failed, got %s", i, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,6 +65,7 @@ var directiveOrder = []string{
|
||||
"templates",
|
||||
|
||||
// special routing & dispatching directives
|
||||
"invoke",
|
||||
"handle",
|
||||
"handle_path",
|
||||
"route",
|
||||
@@ -172,6 +173,7 @@ func (h Helper) Caddyfiles() []string {
|
||||
for file := range files {
|
||||
filesSlice = append(filesSlice, file)
|
||||
}
|
||||
sort.Strings(filesSlice)
|
||||
return filesSlice
|
||||
}
|
||||
|
||||
@@ -289,7 +291,7 @@ func ParseSegmentAsSubroute(h Helper) (caddyhttp.MiddlewareHandler, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return buildSubroute(allResults, h.groupCounter)
|
||||
return buildSubroute(allResults, h.groupCounter, true)
|
||||
}
|
||||
|
||||
// parseSegmentAsConfig parses the segment such that its subdirectives
|
||||
@@ -427,26 +429,16 @@ func sortRoutes(routes []ConfigValue) {
|
||||
jPathLen = len(jPM[0])
|
||||
}
|
||||
|
||||
// some directives involve setting values which can overwrite
|
||||
// each other, so it makes most sense to reverse the order so
|
||||
// that the lease specific matcher is first; everything else
|
||||
// has most-specific matcher first
|
||||
if iDir == "vars" {
|
||||
sortByPath := func() bool {
|
||||
// we can only confidently compare path lengths if both
|
||||
// directives have a single path to match (issue #5037)
|
||||
if iPathLen > 0 && jPathLen > 0 {
|
||||
// sort least-specific (shortest) path first
|
||||
return iPathLen < jPathLen
|
||||
}
|
||||
// if both paths are the same except for a trailing wildcard,
|
||||
// sort by the shorter path first (which is more specific)
|
||||
if strings.TrimSuffix(iPM[0], "*") == strings.TrimSuffix(jPM[0], "*") {
|
||||
return iPathLen < jPathLen
|
||||
}
|
||||
|
||||
// if both directives don't have a single path to compare,
|
||||
// sort whichever one has no matcher first; if both have
|
||||
// no matcher, sort equally (stable sort preserves order)
|
||||
return len(iRoute.MatcherSetsRaw) == 0 && len(jRoute.MatcherSetsRaw) > 0
|
||||
} else {
|
||||
// we can only confidently compare path lengths if both
|
||||
// directives have a single path to match (issue #5037)
|
||||
if iPathLen > 0 && jPathLen > 0 {
|
||||
// sort most-specific (longest) path first
|
||||
return iPathLen > jPathLen
|
||||
}
|
||||
@@ -455,7 +447,18 @@ func sortRoutes(routes []ConfigValue) {
|
||||
// sort whichever one has a matcher first; if both have
|
||||
// a matcher, sort equally (stable sort preserves order)
|
||||
return len(iRoute.MatcherSetsRaw) > 0 && len(jRoute.MatcherSetsRaw) == 0
|
||||
}()
|
||||
|
||||
// some directives involve setting values which can overwrite
|
||||
// each other, so it makes most sense to reverse the order so
|
||||
// that the least-specific matcher is first, allowing the last
|
||||
// matching one to win
|
||||
if iDir == "vars" {
|
||||
return !sortByPath
|
||||
}
|
||||
|
||||
// everything else is most-specific matcher first
|
||||
return sortByPath
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
"github.com/caddyserver/caddy/v2/modules/caddypki"
|
||||
"github.com/caddyserver/caddy/v2/modules/caddytls"
|
||||
"go.uber.org/zap"
|
||||
"golang.org/x/exp/slices"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -52,8 +53,10 @@ type ServerType struct {
|
||||
}
|
||||
|
||||
// Setup makes a config from the tokens.
|
||||
func (st ServerType) Setup(inputServerBlocks []caddyfile.ServerBlock,
|
||||
options map[string]any) (*caddy.Config, []caddyconfig.Warning, error) {
|
||||
func (st ServerType) Setup(
|
||||
inputServerBlocks []caddyfile.ServerBlock,
|
||||
options map[string]any,
|
||||
) (*caddy.Config, []caddyconfig.Warning, error) {
|
||||
var warnings []caddyconfig.Warning
|
||||
gc := counter{new(int)}
|
||||
state := make(map[string]any)
|
||||
@@ -79,6 +82,11 @@ func (st ServerType) Setup(inputServerBlocks []caddyfile.ServerBlock,
|
||||
return nil, warnings, err
|
||||
}
|
||||
|
||||
originalServerBlocks, err = st.extractNamedRoutes(originalServerBlocks, options, &warnings)
|
||||
if err != nil {
|
||||
return nil, warnings, err
|
||||
}
|
||||
|
||||
// replace shorthand placeholders (which are convenient
|
||||
// when writing a Caddyfile) with their actual placeholder
|
||||
// identifiers or variable names
|
||||
@@ -172,6 +180,18 @@ func (st ServerType) Setup(inputServerBlocks []caddyfile.ServerBlock,
|
||||
result.directive = dir
|
||||
sb.pile[result.Class] = append(sb.pile[result.Class], result)
|
||||
}
|
||||
|
||||
// specially handle named routes that were pulled out from
|
||||
// the invoke directive, which could be nested anywhere within
|
||||
// some subroutes in this directive; we add them to the pile
|
||||
// for this server block
|
||||
if state[namedRouteKey] != nil {
|
||||
for name := range state[namedRouteKey].(map[string]struct{}) {
|
||||
result := ConfigValue{Class: namedRouteKey, Value: name}
|
||||
sb.pile[result.Class] = append(sb.pile[result.Class], result)
|
||||
}
|
||||
state[namedRouteKey] = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,10 +239,10 @@ func (st ServerType) Setup(inputServerBlocks []caddyfile.ServerBlock,
|
||||
if ncl.name == "" {
|
||||
return
|
||||
}
|
||||
if ncl.name == "default" {
|
||||
if ncl.name == caddy.DefaultLoggerName {
|
||||
hasDefaultLog = true
|
||||
}
|
||||
if _, ok := options["debug"]; ok && ncl.log.Level == "" {
|
||||
if _, ok := options["debug"]; ok && ncl.log != nil && ncl.log.Level == "" {
|
||||
ncl.log.Level = zap.DebugLevel.CapitalString()
|
||||
}
|
||||
customLogs = append(customLogs, ncl)
|
||||
@@ -240,8 +260,10 @@ func (st ServerType) Setup(inputServerBlocks []caddyfile.ServerBlock,
|
||||
// configure it with any applicable options
|
||||
if _, ok := options["debug"]; ok {
|
||||
customLogs = append(customLogs, namedCustomLog{
|
||||
name: "default",
|
||||
log: &caddy.CustomLog{Level: zap.DebugLevel.CapitalString()},
|
||||
name: caddy.DefaultLoggerName,
|
||||
log: &caddy.CustomLog{
|
||||
BaseLog: caddy.BaseLog{Level: zap.DebugLevel.CapitalString()},
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -286,28 +308,61 @@ func (st ServerType) Setup(inputServerBlocks []caddyfile.ServerBlock,
|
||||
if adminConfig, ok := options["admin"].(*caddy.AdminConfig); ok && adminConfig != nil {
|
||||
cfg.Admin = adminConfig
|
||||
}
|
||||
|
||||
if pc, ok := options["persist_config"].(string); ok && pc == "off" {
|
||||
if cfg.Admin == nil {
|
||||
cfg.Admin = new(caddy.AdminConfig)
|
||||
}
|
||||
if cfg.Admin.Config == nil {
|
||||
cfg.Admin.Config = new(caddy.ConfigSettings)
|
||||
}
|
||||
cfg.Admin.Config.Persist = new(bool)
|
||||
}
|
||||
|
||||
if len(customLogs) > 0 {
|
||||
if cfg.Logging == nil {
|
||||
cfg.Logging = &caddy.Logging{
|
||||
Logs: make(map[string]*caddy.CustomLog),
|
||||
}
|
||||
}
|
||||
|
||||
// Add the default log first if defined, so that it doesn't
|
||||
// accidentally get re-created below due to the Exclude logic
|
||||
for _, ncl := range customLogs {
|
||||
if ncl.name == caddy.DefaultLoggerName && ncl.log != nil {
|
||||
cfg.Logging.Logs[caddy.DefaultLoggerName] = ncl.log
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Add the rest of the custom logs
|
||||
for _, ncl := range customLogs {
|
||||
if ncl.log == nil || ncl.name == caddy.DefaultLoggerName {
|
||||
continue
|
||||
}
|
||||
if ncl.name != "" {
|
||||
cfg.Logging.Logs[ncl.name] = ncl.log
|
||||
}
|
||||
// most users seem to prefer not writing access logs
|
||||
// to the default log when they are directed to a
|
||||
// file or have any other special customization
|
||||
if ncl.name != "default" && len(ncl.log.Include) > 0 {
|
||||
defaultLog, ok := cfg.Logging.Logs["default"]
|
||||
if ncl.name != caddy.DefaultLoggerName && len(ncl.log.Include) > 0 {
|
||||
defaultLog, ok := cfg.Logging.Logs[caddy.DefaultLoggerName]
|
||||
if !ok {
|
||||
defaultLog = new(caddy.CustomLog)
|
||||
cfg.Logging.Logs["default"] = defaultLog
|
||||
cfg.Logging.Logs[caddy.DefaultLoggerName] = defaultLog
|
||||
}
|
||||
defaultLog.Exclude = append(defaultLog.Exclude, ncl.log.Include...)
|
||||
|
||||
// avoid duplicates by sorting + compacting
|
||||
sort.Strings(defaultLog.Exclude)
|
||||
defaultLog.Exclude = slices.Compact[[]string, string](defaultLog.Exclude)
|
||||
}
|
||||
}
|
||||
// we may have not actually added anything, so remove if empty
|
||||
if len(cfg.Logging.Logs) == 0 {
|
||||
cfg.Logging = nil
|
||||
}
|
||||
}
|
||||
|
||||
return cfg, warnings, nil
|
||||
@@ -390,6 +445,77 @@ func (ServerType) evaluateGlobalOptionsBlock(serverBlocks []serverBlock, options
|
||||
return serverBlocks[1:], nil
|
||||
}
|
||||
|
||||
// extractNamedRoutes pulls out any named route server blocks
|
||||
// so they don't get parsed as sites, and stores them in options
|
||||
// for later.
|
||||
func (ServerType) extractNamedRoutes(
|
||||
serverBlocks []serverBlock,
|
||||
options map[string]any,
|
||||
warnings *[]caddyconfig.Warning,
|
||||
) ([]serverBlock, error) {
|
||||
namedRoutes := map[string]*caddyhttp.Route{}
|
||||
|
||||
gc := counter{new(int)}
|
||||
state := make(map[string]any)
|
||||
|
||||
// copy the server blocks so we can
|
||||
// splice out the named route ones
|
||||
filtered := append([]serverBlock{}, serverBlocks...)
|
||||
index := -1
|
||||
|
||||
for _, sb := range serverBlocks {
|
||||
index++
|
||||
if !sb.block.IsNamedRoute {
|
||||
continue
|
||||
}
|
||||
|
||||
// splice out this block, because we know it's not a real server
|
||||
filtered = append(filtered[:index], filtered[index+1:]...)
|
||||
index--
|
||||
|
||||
if len(sb.block.Segments) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// zip up all the segments since ParseSegmentAsSubroute
|
||||
// was designed to take a directive+
|
||||
wholeSegment := caddyfile.Segment{}
|
||||
for _, segment := range sb.block.Segments {
|
||||
wholeSegment = append(wholeSegment, segment...)
|
||||
}
|
||||
|
||||
h := Helper{
|
||||
Dispenser: caddyfile.NewDispenser(wholeSegment),
|
||||
options: options,
|
||||
warnings: warnings,
|
||||
matcherDefs: nil,
|
||||
parentBlock: sb.block,
|
||||
groupCounter: gc,
|
||||
State: state,
|
||||
}
|
||||
|
||||
handler, err := ParseSegmentAsSubroute(h)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
subroute := handler.(*caddyhttp.Subroute)
|
||||
route := caddyhttp.Route{}
|
||||
|
||||
if len(subroute.Routes) == 1 && len(subroute.Routes[0].MatcherSetsRaw) == 0 {
|
||||
// if there's only one route with no matcher, then we can simplify
|
||||
route.HandlersRaw = append(route.HandlersRaw, subroute.Routes[0].HandlersRaw[0])
|
||||
} else {
|
||||
// otherwise we need the whole subroute
|
||||
route.HandlersRaw = []json.RawMessage{caddyconfig.JSONModuleObject(handler, "handler", subroute.CaddyModule().ID.Name(), h.warnings)}
|
||||
}
|
||||
|
||||
namedRoutes[sb.block.Keys[0]] = &route
|
||||
}
|
||||
options["named_routes"] = namedRoutes
|
||||
|
||||
return filtered, nil
|
||||
}
|
||||
|
||||
// serversFromPairings creates the servers for each pairing of addresses
|
||||
// to server blocks. Each pairing is essentially a server definition.
|
||||
func (st *ServerType) serversFromPairings(
|
||||
@@ -400,6 +526,7 @@ func (st *ServerType) serversFromPairings(
|
||||
) (map[string]*caddyhttp.Server, error) {
|
||||
servers := make(map[string]*caddyhttp.Server)
|
||||
defaultSNI := tryString(options["default_sni"], warnings)
|
||||
fallbackSNI := tryString(options["fallback_sni"], warnings)
|
||||
|
||||
httpPort := strconv.Itoa(caddyhttp.DefaultHTTPPort)
|
||||
if hp, ok := options["http_port"].(int); ok {
|
||||
@@ -518,15 +645,6 @@ func (st *ServerType) serversFromPairings(
|
||||
var hasCatchAllTLSConnPolicy, addressQualifiesForTLS bool
|
||||
autoHTTPSWillAddConnPolicy := autoHTTPS != "off"
|
||||
|
||||
// if a catch-all server block (one which accepts all hostnames) exists in this pairing,
|
||||
// we need to know that so that we can configure logs properly (see #3878)
|
||||
var catchAllSblockExists bool
|
||||
for _, sblock := range p.serverBlocks {
|
||||
if len(sblock.hostsFromKeys(false)) == 0 {
|
||||
catchAllSblockExists = true
|
||||
}
|
||||
}
|
||||
|
||||
// if needed, the ServerLogConfig is initialized beforehand so
|
||||
// that all server blocks can populate it with data, even when not
|
||||
// coming with a log directive
|
||||
@@ -537,6 +655,24 @@ func (st *ServerType) serversFromPairings(
|
||||
}
|
||||
}
|
||||
|
||||
// add named routes to the server if 'invoke' was used inside of it
|
||||
configuredNamedRoutes := options["named_routes"].(map[string]*caddyhttp.Route)
|
||||
for _, sblock := range p.serverBlocks {
|
||||
if len(sblock.pile[namedRouteKey]) == 0 {
|
||||
continue
|
||||
}
|
||||
for _, value := range sblock.pile[namedRouteKey] {
|
||||
if srv.NamedRoutes == nil {
|
||||
srv.NamedRoutes = map[string]*caddyhttp.Route{}
|
||||
}
|
||||
name := value.Value.(string)
|
||||
if configuredNamedRoutes[name] == nil {
|
||||
return nil, fmt.Errorf("cannot invoke named route '%s', which was not defined", name)
|
||||
}
|
||||
srv.NamedRoutes[name] = configuredNamedRoutes[name]
|
||||
}
|
||||
}
|
||||
|
||||
// create a subroute for each site in the server block
|
||||
for _, sblock := range p.serverBlocks {
|
||||
matcherSetsEnc, err := st.compileEncodedMatcherSets(sblock)
|
||||
@@ -566,6 +702,11 @@ func (st *ServerType) serversFromPairings(
|
||||
cp.DefaultSNI = defaultSNI
|
||||
break
|
||||
}
|
||||
if h == fallbackSNI {
|
||||
hosts = append(hosts, "")
|
||||
cp.FallbackSNI = fallbackSNI
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if len(hosts) > 0 {
|
||||
@@ -574,6 +715,7 @@ func (st *ServerType) serversFromPairings(
|
||||
}
|
||||
} else {
|
||||
cp.DefaultSNI = defaultSNI
|
||||
cp.FallbackSNI = fallbackSNI
|
||||
}
|
||||
|
||||
// only append this policy if it actually changes something
|
||||
@@ -627,7 +769,7 @@ func (st *ServerType) serversFromPairings(
|
||||
|
||||
// set up each handler directive, making sure to honor directive order
|
||||
dirRoutes := sblock.pile["route"]
|
||||
siteSubroute, err := buildSubroute(dirRoutes, groupCounter)
|
||||
siteSubroute, err := buildSubroute(dirRoutes, groupCounter, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -651,25 +793,25 @@ func (st *ServerType) serversFromPairings(
|
||||
sblockLogHosts := sblock.hostsFromKeys(true)
|
||||
for _, cval := range sblock.pile["custom_log"] {
|
||||
ncl := cval.Value.(namedCustomLog)
|
||||
if sblock.hasHostCatchAllKey() {
|
||||
if sblock.hasHostCatchAllKey() && len(ncl.hostnames) == 0 {
|
||||
// all requests for hosts not able to be listed should use
|
||||
// this log because it's a catch-all-hosts server block
|
||||
srv.Logs.DefaultLoggerName = ncl.name
|
||||
} else {
|
||||
// map each host to the user's desired logger name
|
||||
for _, h := range sblockLogHosts {
|
||||
// if the custom logger name is non-empty, add it to the map;
|
||||
// otherwise, only map to an empty logger name if this or
|
||||
// another site block on this server has a catch-all host (in
|
||||
// which case only requests with mapped hostnames will be
|
||||
// access-logged, so it'll be necessary to add them to the
|
||||
// map even if they use default logger)
|
||||
if ncl.name != "" || catchAllSblockExists {
|
||||
if srv.Logs.LoggerNames == nil {
|
||||
srv.Logs.LoggerNames = make(map[string]string)
|
||||
}
|
||||
srv.Logs.LoggerNames[h] = ncl.name
|
||||
} else if len(ncl.hostnames) > 0 {
|
||||
// if the logger overrides the hostnames, map that to the logger name
|
||||
for _, h := range ncl.hostnames {
|
||||
if srv.Logs.LoggerNames == nil {
|
||||
srv.Logs.LoggerNames = make(map[string]string)
|
||||
}
|
||||
srv.Logs.LoggerNames[h] = ncl.name
|
||||
}
|
||||
} else {
|
||||
// otherwise, map each host to the logger name
|
||||
for _, h := range sblockLogHosts {
|
||||
if srv.Logs.LoggerNames == nil {
|
||||
srv.Logs.LoggerNames = make(map[string]string)
|
||||
}
|
||||
srv.Logs.LoggerNames[h] = ncl.name
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -707,8 +849,8 @@ func (st *ServerType) serversFromPairings(
|
||||
// policy missing for any HTTPS-enabled hosts, if so, add it... maybe?
|
||||
if addressQualifiesForTLS &&
|
||||
!hasCatchAllTLSConnPolicy &&
|
||||
(len(srv.TLSConnPolicies) > 0 || !autoHTTPSWillAddConnPolicy || defaultSNI != "") {
|
||||
srv.TLSConnPolicies = append(srv.TLSConnPolicies, &caddytls.ConnectionPolicy{DefaultSNI: defaultSNI})
|
||||
(len(srv.TLSConnPolicies) > 0 || !autoHTTPSWillAddConnPolicy || defaultSNI != "" || fallbackSNI != "") {
|
||||
srv.TLSConnPolicies = append(srv.TLSConnPolicies, &caddytls.ConnectionPolicy{DefaultSNI: defaultSNI, FallbackSNI: fallbackSNI})
|
||||
}
|
||||
|
||||
// tidy things up a bit
|
||||
@@ -723,7 +865,7 @@ func (st *ServerType) serversFromPairings(
|
||||
|
||||
err := applyServerOptions(servers, options, warnings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("applying global server options: %v", err)
|
||||
}
|
||||
|
||||
return servers, nil
|
||||
@@ -924,11 +1066,32 @@ func appendSubrouteToRouteList(routeList caddyhttp.RouteList,
|
||||
return routeList
|
||||
}
|
||||
|
||||
// No need to wrap the handlers in a subroute if this is the only server block
|
||||
// and there is no matcher for it (doing so would produce unnecessarily nested
|
||||
// JSON), *unless* there is a host matcher within this site block; if so, then
|
||||
// we still need to wrap in a subroute because otherwise the host matcher from
|
||||
// the inside of the site block would be a top-level host matcher, which is
|
||||
// subject to auto-HTTPS (cert management), and using a host matcher within
|
||||
// a site block is a valid, common pattern for excluding domains from cert
|
||||
// management, leading to unexpected behavior; see issue #5124.
|
||||
wrapInSubroute := true
|
||||
if len(matcherSetsEnc) == 0 && len(p.serverBlocks) == 1 {
|
||||
// no need to wrap the handlers in a subroute if this is
|
||||
// the only server block and there is no matcher for it
|
||||
routeList = append(routeList, subroute.Routes...)
|
||||
} else {
|
||||
var hasHostMatcher bool
|
||||
outer:
|
||||
for _, route := range subroute.Routes {
|
||||
for _, ms := range route.MatcherSetsRaw {
|
||||
for matcherName := range ms {
|
||||
if matcherName == "host" {
|
||||
hasHostMatcher = true
|
||||
break outer
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
wrapInSubroute = hasHostMatcher
|
||||
}
|
||||
|
||||
if wrapInSubroute {
|
||||
route := caddyhttp.Route{
|
||||
// the semantics of a site block in the Caddyfile dictate
|
||||
// that only the first matching one is evaluated, since
|
||||
@@ -946,20 +1109,25 @@ func appendSubrouteToRouteList(routeList caddyhttp.RouteList,
|
||||
if len(route.MatcherSetsRaw) > 0 || len(route.HandlersRaw) > 0 {
|
||||
routeList = append(routeList, route)
|
||||
}
|
||||
} else {
|
||||
routeList = append(routeList, subroute.Routes...)
|
||||
}
|
||||
|
||||
return routeList
|
||||
}
|
||||
|
||||
// buildSubroute turns the config values, which are expected to be routes
|
||||
// into a clean and orderly subroute that has all the routes within it.
|
||||
func buildSubroute(routes []ConfigValue, groupCounter counter) (*caddyhttp.Subroute, error) {
|
||||
for _, val := range routes {
|
||||
if !directiveIsOrdered(val.directive) {
|
||||
return nil, fmt.Errorf("directive '%s' is not an ordered HTTP handler, so it cannot be used here", val.directive)
|
||||
func buildSubroute(routes []ConfigValue, groupCounter counter, needsSorting bool) (*caddyhttp.Subroute, error) {
|
||||
if needsSorting {
|
||||
for _, val := range routes {
|
||||
if !directiveIsOrdered(val.directive) {
|
||||
return nil, fmt.Errorf("directive '%s' is not an ordered HTTP handler, so it cannot be used here - try placing within a route block or using the order global option", val.directive)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sortRoutes(routes)
|
||||
sortRoutes(routes)
|
||||
}
|
||||
|
||||
subroute := new(caddyhttp.Subroute)
|
||||
|
||||
@@ -1308,6 +1476,7 @@ func placeholderShorthands() []string {
|
||||
"{tls_client_certificate_pem}", "{http.request.tls.client.certificate_pem}",
|
||||
"{tls_client_certificate_der_base64}", "{http.request.tls.client.certificate_der_base64}",
|
||||
"{upstream_hostport}", "{http.reverse_proxy.upstream.hostport}",
|
||||
"{client_ip}", "{http.vars.client_ip}",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1426,8 +1595,9 @@ func (c counter) nextGroup() string {
|
||||
}
|
||||
|
||||
type namedCustomLog struct {
|
||||
name string
|
||||
log *caddy.CustomLog
|
||||
name string
|
||||
hostnames []string
|
||||
log *caddy.CustomLog
|
||||
}
|
||||
|
||||
// sbAddrAssociation is a mapping from a list of
|
||||
@@ -1439,6 +1609,7 @@ type sbAddrAssociation struct {
|
||||
}
|
||||
|
||||
const matcherPrefix = "@"
|
||||
const namedRouteKey = "named_route"
|
||||
|
||||
// Interface guard
|
||||
var _ caddyfile.ServerType = (*ServerType)(nil)
|
||||
|
||||
@@ -33,6 +33,7 @@ func init() {
|
||||
RegisterGlobalOption("grace_period", parseOptDuration)
|
||||
RegisterGlobalOption("shutdown_delay", parseOptDuration)
|
||||
RegisterGlobalOption("default_sni", parseOptSingleString)
|
||||
RegisterGlobalOption("fallback_sni", parseOptSingleString)
|
||||
RegisterGlobalOption("order", parseOptOrder)
|
||||
RegisterGlobalOption("storage", parseOptStorage)
|
||||
RegisterGlobalOption("storage_clean_interval", parseOptDuration)
|
||||
@@ -54,6 +55,7 @@ func init() {
|
||||
RegisterGlobalOption("ocsp_stapling", parseOCSPStaplingOptions)
|
||||
RegisterGlobalOption("log", parseLogOptions)
|
||||
RegisterGlobalOption("preferred_chains", parseOptPreferredChains)
|
||||
RegisterGlobalOption("persist_config", parseOptPersistConfig)
|
||||
}
|
||||
|
||||
func parseOptTrue(d *caddyfile.Dispenser, _ any) (any, error) { return true, nil }
|
||||
@@ -386,6 +388,21 @@ func parseOptOnDemand(d *caddyfile.Dispenser, _ any) (any, error) {
|
||||
return ond, nil
|
||||
}
|
||||
|
||||
func parseOptPersistConfig(d *caddyfile.Dispenser, _ any) (any, error) {
|
||||
d.Next() // consume parameter name
|
||||
if !d.Next() {
|
||||
return "", d.ArgErr()
|
||||
}
|
||||
val := d.Val()
|
||||
if d.Next() {
|
||||
return "", d.ArgErr()
|
||||
}
|
||||
if val != "off" {
|
||||
return "", d.Errf("persist_config must be 'off'")
|
||||
}
|
||||
return val, nil
|
||||
}
|
||||
|
||||
func parseOptAutoHTTPS(d *caddyfile.Dispenser, _ any) (any, error) {
|
||||
d.Next() // consume parameter name
|
||||
if !d.Next() {
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
package httpcaddyfile
|
||||
|
||||
import (
|
||||
"github.com/caddyserver/caddy/v2"
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
||||
"github.com/caddyserver/caddy/v2/modules/caddypki"
|
||||
@@ -26,23 +27,24 @@ func init() {
|
||||
|
||||
// parsePKIApp parses the global log option. Syntax:
|
||||
//
|
||||
// pki {
|
||||
// ca [<id>] {
|
||||
// name <name>
|
||||
// root_cn <name>
|
||||
// intermediate_cn <name>
|
||||
// root {
|
||||
// cert <path>
|
||||
// key <path>
|
||||
// format <format>
|
||||
// }
|
||||
// intermediate {
|
||||
// cert <path>
|
||||
// key <path>
|
||||
// format <format>
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// pki {
|
||||
// ca [<id>] {
|
||||
// name <name>
|
||||
// root_cn <name>
|
||||
// intermediate_cn <name>
|
||||
// intermediate_lifetime <duration>
|
||||
// root {
|
||||
// cert <path>
|
||||
// key <path>
|
||||
// format <format>
|
||||
// }
|
||||
// intermediate {
|
||||
// cert <path>
|
||||
// key <path>
|
||||
// format <format>
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// When the CA ID is unspecified, 'local' is assumed.
|
||||
func parsePKIApp(d *caddyfile.Dispenser, existingVal any) (any, error) {
|
||||
@@ -83,6 +85,16 @@ func parsePKIApp(d *caddyfile.Dispenser, existingVal any) (any, error) {
|
||||
}
|
||||
pkiCa.IntermediateCommonName = d.Val()
|
||||
|
||||
case "intermediate_lifetime":
|
||||
if !d.NextArg() {
|
||||
return nil, d.ArgErr()
|
||||
}
|
||||
dur, err := caddy.ParseDuration(d.Val())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pkiCa.IntermediateLifetime = caddy.Duration(dur)
|
||||
|
||||
case "root":
|
||||
if pkiCa.Root == nil {
|
||||
pkiCa.Root = new(caddypki.KeyPair)
|
||||
|
||||
@@ -33,6 +33,7 @@ type serverOptions struct {
|
||||
ListenerAddress string
|
||||
|
||||
// These will all map 1:1 to the caddyhttp.Server struct
|
||||
Name string
|
||||
ListenerWrappersRaw []json.RawMessage
|
||||
ReadTimeout caddy.Duration
|
||||
ReadHeaderTimeout caddy.Duration
|
||||
@@ -40,8 +41,11 @@ type serverOptions struct {
|
||||
IdleTimeout caddy.Duration
|
||||
KeepAliveInterval caddy.Duration
|
||||
MaxHeaderBytes int
|
||||
EnableFullDuplex bool
|
||||
Protocols []string
|
||||
StrictSNIHost *bool
|
||||
TrustedProxiesRaw json.RawMessage
|
||||
ClientIPHeaders []string
|
||||
ShouldLogCredentials bool
|
||||
Metrics *caddyhttp.Metrics
|
||||
}
|
||||
@@ -57,6 +61,15 @@ func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) {
|
||||
}
|
||||
for nesting := d.Nesting(); d.NextBlock(nesting); {
|
||||
switch d.Val() {
|
||||
case "name":
|
||||
if serverOpts.ListenerAddress == "" {
|
||||
return nil, d.Errf("cannot set a name for a server without a listener address")
|
||||
}
|
||||
if !d.NextArg() {
|
||||
return nil, d.ArgErr()
|
||||
}
|
||||
serverOpts.Name = d.Val()
|
||||
|
||||
case "listener_wrappers":
|
||||
for nesting := d.Nesting(); d.NextBlock(nesting); {
|
||||
modID := "caddy.listeners." + d.Val()
|
||||
@@ -145,6 +158,12 @@ func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) {
|
||||
}
|
||||
serverOpts.MaxHeaderBytes = int(size)
|
||||
|
||||
case "enable_full_duplex":
|
||||
if d.NextArg() {
|
||||
return nil, d.ArgErr()
|
||||
}
|
||||
serverOpts.EnableFullDuplex = true
|
||||
|
||||
case "log_credentials":
|
||||
if d.NextArg() {
|
||||
return nil, d.ArgErr()
|
||||
@@ -176,11 +195,44 @@ func unmarshalCaddyfileServerOptions(d *caddyfile.Dispenser) (any, error) {
|
||||
}
|
||||
serverOpts.StrictSNIHost = &boolVal
|
||||
|
||||
case "trusted_proxies":
|
||||
if !d.NextArg() {
|
||||
return nil, d.Err("trusted_proxies expects an IP range source module name as its first argument")
|
||||
}
|
||||
modID := "http.ip_sources." + d.Val()
|
||||
unm, err := caddyfile.UnmarshalModule(d, modID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
source, ok := unm.(caddyhttp.IPRangeSource)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("module %s (%T) is not an IP range source", modID, unm)
|
||||
}
|
||||
jsonSource := caddyconfig.JSONModuleObject(
|
||||
source,
|
||||
"source",
|
||||
source.(caddy.Module).CaddyModule().ID.Name(),
|
||||
nil,
|
||||
)
|
||||
serverOpts.TrustedProxiesRaw = jsonSource
|
||||
|
||||
case "client_ip_headers":
|
||||
headers := d.RemainingArgs()
|
||||
for _, header := range headers {
|
||||
if sliceContains(serverOpts.ClientIPHeaders, header) {
|
||||
return nil, d.Errf("client IP header %s specified more than once", header)
|
||||
}
|
||||
serverOpts.ClientIPHeaders = append(serverOpts.ClientIPHeaders, header)
|
||||
}
|
||||
if nesting := d.Nesting(); d.NextBlock(nesting) {
|
||||
return nil, d.ArgErr()
|
||||
}
|
||||
|
||||
case "metrics":
|
||||
if d.NextArg() {
|
||||
return nil, d.ArgErr()
|
||||
}
|
||||
if d.NextBlock(0) {
|
||||
if nesting := d.Nesting(); d.NextBlock(nesting) {
|
||||
return nil, d.ArgErr()
|
||||
}
|
||||
serverOpts.Metrics = new(caddyhttp.Metrics)
|
||||
@@ -238,7 +290,22 @@ func applyServerOptions(
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, server := range servers {
|
||||
// check for duplicate names, which would clobber the config
|
||||
existingNames := map[string]bool{}
|
||||
for _, opts := range serverOpts {
|
||||
if opts.Name == "" {
|
||||
continue
|
||||
}
|
||||
if existingNames[opts.Name] {
|
||||
return fmt.Errorf("cannot use duplicate server name '%s'", opts.Name)
|
||||
}
|
||||
existingNames[opts.Name] = true
|
||||
}
|
||||
|
||||
// collect the server name overrides
|
||||
nameReplacements := map[string]string{}
|
||||
|
||||
for key, server := range servers {
|
||||
// find the options that apply to this server
|
||||
opts := func() *serverOptions {
|
||||
for _, entry := range serverOpts {
|
||||
@@ -267,8 +334,11 @@ func applyServerOptions(
|
||||
server.IdleTimeout = opts.IdleTimeout
|
||||
server.KeepAliveInterval = opts.KeepAliveInterval
|
||||
server.MaxHeaderBytes = opts.MaxHeaderBytes
|
||||
server.EnableFullDuplex = opts.EnableFullDuplex
|
||||
server.Protocols = opts.Protocols
|
||||
server.StrictSNIHost = opts.StrictSNIHost
|
||||
server.TrustedProxiesRaw = opts.TrustedProxiesRaw
|
||||
server.ClientIPHeaders = opts.ClientIPHeaders
|
||||
server.Metrics = opts.Metrics
|
||||
if opts.ShouldLogCredentials {
|
||||
if server.Logs == nil {
|
||||
@@ -276,6 +346,16 @@ func applyServerOptions(
|
||||
}
|
||||
server.Logs.ShouldLogCredentials = opts.ShouldLogCredentials
|
||||
}
|
||||
|
||||
if opts.Name != "" {
|
||||
nameReplacements[key] = opts.Name
|
||||
}
|
||||
}
|
||||
|
||||
// rename the servers if marked to do so
|
||||
for old, new := range nameReplacements {
|
||||
servers[new] = servers[old]
|
||||
delete(servers, old)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
(t2) {
|
||||
respond 200 {
|
||||
body {args[:]}
|
||||
}
|
||||
}
|
||||
|
||||
:8082 {
|
||||
import t2 false
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
(t1) {
|
||||
respond 200 {
|
||||
body {args[:]}
|
||||
}
|
||||
}
|
||||
|
||||
:8081 {
|
||||
import t1 false
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
(t1) {
|
||||
respond 200 {
|
||||
body {args[:]}
|
||||
}
|
||||
}
|
||||
|
||||
:8081 {
|
||||
import t1 false
|
||||
}
|
||||
|
||||
import import_variadic.txt
|
||||
|
||||
:8083 {
|
||||
import t2 true
|
||||
}
|
||||
@@ -44,37 +44,32 @@ func (st ServerType) buildTLSApp(
|
||||
if hp, ok := options["http_port"].(int); ok {
|
||||
httpPort = strconv.Itoa(hp)
|
||||
}
|
||||
httpsPort := strconv.Itoa(caddyhttp.DefaultHTTPSPort)
|
||||
if hsp, ok := options["https_port"].(int); ok {
|
||||
httpsPort = strconv.Itoa(hsp)
|
||||
autoHTTPS := "on"
|
||||
if ah, ok := options["auto_https"].(string); ok {
|
||||
autoHTTPS = ah
|
||||
}
|
||||
|
||||
// count how many server blocks have a TLS-enabled key with
|
||||
// no host, and find all hosts that share a server block with
|
||||
// a hostless key, so that they don't get forgotten/omitted
|
||||
// by auto-HTTPS (since they won't appear in route matchers)
|
||||
var serverBlocksWithTLSHostlessKey int
|
||||
// find all hosts that share a server block with a hostless
|
||||
// key, so that they don't get forgotten/omitted by auto-HTTPS
|
||||
// (since they won't appear in route matchers)
|
||||
httpsHostsSharedWithHostlessKey := make(map[string]struct{})
|
||||
for _, pair := range pairings {
|
||||
for _, sb := range pair.serverBlocks {
|
||||
for _, addr := range sb.keys {
|
||||
if addr.Host == "" {
|
||||
// this address has no hostname, but if it's explicitly set
|
||||
// to HTTPS, then we need to count it as being TLS-enabled
|
||||
if addr.Scheme == "https" || addr.Port == httpsPort {
|
||||
serverBlocksWithTLSHostlessKey++
|
||||
}
|
||||
// this server block has a hostless key, now
|
||||
// go through and add all the hosts to the set
|
||||
for _, otherAddr := range sb.keys {
|
||||
if otherAddr.Original == addr.Original {
|
||||
continue
|
||||
}
|
||||
if otherAddr.Host != "" && otherAddr.Scheme != "http" && otherAddr.Port != httpPort {
|
||||
httpsHostsSharedWithHostlessKey[otherAddr.Host] = struct{}{}
|
||||
if autoHTTPS != "off" {
|
||||
for _, pair := range pairings {
|
||||
for _, sb := range pair.serverBlocks {
|
||||
for _, addr := range sb.keys {
|
||||
if addr.Host == "" {
|
||||
// this server block has a hostless key, now
|
||||
// go through and add all the hosts to the set
|
||||
for _, otherAddr := range sb.keys {
|
||||
if otherAddr.Original == addr.Original {
|
||||
continue
|
||||
}
|
||||
if otherAddr.Host != "" && otherAddr.Scheme != "http" && otherAddr.Port != httpPort {
|
||||
httpsHostsSharedWithHostlessKey[otherAddr.Host] = struct{}{}
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -134,6 +129,19 @@ func (st ServerType) buildTLSApp(
|
||||
issuers = append(issuers, issuerVal.Value.(certmagic.Issuer))
|
||||
}
|
||||
if ap == catchAllAP && !reflect.DeepEqual(ap.Issuers, issuers) {
|
||||
// this more correctly implements an error check that was removed
|
||||
// below; try it with this config:
|
||||
//
|
||||
// :443 {
|
||||
// bind 127.0.0.1
|
||||
// }
|
||||
//
|
||||
// :443 {
|
||||
// bind ::1
|
||||
// tls {
|
||||
// issuer acme
|
||||
// }
|
||||
// }
|
||||
return nil, warnings, fmt.Errorf("automation policy from site block is also default/catch-all policy because of key without hostname, and the two are in conflict: %#v != %#v", ap.Issuers, issuers)
|
||||
}
|
||||
ap.Issuers = issuers
|
||||
@@ -176,34 +184,30 @@ func (st ServerType) buildTLSApp(
|
||||
}
|
||||
}
|
||||
|
||||
// first make sure this block is allowed to create an automation policy;
|
||||
// doing so is forbidden if it has a key with no host (i.e. ":443")
|
||||
// we used to ensure this block is allowed to create an automation policy;
|
||||
// doing so was forbidden if it has a key with no host (i.e. ":443")
|
||||
// and if there is a different server block that also has a key with no
|
||||
// host -- since a key with no host matches any host, we need its
|
||||
// associated automation policy to have an empty Subjects list, i.e. no
|
||||
// host filter, which is indistinguishable between the two server blocks
|
||||
// because automation is not done in the context of a particular server...
|
||||
// this is an example of a poor mapping from Caddyfile to JSON but that's
|
||||
// the least-leaky abstraction I could figure out
|
||||
if len(sblockHosts) == 0 {
|
||||
if serverBlocksWithTLSHostlessKey > 1 {
|
||||
// this server block and at least one other has a key with no host,
|
||||
// making the two indistinguishable; it is misleading to define such
|
||||
// a policy within one server block since it actually will apply to
|
||||
// others as well
|
||||
return nil, warnings, fmt.Errorf("cannot make a TLS automation policy from a server block that has a host-less address when there are other TLS-enabled server block addresses lacking a host")
|
||||
}
|
||||
if catchAllAP == nil {
|
||||
// this server block has a key with no hosts, but there is not yet
|
||||
// a catch-all automation policy (probably because no global options
|
||||
// were set), so this one becomes it
|
||||
catchAllAP = ap
|
||||
}
|
||||
// the least-leaky abstraction I could figure out -- however, this check
|
||||
// was preventing certain listeners, like those provided by plugins, from
|
||||
// being used as desired (see the Tailscale listener plugin), so I removed
|
||||
// the check: and I think since I originally wrote the check I added a new
|
||||
// check above which *properly* detects this ambiguity without breaking the
|
||||
// listener plugin; see the check above with a commented example config
|
||||
if len(sblockHosts) == 0 && catchAllAP == nil {
|
||||
// this server block has a key with no hosts, but there is not yet
|
||||
// a catch-all automation policy (probably because no global options
|
||||
// were set), so this one becomes it
|
||||
catchAllAP = ap
|
||||
}
|
||||
|
||||
// associate our new automation policy with this server block's hosts
|
||||
ap.Subjects = sblock.hostsFromKeysNotHTTP(httpPort)
|
||||
sort.Strings(ap.Subjects) // solely for deterministic test results
|
||||
ap.SubjectsRaw = sblock.hostsFromKeysNotHTTP(httpPort)
|
||||
sort.Strings(ap.SubjectsRaw) // solely for deterministic test results
|
||||
|
||||
// if a combination of public and internal names were given
|
||||
// for this same server block and no issuer was specified, we
|
||||
@@ -213,7 +217,11 @@ func (st ServerType) buildTLSApp(
|
||||
var ap2 *caddytls.AutomationPolicy
|
||||
if len(ap.Issuers) == 0 {
|
||||
var internal, external []string
|
||||
for _, s := range ap.Subjects {
|
||||
for _, s := range ap.SubjectsRaw {
|
||||
// do not create Issuers for Tailscale domains; they will be given a Manager instead
|
||||
if strings.HasSuffix(strings.ToLower(s), ".ts.net") {
|
||||
continue
|
||||
}
|
||||
if !certmagic.SubjectQualifiesForCert(s) {
|
||||
return nil, warnings, fmt.Errorf("subject does not qualify for certificate: '%s'", s)
|
||||
}
|
||||
@@ -231,10 +239,10 @@ func (st ServerType) buildTLSApp(
|
||||
}
|
||||
}
|
||||
if len(external) > 0 && len(internal) > 0 {
|
||||
ap.Subjects = external
|
||||
ap.SubjectsRaw = external
|
||||
apCopy := *ap
|
||||
ap2 = &apCopy
|
||||
ap2.Subjects = internal
|
||||
ap2.SubjectsRaw = internal
|
||||
ap2.IssuersRaw = []json.RawMessage{caddyconfig.JSONModuleObject(caddytls.InternalIssuer{}, "module", "internal", &warnings)}
|
||||
}
|
||||
}
|
||||
@@ -331,16 +339,18 @@ func (st ServerType) buildTLSApp(
|
||||
internalAP := &caddytls.AutomationPolicy{
|
||||
IssuersRaw: []json.RawMessage{json.RawMessage(`{"module":"internal"}`)},
|
||||
}
|
||||
for h := range httpsHostsSharedWithHostlessKey {
|
||||
al = append(al, h)
|
||||
if !certmagic.SubjectQualifiesForPublicCert(h) {
|
||||
internalAP.Subjects = append(internalAP.Subjects, h)
|
||||
if autoHTTPS != "off" {
|
||||
for h := range httpsHostsSharedWithHostlessKey {
|
||||
al = append(al, h)
|
||||
if !certmagic.SubjectQualifiesForPublicCert(h) {
|
||||
internalAP.SubjectsRaw = append(internalAP.SubjectsRaw, h)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(al) > 0 {
|
||||
tlsApp.CertificatesRaw["automate"] = caddyconfig.JSON(al, &warnings)
|
||||
}
|
||||
if len(internalAP.Subjects) > 0 {
|
||||
if len(internalAP.SubjectsRaw) > 0 {
|
||||
if tlsApp.Automation == nil {
|
||||
tlsApp.Automation = new(caddytls.AutomationConfig)
|
||||
}
|
||||
@@ -406,7 +416,7 @@ func (st ServerType) buildTLSApp(
|
||||
// for convenience)
|
||||
automationHostSet := make(map[string]struct{})
|
||||
for _, ap := range tlsApp.Automation.Policies {
|
||||
for _, s := range ap.Subjects {
|
||||
for _, s := range ap.SubjectsRaw {
|
||||
if _, ok := automationHostSet[s]; ok {
|
||||
return nil, warnings, fmt.Errorf("hostname appears in more than one automation policy, making certificate management ambiguous: %s", s)
|
||||
}
|
||||
@@ -527,7 +537,7 @@ func consolidateAutomationPolicies(aps []*caddytls.AutomationPolicy) []*caddytls
|
||||
if automationPolicyIsSubset(aps[j], aps[i]) {
|
||||
return false
|
||||
}
|
||||
return len(aps[i].Subjects) > len(aps[j].Subjects)
|
||||
return len(aps[i].SubjectsRaw) > len(aps[j].SubjectsRaw)
|
||||
})
|
||||
|
||||
emptyAPCount := 0
|
||||
@@ -535,7 +545,7 @@ func consolidateAutomationPolicies(aps []*caddytls.AutomationPolicy) []*caddytls
|
||||
// compute the number of empty policies (disregarding subjects) - see #4128
|
||||
emptyAP := new(caddytls.AutomationPolicy)
|
||||
for i := 0; i < len(aps); i++ {
|
||||
emptyAP.Subjects = aps[i].Subjects
|
||||
emptyAP.SubjectsRaw = aps[i].SubjectsRaw
|
||||
if reflect.DeepEqual(aps[i], emptyAP) {
|
||||
emptyAPCount++
|
||||
if !automationPolicyHasAllPublicNames(aps[i]) {
|
||||
@@ -577,7 +587,7 @@ outer:
|
||||
aps[i].KeyType == aps[j].KeyType &&
|
||||
aps[i].OnDemand == aps[j].OnDemand &&
|
||||
aps[i].RenewalWindowRatio == aps[j].RenewalWindowRatio {
|
||||
if len(aps[i].Subjects) > 0 && len(aps[j].Subjects) == 0 {
|
||||
if len(aps[i].SubjectsRaw) > 0 && len(aps[j].SubjectsRaw) == 0 {
|
||||
// later policy (at j) has no subjects ("catch-all"), so we can
|
||||
// remove the identical-but-more-specific policy that comes first
|
||||
// AS LONG AS it is not shadowed by another policy before it; e.g.
|
||||
@@ -592,9 +602,9 @@ outer:
|
||||
}
|
||||
} else {
|
||||
// avoid repeated subjects
|
||||
for _, subj := range aps[j].Subjects {
|
||||
if !sliceContains(aps[i].Subjects, subj) {
|
||||
aps[i].Subjects = append(aps[i].Subjects, subj)
|
||||
for _, subj := range aps[j].SubjectsRaw {
|
||||
if !sliceContains(aps[i].SubjectsRaw, subj) {
|
||||
aps[i].SubjectsRaw = append(aps[i].SubjectsRaw, subj)
|
||||
}
|
||||
}
|
||||
aps = append(aps[:j], aps[j+1:]...)
|
||||
@@ -610,15 +620,15 @@ outer:
|
||||
// automationPolicyIsSubset returns true if a's subjects are a subset
|
||||
// of b's subjects.
|
||||
func automationPolicyIsSubset(a, b *caddytls.AutomationPolicy) bool {
|
||||
if len(b.Subjects) == 0 {
|
||||
if len(b.SubjectsRaw) == 0 {
|
||||
return true
|
||||
}
|
||||
if len(a.Subjects) == 0 {
|
||||
if len(a.SubjectsRaw) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, aSubj := range a.Subjects {
|
||||
for _, aSubj := range a.SubjectsRaw {
|
||||
var inSuperset bool
|
||||
for _, bSubj := range b.Subjects {
|
||||
for _, bSubj := range b.SubjectsRaw {
|
||||
if certmagic.MatchWildcard(aSubj, bSubj) {
|
||||
inSuperset = true
|
||||
break
|
||||
@@ -656,7 +666,7 @@ func subjectQualifiesForPublicCert(ap *caddytls.AutomationPolicy, subj string) b
|
||||
}
|
||||
|
||||
func automationPolicyHasAllPublicNames(ap *caddytls.AutomationPolicy) bool {
|
||||
for _, subj := range ap.Subjects {
|
||||
for _, subj := range ap.SubjectsRaw {
|
||||
if !subjectQualifiesForPublicCert(ap, subj) {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -47,8 +47,8 @@ func TestAutomationPolicyIsSubset(t *testing.T) {
|
||||
expect: false,
|
||||
},
|
||||
} {
|
||||
apA := &caddytls.AutomationPolicy{Subjects: test.a}
|
||||
apB := &caddytls.AutomationPolicy{Subjects: test.b}
|
||||
apA := &caddytls.AutomationPolicy{SubjectsRaw: test.a}
|
||||
apB := &caddytls.AutomationPolicy{SubjectsRaw: test.b}
|
||||
if actual := automationPolicyIsSubset(apA, apB); actual != test.expect {
|
||||
t.Errorf("Test %d: Expected %t but got %t (A: %v B: %v)", i, test.expect, actual, test.a, test.b)
|
||||
}
|
||||
|
||||
@@ -30,8 +30,14 @@ func init() {
|
||||
caddy.RegisterModule(HTTPLoader{})
|
||||
}
|
||||
|
||||
// HTTPLoader can load Caddy configs over HTTP(S). It can adapt the config
|
||||
// based on the Content-Type header of the HTTP response.
|
||||
// HTTPLoader can load Caddy configs over HTTP(S).
|
||||
//
|
||||
// If the response is not a JSON config, a config adapter must be specified
|
||||
// either in the loader config (`adapter`), or in the Content-Type HTTP header
|
||||
// returned in the HTTP response from the server. The Content-Type header is
|
||||
// read just like the admin API's `/load` endpoint. Uf you don't have control
|
||||
// over the HTTP server (but can still trust its response), you can override
|
||||
// the Content-Type header by setting the `adapter` property in this config.
|
||||
type HTTPLoader struct {
|
||||
// The method for the request. Default: GET
|
||||
Method string `json:"method,omitempty"`
|
||||
@@ -45,6 +51,11 @@ type HTTPLoader struct {
|
||||
// Maximum time allowed for a complete connection and request.
|
||||
Timeout caddy.Duration `json:"timeout,omitempty"`
|
||||
|
||||
// The name of the config adapter to use, if any. Only needed
|
||||
// if the HTTP response is not a JSON config and if the server's
|
||||
// Content-Type header is missing or incorrect.
|
||||
Adapter string `json:"adapter,omitempty"`
|
||||
|
||||
TLS *struct {
|
||||
// Present this instance's managed remote identity credentials to the server.
|
||||
UseServerIdentity bool `json:"use_server_identity,omitempty"`
|
||||
@@ -94,7 +105,7 @@ func (hl HTTPLoader) LoadConfig(ctx caddy.Context) ([]byte, error) {
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
resp, err := doHttpCallWithRetries(ctx, client, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -108,7 +119,12 @@ func (hl HTTPLoader) LoadConfig(ctx caddy.Context) ([]byte, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result, warnings, err := adaptByContentType(resp.Header.Get("Content-Type"), body)
|
||||
// adapt the config based on either manually-configured adapter or server's response header
|
||||
ct := resp.Header.Get("Content-Type")
|
||||
if hl.Adapter != "" {
|
||||
ct = "text/" + hl.Adapter
|
||||
}
|
||||
result, warnings, err := adaptByContentType(ct, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -119,6 +135,38 @@ func (hl HTTPLoader) LoadConfig(ctx caddy.Context) ([]byte, error) {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func attemptHttpCall(client *http.Client, request *http.Request) (*http.Response, error) {
|
||||
resp, err := client.Do(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("problem calling http loader url: %v", err)
|
||||
} else if resp.StatusCode < 200 || resp.StatusCode > 499 {
|
||||
resp.Body.Close()
|
||||
return nil, fmt.Errorf("bad response status code from http loader url: %v", resp.StatusCode)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func doHttpCallWithRetries(ctx caddy.Context, client *http.Client, request *http.Request) (*http.Response, error) {
|
||||
var resp *http.Response
|
||||
var err error
|
||||
const maxAttempts = 10
|
||||
|
||||
for i := 0; i < maxAttempts; i++ {
|
||||
resp, err = attemptHttpCall(client, request)
|
||||
if err != nil && i < maxAttempts-1 {
|
||||
select {
|
||||
case <-time.After(time.Millisecond * 500):
|
||||
case <-ctx.Done():
|
||||
return resp, ctx.Err()
|
||||
}
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (hl HTTPLoader) makeClient(ctx caddy.Context) (*http.Client, error) {
|
||||
client := &http.Client{
|
||||
Timeout: time.Duration(hl.Timeout),
|
||||
|
||||
+24
-7
@@ -114,7 +114,7 @@ func (tc *Tester) initServer(rawConfig string, configType string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
err := validateTestPrerequisites()
|
||||
err := validateTestPrerequisites(tc.t)
|
||||
if err != nil {
|
||||
tc.t.Skipf("skipping tests as failed integration prerequisites. %s", err)
|
||||
return nil
|
||||
@@ -214,19 +214,24 @@ func (tc *Tester) ensureConfigRunning(rawConfig string, configType string) error
|
||||
return actual
|
||||
}
|
||||
|
||||
for retries := 4; retries > 0; retries-- {
|
||||
for retries := 10; retries > 0; retries-- {
|
||||
if reflect.DeepEqual(expected, fetchConfig(client)) {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
tc.t.Errorf("POSTed configuration isn't active")
|
||||
return errors.New("EnsureConfigRunning: POSTed configuration isn't active")
|
||||
}
|
||||
|
||||
const initConfig = `{
|
||||
admin localhost:2999
|
||||
}
|
||||
`
|
||||
|
||||
// validateTestPrerequisites ensures the certificates are available in the
|
||||
// designated path and Caddy sub-process is running.
|
||||
func validateTestPrerequisites() error {
|
||||
func validateTestPrerequisites(t *testing.T) error {
|
||||
|
||||
// check certificates are found
|
||||
for _, certName := range Default.Certifcates {
|
||||
@@ -236,15 +241,27 @@ func validateTestPrerequisites() error {
|
||||
}
|
||||
|
||||
if isCaddyAdminRunning() != nil {
|
||||
// setup the init config file, and set the cleanup afterwards
|
||||
f, err := os.CreateTemp("", "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
os.Remove(f.Name())
|
||||
})
|
||||
if _, err := f.WriteString(initConfig); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// start inprocess caddy server
|
||||
os.Args = []string{"caddy", "run"}
|
||||
os.Args = []string{"caddy", "run", "--config", f.Name(), "--adapter", "caddyfile"}
|
||||
go func() {
|
||||
caddycmd.Main()
|
||||
}()
|
||||
|
||||
// wait for caddy to start serving the initial config
|
||||
for retries := 4; retries > 0 && isCaddyAdminRunning() != nil; retries-- {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
for retries := 10; retries > 0 && isCaddyAdminRunning() != nil; retries-- {
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ func TestAutoHTTPtoHTTPSRedirectsImplicitPort(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
admin localhost:2999
|
||||
skip_install_trust
|
||||
http_port 9080
|
||||
https_port 9443
|
||||
}
|
||||
@@ -25,6 +27,8 @@ func TestAutoHTTPtoHTTPSRedirectsExplicitPortSameAsHTTPSPort(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
skip_install_trust
|
||||
admin localhost:2999
|
||||
http_port 9080
|
||||
https_port 9443
|
||||
}
|
||||
@@ -39,6 +43,8 @@ func TestAutoHTTPtoHTTPSRedirectsExplicitPortDifferentFromHTTPSPort(t *testing.T
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
skip_install_trust
|
||||
admin localhost:2999
|
||||
http_port 9080
|
||||
https_port 9443
|
||||
}
|
||||
@@ -53,6 +59,9 @@ func TestAutoHTTPRedirectsWithHTTPListenerFirstInAddresses(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
"admin": {
|
||||
"listen": "localhost:2999"
|
||||
},
|
||||
"apps": {
|
||||
"http": {
|
||||
"http_port": 9080,
|
||||
@@ -74,7 +83,14 @@ func TestAutoHTTPRedirectsWithHTTPListenerFirstInAddresses(t *testing.T) {
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"pki": {
|
||||
"certificate_authorities": {
|
||||
"local": {
|
||||
"install_trust": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`, "json")
|
||||
@@ -85,6 +101,8 @@ func TestAutoHTTPRedirectsInsertedBeforeUserDefinedCatchAll(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
skip_install_trust
|
||||
admin localhost:2999
|
||||
http_port 9080
|
||||
https_port 9443
|
||||
local_certs
|
||||
@@ -108,6 +126,8 @@ func TestAutoHTTPRedirectsInsertedBeforeUserDefinedCatchAllWithNoExplicitHTTPSit
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
skip_install_trust
|
||||
admin localhost:2999
|
||||
http_port 9080
|
||||
https_port 9443
|
||||
local_certs
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
{
|
||||
pki {
|
||||
ca internal {
|
||||
name "Internal"
|
||||
root_cn "Internal Root Cert"
|
||||
intermediate_cn "Internal Intermediate Cert"
|
||||
}
|
||||
ca internal-long-lived {
|
||||
name "Long-lived"
|
||||
root_cn "Internal Root Cert 2"
|
||||
intermediate_cn "Internal Intermediate Cert 2"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
acme-internal.example.com {
|
||||
acme_server {
|
||||
ca internal
|
||||
}
|
||||
}
|
||||
|
||||
acme-long-lived.example.com {
|
||||
acme_server {
|
||||
ca internal-long-lived
|
||||
lifetime 7d
|
||||
}
|
||||
}
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"acme-long-lived.example.com"
|
||||
]
|
||||
}
|
||||
],
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"ca": "internal-long-lived",
|
||||
"handler": "acme_server",
|
||||
"lifetime": 604800000000000
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
},
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"acme-internal.example.com"
|
||||
]
|
||||
}
|
||||
],
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"ca": "internal",
|
||||
"handler": "acme_server"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"pki": {
|
||||
"certificate_authorities": {
|
||||
"internal": {
|
||||
"name": "Internal",
|
||||
"root_common_name": "Internal Root Cert",
|
||||
"intermediate_common_name": "Internal Intermediate Cert"
|
||||
},
|
||||
"internal-long-lived": {
|
||||
"name": "Long-lived",
|
||||
"root_common_name": "Internal Root Cert 2",
|
||||
"intermediate_common_name": "Internal Intermediate Cert 2"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
{
|
||||
http_port 8080
|
||||
persist_config off
|
||||
admin {
|
||||
origins localhost:2019 [::1]:2019 127.0.0.1:2019 192.168.10.128
|
||||
}
|
||||
}
|
||||
|
||||
:80
|
||||
----------
|
||||
{
|
||||
"admin": {
|
||||
"listen": "localhost:2019",
|
||||
"origins": [
|
||||
"localhost:2019",
|
||||
"[::1]:2019",
|
||||
"127.0.0.1:2019",
|
||||
"192.168.10.128"
|
||||
],
|
||||
"config": {
|
||||
"persist": false
|
||||
}
|
||||
},
|
||||
"apps": {
|
||||
"http": {
|
||||
"http_port": 8080,
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":80"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
persist_config off
|
||||
}
|
||||
|
||||
:8881 {
|
||||
}
|
||||
----------
|
||||
{
|
||||
"admin": {
|
||||
"config": {
|
||||
"persist": false
|
||||
}
|
||||
},
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":8881"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -165,4 +165,4 @@ acme-bar.example.com {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,9 +3,7 @@
|
||||
timeouts {
|
||||
idle 90s
|
||||
}
|
||||
protocol {
|
||||
strict_sni_host insecure_off
|
||||
}
|
||||
strict_sni_host insecure_off
|
||||
}
|
||||
servers :80 {
|
||||
timeouts {
|
||||
@@ -16,9 +14,7 @@
|
||||
timeouts {
|
||||
idle 30s
|
||||
}
|
||||
protocol {
|
||||
strict_sni_host
|
||||
}
|
||||
strict_sni_host
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,9 +11,13 @@
|
||||
idle 30s
|
||||
}
|
||||
max_header_size 100MB
|
||||
enable_full_duplex
|
||||
log_credentials
|
||||
protocols h1 h2 h2c h3
|
||||
strict_sni_host
|
||||
trusted_proxies static private_ranges
|
||||
client_ip_headers Custom-Real-Client-IP X-Forwarded-For
|
||||
client_ip_headers A-Third-One
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +46,7 @@ foo.com {
|
||||
"write_timeout": 30000000000,
|
||||
"idle_timeout": 30000000000,
|
||||
"max_header_bytes": 100000000,
|
||||
"enable_full_duplex": true,
|
||||
"routes": [
|
||||
{
|
||||
"match": [
|
||||
@@ -55,6 +60,22 @@ foo.com {
|
||||
}
|
||||
],
|
||||
"strict_sni_host": true,
|
||||
"trusted_proxies": {
|
||||
"ranges": [
|
||||
"192.168.0.0/16",
|
||||
"172.16.0.0/12",
|
||||
"10.0.0.0/8",
|
||||
"127.0.0.1/8",
|
||||
"fd00::/8",
|
||||
"::1"
|
||||
],
|
||||
"source": "static"
|
||||
},
|
||||
"client_ip_headers": [
|
||||
"Custom-Real-Client-IP",
|
||||
"X-Forwarded-For",
|
||||
"A-Third-One"
|
||||
],
|
||||
"logs": {
|
||||
"should_log_credentials": true
|
||||
},
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
:8881 {
|
||||
route {
|
||||
handle /foo/* {
|
||||
respond "Foo"
|
||||
}
|
||||
handle {
|
||||
respond "Bar"
|
||||
}
|
||||
}
|
||||
}
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":8881"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"group": "group2",
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "Foo",
|
||||
"handler": "static_response"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"path": [
|
||||
"/foo/*"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "group2",
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "Bar",
|
||||
"handler": "static_response"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@
|
||||
+Link "Foo"
|
||||
+Link "Bar"
|
||||
}
|
||||
header >Set Defer
|
||||
header >Replace Deferred Replacement
|
||||
}
|
||||
----------
|
||||
{
|
||||
@@ -136,6 +138,31 @@
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"handler": "headers",
|
||||
"response": {
|
||||
"deferred": true,
|
||||
"set": {
|
||||
"Set": [
|
||||
"Defer"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"handler": "headers",
|
||||
"response": {
|
||||
"deferred": true,
|
||||
"replace": {
|
||||
"Replace": [
|
||||
{
|
||||
"replace": "Replacement",
|
||||
"search_regexp": "Deferred"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
example.com {
|
||||
respond <<EOF
|
||||
<html>
|
||||
<head><title>Foo</title>
|
||||
<body>Foo</body>
|
||||
</html>
|
||||
EOF 200
|
||||
}
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"example.com"
|
||||
]
|
||||
}
|
||||
],
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "\u003chtml\u003e\n \u003chead\u003e\u003ctitle\u003eFoo\u003c/title\u003e\n \u003cbody\u003eFoo\u003c/body\u003e\n\u003c/html\u003e",
|
||||
"handler": "static_response",
|
||||
"status_code": 200
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
(logging) {
|
||||
log {
|
||||
output file /var/log/caddy/{args.0}.access.log
|
||||
output file /var/log/caddy/{args[0]}.access.log
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
&(first) {
|
||||
@first path /first
|
||||
vars @first first 1
|
||||
respond "first"
|
||||
}
|
||||
|
||||
&(second) {
|
||||
respond "second"
|
||||
}
|
||||
|
||||
:8881 {
|
||||
invoke first
|
||||
route {
|
||||
invoke second
|
||||
}
|
||||
}
|
||||
|
||||
:8882 {
|
||||
handle {
|
||||
invoke second
|
||||
}
|
||||
}
|
||||
|
||||
:8883 {
|
||||
respond "no invoke"
|
||||
}
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":8881"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "invoke",
|
||||
"name": "first"
|
||||
},
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "invoke",
|
||||
"name": "second"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"named_routes": {
|
||||
"first": {
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"first": 1,
|
||||
"handler": "vars"
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"path": [
|
||||
"/first"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "first",
|
||||
"handler": "static_response"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"second": {
|
||||
"handle": [
|
||||
{
|
||||
"body": "second",
|
||||
"handler": "static_response"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"srv1": {
|
||||
"listen": [
|
||||
":8882"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "invoke",
|
||||
"name": "second"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"named_routes": {
|
||||
"second": {
|
||||
"handle": [
|
||||
{
|
||||
"body": "second",
|
||||
"handler": "static_response"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"srv2": {
|
||||
"listen": [
|
||||
":8883"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "no invoke",
|
||||
"handler": "static_response"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
*.example.com {
|
||||
log {
|
||||
hostnames foo.example.com bar.example.com
|
||||
output file /foo-bar.txt
|
||||
}
|
||||
log {
|
||||
hostnames baz.example.com
|
||||
output file /baz.txt
|
||||
}
|
||||
}
|
||||
----------
|
||||
{
|
||||
"logging": {
|
||||
"logs": {
|
||||
"default": {
|
||||
"exclude": [
|
||||
"http.log.access.log0",
|
||||
"http.log.access.log1"
|
||||
]
|
||||
},
|
||||
"log0": {
|
||||
"writer": {
|
||||
"filename": "/foo-bar.txt",
|
||||
"output": "file"
|
||||
},
|
||||
"include": [
|
||||
"http.log.access.log0"
|
||||
]
|
||||
},
|
||||
"log1": {
|
||||
"writer": {
|
||||
"filename": "/baz.txt",
|
||||
"output": "file"
|
||||
},
|
||||
"include": [
|
||||
"http.log.access.log1"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"*.example.com"
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
],
|
||||
"logs": {
|
||||
"logger_names": {
|
||||
"bar.example.com": "log0",
|
||||
"baz.example.com": "log1",
|
||||
"foo.example.com": "log0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
{
|
||||
log access-console {
|
||||
include http.log.access.foo
|
||||
output file access-localhost.log
|
||||
format console
|
||||
}
|
||||
|
||||
log access-json {
|
||||
include http.log.access.foo
|
||||
output file access-localhost.json
|
||||
format json
|
||||
}
|
||||
}
|
||||
|
||||
http://localhost:8881 {
|
||||
log foo
|
||||
}
|
||||
----------
|
||||
{
|
||||
"logging": {
|
||||
"logs": {
|
||||
"access-console": {
|
||||
"writer": {
|
||||
"filename": "access-localhost.log",
|
||||
"output": "file"
|
||||
},
|
||||
"encoder": {
|
||||
"format": "console"
|
||||
},
|
||||
"include": [
|
||||
"http.log.access.foo"
|
||||
]
|
||||
},
|
||||
"access-json": {
|
||||
"writer": {
|
||||
"filename": "access-localhost.json",
|
||||
"output": "file"
|
||||
},
|
||||
"encoder": {
|
||||
"format": "json"
|
||||
},
|
||||
"include": [
|
||||
"http.log.access.foo"
|
||||
]
|
||||
},
|
||||
"default": {
|
||||
"exclude": [
|
||||
"http.log.access.foo"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":8881"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"localhost"
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
],
|
||||
"automatic_https": {
|
||||
"skip": [
|
||||
"localhost"
|
||||
]
|
||||
},
|
||||
"logs": {
|
||||
"logger_names": {
|
||||
"localhost:8881": "foo"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
{
|
||||
debug
|
||||
|
||||
log access-console {
|
||||
include http.log.access.foo
|
||||
output file access-localhost.log
|
||||
format console
|
||||
}
|
||||
|
||||
log access-json {
|
||||
include http.log.access.foo
|
||||
output file access-localhost.json
|
||||
format json
|
||||
}
|
||||
}
|
||||
|
||||
http://localhost:8881 {
|
||||
log foo
|
||||
}
|
||||
----------
|
||||
{
|
||||
"logging": {
|
||||
"logs": {
|
||||
"access-console": {
|
||||
"writer": {
|
||||
"filename": "access-localhost.log",
|
||||
"output": "file"
|
||||
},
|
||||
"encoder": {
|
||||
"format": "console"
|
||||
},
|
||||
"level": "DEBUG",
|
||||
"include": [
|
||||
"http.log.access.foo"
|
||||
]
|
||||
},
|
||||
"access-json": {
|
||||
"writer": {
|
||||
"filename": "access-localhost.json",
|
||||
"output": "file"
|
||||
},
|
||||
"encoder": {
|
||||
"format": "json"
|
||||
},
|
||||
"level": "DEBUG",
|
||||
"include": [
|
||||
"http.log.access.foo"
|
||||
]
|
||||
},
|
||||
"default": {
|
||||
"level": "DEBUG",
|
||||
"exclude": [
|
||||
"http.log.access.foo"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":8881"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"localhost"
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
],
|
||||
"automatic_https": {
|
||||
"skip": [
|
||||
"localhost"
|
||||
]
|
||||
},
|
||||
"logs": {
|
||||
"logger_names": {
|
||||
"localhost:8881": "foo"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,9 @@ example.com {
|
||||
}
|
||||
],
|
||||
"logs": {
|
||||
"logger_names": {
|
||||
"one.example.com": ""
|
||||
},
|
||||
"skip_hosts": [
|
||||
"three.example.com",
|
||||
"two.example.com",
|
||||
|
||||
@@ -100,16 +100,16 @@ vars {
|
||||
],
|
||||
"source": "{http.request.host}"
|
||||
},
|
||||
{
|
||||
"foo": "bar",
|
||||
"handler": "vars"
|
||||
},
|
||||
{
|
||||
"abc": true,
|
||||
"def": 1,
|
||||
"ghi": 2.3,
|
||||
"handler": "vars",
|
||||
"jkl": "mn op"
|
||||
},
|
||||
{
|
||||
"foo": "bar",
|
||||
"handler": "vars"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -43,6 +43,9 @@
|
||||
|
||||
@matcher11 remote_ip private_ranges
|
||||
respond @matcher11 "remote_ip matcher with private ranges"
|
||||
|
||||
@matcher12 client_ip private_ranges
|
||||
respond @matcher12 "client_ip matcher with private ranges"
|
||||
}
|
||||
----------
|
||||
{
|
||||
@@ -250,6 +253,28 @@
|
||||
"handler": "static_response"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"client_ip": {
|
||||
"ranges": [
|
||||
"192.168.0.0/16",
|
||||
"172.16.0.0/12",
|
||||
"10.0.0.0/8",
|
||||
"127.0.0.1/8",
|
||||
"fd00::/8",
|
||||
"::1"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"handle": [
|
||||
{
|
||||
"body": "client_ip matcher with private ranges",
|
||||
"handler": "static_response"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ route {
|
||||
}
|
||||
not path */
|
||||
}
|
||||
redir @canonicalPath {path}/ 308
|
||||
redir @canonicalPath {http.request.orig_uri.path}/ 308
|
||||
|
||||
# If the requested file does not exist, try index files
|
||||
@indexFiles {
|
||||
@@ -50,7 +50,7 @@ route {
|
||||
"handler": "static_response",
|
||||
"headers": {
|
||||
"Location": [
|
||||
"{http.request.uri.path}/"
|
||||
"{http.request.orig_uri.path}/"
|
||||
]
|
||||
},
|
||||
"status_code": 308
|
||||
@@ -74,6 +74,7 @@ route {
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "group0",
|
||||
"handle": [
|
||||
{
|
||||
"handler": "rewrite",
|
||||
@@ -129,4 +130,4 @@ route {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
"handler": "static_response",
|
||||
"headers": {
|
||||
"Location": [
|
||||
"{http.request.uri.path}/"
|
||||
"{http.request.orig_uri.path}/"
|
||||
]
|
||||
},
|
||||
"status_code": 308
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
:8884
|
||||
|
||||
@api host example.com
|
||||
php_fastcgi @api localhost:9000
|
||||
# the use of a host matcher here should cause this
|
||||
# site block to be wrapped in a subroute, even though
|
||||
# the site block does not have a hostname; this is
|
||||
# to prevent auto-HTTPS from picking up on this host
|
||||
# matcher because it is not a key on the site block
|
||||
@test host example.com
|
||||
php_fastcgi @test localhost:9000
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
@@ -13,13 +18,6 @@ php_fastcgi @api localhost:9000
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"example.com"
|
||||
]
|
||||
}
|
||||
],
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
@@ -27,82 +25,99 @@ php_fastcgi @api localhost:9000
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "static_response",
|
||||
"headers": {
|
||||
"Location": [
|
||||
"{http.request.uri.path}/"
|
||||
]
|
||||
},
|
||||
"status_code": 308
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"file": {
|
||||
"try_files": [
|
||||
"{http.request.uri.path}/index.php"
|
||||
]
|
||||
},
|
||||
"not": [
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"path": [
|
||||
"*/"
|
||||
"handle": [
|
||||
{
|
||||
"handler": "static_response",
|
||||
"headers": {
|
||||
"Location": [
|
||||
"{http.request.orig_uri.path}/"
|
||||
]
|
||||
},
|
||||
"status_code": 308
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"file": {
|
||||
"try_files": [
|
||||
"{http.request.uri.path}/index.php"
|
||||
]
|
||||
},
|
||||
"not": [
|
||||
{
|
||||
"path": [
|
||||
"*/"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "rewrite",
|
||||
"uri": "{http.matchers.file.relative}"
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"file": {
|
||||
"split_path": [
|
||||
".php"
|
||||
],
|
||||
"try_files": [
|
||||
"{http.request.uri.path}",
|
||||
"{http.request.uri.path}/index.php",
|
||||
"index.php"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "reverse_proxy",
|
||||
"transport": {
|
||||
"protocol": "fastcgi",
|
||||
"split_path": [
|
||||
".php"
|
||||
]
|
||||
},
|
||||
"upstreams": [
|
||||
{
|
||||
"dial": "localhost:9000"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"path": [
|
||||
"*.php"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "rewrite",
|
||||
"uri": "{http.matchers.file.relative}"
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"file": {
|
||||
"split_path": [
|
||||
".php"
|
||||
],
|
||||
"try_files": [
|
||||
"{http.request.uri.path}",
|
||||
"{http.request.uri.path}/index.php",
|
||||
"index.php"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "reverse_proxy",
|
||||
"transport": {
|
||||
"protocol": "fastcgi",
|
||||
"split_path": [
|
||||
".php"
|
||||
]
|
||||
},
|
||||
"upstreams": [
|
||||
{
|
||||
"dial": "localhost:9000"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"path": [
|
||||
"*.php"
|
||||
"host": [
|
||||
"example.com"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ php_fastcgi localhost:9000 {
|
||||
"handler": "static_response",
|
||||
"headers": {
|
||||
"Location": [
|
||||
"{http.request.uri.path}/"
|
||||
"{http.request.orig_uri.path}/"
|
||||
]
|
||||
},
|
||||
"status_code": 308
|
||||
|
||||
@@ -46,7 +46,7 @@ php_fastcgi localhost:9000 {
|
||||
"handler": "static_response",
|
||||
"headers": {
|
||||
"Location": [
|
||||
"{http.request.uri.path}/"
|
||||
"{http.request.orig_uri.path}/"
|
||||
]
|
||||
},
|
||||
"status_code": 308
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
*.sandbox.localhost {
|
||||
@sandboxPort {
|
||||
header_regexp first_label Host ^([0-9]{3})\.sandbox\.
|
||||
}
|
||||
handle @sandboxPort {
|
||||
reverse_proxy {re.first_label.1}
|
||||
}
|
||||
handle {
|
||||
redir {scheme}://application.localhost
|
||||
}
|
||||
}
|
||||
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"*.sandbox.localhost"
|
||||
]
|
||||
}
|
||||
],
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"group": "group2",
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "reverse_proxy",
|
||||
"upstreams": [
|
||||
{
|
||||
"dial": "{http.regexp.first_label.1}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"header_regexp": {
|
||||
"Host": {
|
||||
"name": "first_label",
|
||||
"pattern": "^([0-9]{3})\\.sandbox\\."
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "group2",
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "static_response",
|
||||
"headers": {
|
||||
"Location": [
|
||||
"{http.request.scheme}://application.localhost"
|
||||
]
|
||||
},
|
||||
"status_code": 302
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
*.sandbox.localhost {
|
||||
@sandboxPort {
|
||||
header_regexp port Host ^([0-9]{3})\.sandbox\.
|
||||
}
|
||||
handle @sandboxPort {
|
||||
reverse_proxy app:6{re.port.1}
|
||||
}
|
||||
handle {
|
||||
redir {scheme}://application.localhost
|
||||
}
|
||||
}
|
||||
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"*.sandbox.localhost"
|
||||
]
|
||||
}
|
||||
],
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"group": "group2",
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "reverse_proxy",
|
||||
"upstreams": [
|
||||
{
|
||||
"dial": "app:6{http.regexp.port.1}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"header_regexp": {
|
||||
"Host": {
|
||||
"name": "port",
|
||||
"pattern": "^([0-9]{3})\\.sandbox\\."
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "group2",
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "static_response",
|
||||
"headers": {
|
||||
"Location": [
|
||||
"{http.request.scheme}://application.localhost"
|
||||
]
|
||||
},
|
||||
"status_code": 302
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
*.sandbox.localhost {
|
||||
@sandboxPort {
|
||||
header_regexp port Host ^([0-9]{3})\.sandbox\.
|
||||
}
|
||||
handle @sandboxPort {
|
||||
reverse_proxy app:{re.port.1}
|
||||
}
|
||||
handle {
|
||||
redir {scheme}://application.localhost
|
||||
}
|
||||
}
|
||||
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"*.sandbox.localhost"
|
||||
]
|
||||
}
|
||||
],
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"group": "group2",
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "reverse_proxy",
|
||||
"upstreams": [
|
||||
{
|
||||
"dial": "app:{http.regexp.port.1}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"header_regexp": {
|
||||
"Host": {
|
||||
"name": "port",
|
||||
"pattern": "^([0-9]{3})\\.sandbox\\."
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "group2",
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "static_response",
|
||||
"headers": {
|
||||
"Location": [
|
||||
"{http.request.scheme}://application.localhost"
|
||||
]
|
||||
},
|
||||
"status_code": 302
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
resolvers 8.8.8.8 8.8.4.4
|
||||
dial_timeout 2s
|
||||
dial_fallback_delay 300ms
|
||||
versions ipv6
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,7 +67,10 @@
|
||||
"8.8.4.4"
|
||||
]
|
||||
},
|
||||
"source": "a"
|
||||
"source": "a",
|
||||
"versions": {
|
||||
"ipv6": true
|
||||
}
|
||||
},
|
||||
"handler": "reverse_proxy"
|
||||
}
|
||||
@@ -113,4 +117,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
:8884
|
||||
|
||||
reverse_proxy 127.0.0.1:65535 127.0.0.1:35535 {
|
||||
lb_policy weighted_round_robin 10 1
|
||||
lb_retries 5
|
||||
lb_try_duration 10s
|
||||
lb_try_interval 500ms
|
||||
lb_retry_match {
|
||||
path /foo*
|
||||
method POST
|
||||
}
|
||||
lb_retry_match path /bar*
|
||||
}
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":8884"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "reverse_proxy",
|
||||
"load_balancing": {
|
||||
"retries": 5,
|
||||
"retry_match": [
|
||||
{
|
||||
"method": [
|
||||
"POST"
|
||||
],
|
||||
"path": [
|
||||
"/foo*"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": [
|
||||
"/bar*"
|
||||
]
|
||||
}
|
||||
],
|
||||
"selection_policy": {
|
||||
"policy": "weighted_round_robin",
|
||||
"weights": [
|
||||
10,
|
||||
1
|
||||
]
|
||||
},
|
||||
"try_duration": 10000000000,
|
||||
"try_interval": 500000000
|
||||
},
|
||||
"upstreams": [
|
||||
{
|
||||
"dial": "127.0.0.1:65535"
|
||||
},
|
||||
{
|
||||
"dial": "127.0.0.1:35535"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
https://example.com {
|
||||
reverse_proxy /path https://localhost:54321 {
|
||||
header_up Host {upstream_hostport}
|
||||
@@ -7,7 +6,7 @@ https://example.com {
|
||||
method GET
|
||||
rewrite /rewritten?uri={uri}
|
||||
|
||||
buffer_requests
|
||||
request_buffers 4KB
|
||||
|
||||
transport http {
|
||||
read_buffer 10MB
|
||||
@@ -24,13 +23,12 @@ https://example.com {
|
||||
max_conns_per_host 5
|
||||
keepalive_idle_conns_per_host 2
|
||||
keepalive_interval 30s
|
||||
|
||||
|
||||
tls_renegotiation freely
|
||||
tls_except_ports 8181 8182
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
@@ -56,7 +54,6 @@ https://example.com {
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"buffer_requests": true,
|
||||
"handler": "reverse_proxy",
|
||||
"headers": {
|
||||
"request": {
|
||||
@@ -70,6 +67,7 @@ https://example.com {
|
||||
}
|
||||
}
|
||||
},
|
||||
"request_buffers": 4000,
|
||||
"rewrite": {
|
||||
"method": "GET",
|
||||
"uri": "/rewritten?uri={http.request.uri}"
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
:8884 {
|
||||
# Port range
|
||||
reverse_proxy localhost:8001-8002
|
||||
|
||||
# Port range with placeholder
|
||||
reverse_proxy {host}:8001-8002
|
||||
|
||||
# Port range with scheme
|
||||
reverse_proxy https://localhost:8001-8002
|
||||
}
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":8884"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "reverse_proxy",
|
||||
"upstreams": [
|
||||
{
|
||||
"dial": "localhost:8001"
|
||||
},
|
||||
{
|
||||
"dial": "localhost:8002"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"handler": "reverse_proxy",
|
||||
"upstreams": [
|
||||
{
|
||||
"dial": "{http.request.host}:8001"
|
||||
},
|
||||
{
|
||||
"dial": "{http.request.host}:8002"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"handler": "reverse_proxy",
|
||||
"transport": {
|
||||
"protocol": "http",
|
||||
"tls": {}
|
||||
},
|
||||
"upstreams": [
|
||||
{
|
||||
"dial": "localhost:8001"
|
||||
},
|
||||
{
|
||||
"dial": "localhost:8002"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
{
|
||||
servers :443 {
|
||||
name https
|
||||
}
|
||||
|
||||
servers :8000 {
|
||||
name app1
|
||||
}
|
||||
|
||||
servers :8001 {
|
||||
name app2
|
||||
}
|
||||
|
||||
servers 123.123.123.123:8002 {
|
||||
name bind-server
|
||||
}
|
||||
}
|
||||
|
||||
example.com {
|
||||
}
|
||||
|
||||
:8000 {
|
||||
}
|
||||
|
||||
:8001, :8002 {
|
||||
}
|
||||
|
||||
:8002 {
|
||||
bind 123.123.123.123 222.222.222.222
|
||||
}
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"app1": {
|
||||
"listen": [
|
||||
":8000"
|
||||
]
|
||||
},
|
||||
"app2": {
|
||||
"listen": [
|
||||
":8001"
|
||||
]
|
||||
},
|
||||
"bind-server": {
|
||||
"listen": [
|
||||
"123.123.123.123:8002",
|
||||
"222.222.222.222:8002"
|
||||
]
|
||||
},
|
||||
"https": {
|
||||
"listen": [
|
||||
":443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"example.com"
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"srv4": {
|
||||
"listen": [
|
||||
":8002"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
*.example.com {
|
||||
@foo host foo.example.com
|
||||
handle @foo {
|
||||
handle_path /strip* {
|
||||
handle_path /strip {
|
||||
respond "this should be first"
|
||||
}
|
||||
handle {
|
||||
handle_path /strip* {
|
||||
respond "this should be second"
|
||||
}
|
||||
handle {
|
||||
respond "this should be last"
|
||||
}
|
||||
}
|
||||
handle {
|
||||
respond "this should be last"
|
||||
@@ -35,13 +38,13 @@
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"group": "group5",
|
||||
"group": "group6",
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"group": "group2",
|
||||
"group": "group3",
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
@@ -68,17 +71,25 @@
|
||||
"match": [
|
||||
{
|
||||
"path": [
|
||||
"/strip*"
|
||||
"/strip"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "group2",
|
||||
"group": "group3",
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "rewrite",
|
||||
"strip_path_prefix": "/strip"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
@@ -89,6 +100,31 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"path": [
|
||||
"/strip*"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "group3",
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "this should be last",
|
||||
"handler": "static_response"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -103,7 +139,7 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "group5",
|
||||
"group": "group6",
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
:80
|
||||
|
||||
vars /foobar foo last
|
||||
vars /foo foo middle
|
||||
vars /foo foo middle-last
|
||||
vars /foo* foo middle-first
|
||||
vars * foo first
|
||||
----------
|
||||
{
|
||||
@@ -21,6 +22,21 @@ vars * foo first
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"path": [
|
||||
"/foo*"
|
||||
]
|
||||
}
|
||||
],
|
||||
"handle": [
|
||||
{
|
||||
"foo": "middle-first",
|
||||
"handler": "vars"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
@@ -31,7 +47,7 @@ vars * foo first
|
||||
],
|
||||
"handle": [
|
||||
{
|
||||
"foo": "middle",
|
||||
"foo": "middle-last",
|
||||
"handler": "vars"
|
||||
}
|
||||
]
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# example from issue #4667
|
||||
{
|
||||
auto_https off
|
||||
}
|
||||
|
||||
https://, example.com {
|
||||
tls test.crt test.key
|
||||
respond "Hello World"
|
||||
}
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "Hello World",
|
||||
"handler": "static_response"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"tls_connection_policies": [
|
||||
{
|
||||
"certificate_selection": {
|
||||
"any_tag": [
|
||||
"cert0"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"automatic_https": {
|
||||
"disable": true
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"tls": {
|
||||
"certificates": {
|
||||
"load_files": [
|
||||
{
|
||||
"certificate": "test.crt",
|
||||
"key": "test.key",
|
||||
"tags": [
|
||||
"cert0"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
localhost
|
||||
|
||||
respond "hello from localhost"
|
||||
tls {
|
||||
dns_ttl 5m10s
|
||||
}
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"localhost"
|
||||
]
|
||||
}
|
||||
],
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "hello from localhost",
|
||||
"handler": "static_response"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"tls": {
|
||||
"automation": {
|
||||
"policies": [
|
||||
{
|
||||
"subjects": [
|
||||
"localhost"
|
||||
],
|
||||
"issuers": [
|
||||
{
|
||||
"challenges": {
|
||||
"dns": {
|
||||
"ttl": 310000000000
|
||||
}
|
||||
},
|
||||
"module": "acme"
|
||||
},
|
||||
{
|
||||
"challenges": {
|
||||
"dns": {
|
||||
"ttl": 310000000000
|
||||
}
|
||||
},
|
||||
"module": "zerossl"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
localhost
|
||||
|
||||
respond "hello from localhost"
|
||||
tls {
|
||||
issuer acme {
|
||||
dns_ttl 5m10s
|
||||
}
|
||||
issuer zerossl {
|
||||
dns_ttl 10m20s
|
||||
}
|
||||
}
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"localhost"
|
||||
]
|
||||
}
|
||||
],
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "hello from localhost",
|
||||
"handler": "static_response"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"tls": {
|
||||
"automation": {
|
||||
"policies": [
|
||||
{
|
||||
"subjects": [
|
||||
"localhost"
|
||||
],
|
||||
"issuers": [
|
||||
{
|
||||
"challenges": {
|
||||
"dns": {
|
||||
"ttl": 310000000000
|
||||
}
|
||||
},
|
||||
"module": "acme"
|
||||
},
|
||||
{
|
||||
"challenges": {
|
||||
"dns": {
|
||||
"ttl": 620000000000
|
||||
}
|
||||
},
|
||||
"module": "zerossl"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
localhost
|
||||
|
||||
respond "hello from localhost"
|
||||
tls {
|
||||
propagation_delay 5m10s
|
||||
propagation_timeout 10m20s
|
||||
}
|
||||
----------
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"localhost"
|
||||
]
|
||||
}
|
||||
],
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "hello from localhost",
|
||||
"handler": "static_response"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"tls": {
|
||||
"automation": {
|
||||
"policies": [
|
||||
{
|
||||
"subjects": [
|
||||
"localhost"
|
||||
],
|
||||
"issuers": [
|
||||
{
|
||||
"challenges": {
|
||||
"dns": {
|
||||
"propagation_delay": 310000000000,
|
||||
"propagation_timeout": 620000000000
|
||||
}
|
||||
},
|
||||
"module": "acme"
|
||||
},
|
||||
{
|
||||
"challenges": {
|
||||
"dns": {
|
||||
"propagation_delay": 310000000000,
|
||||
"propagation_timeout": 620000000000
|
||||
}
|
||||
},
|
||||
"module": "zerossl"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,9 +14,10 @@ func TestRespond(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
admin localhost:2999
|
||||
http_port 9080
|
||||
https_port 9443
|
||||
grace_period 1
|
||||
grace_period 1ns
|
||||
}
|
||||
|
||||
localhost:9080 {
|
||||
@@ -36,9 +37,10 @@ func TestRedirect(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
admin localhost:2999
|
||||
http_port 9080
|
||||
https_port 9443
|
||||
grace_period 1
|
||||
grace_period 1ns
|
||||
}
|
||||
|
||||
localhost:9080 {
|
||||
@@ -86,9 +88,11 @@ func TestReadCookie(t *testing.T) {
|
||||
tester.Client.Jar.SetCookies(localhost, []*http.Cookie{&cookie})
|
||||
tester.InitServer(`
|
||||
{
|
||||
skip_install_trust
|
||||
admin localhost:2999
|
||||
http_port 9080
|
||||
https_port 9443
|
||||
grace_period 1
|
||||
grace_period 1ns
|
||||
}
|
||||
|
||||
localhost:9080 {
|
||||
@@ -110,9 +114,11 @@ func TestReplIndex(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
skip_install_trust
|
||||
admin localhost:2999
|
||||
http_port 9080
|
||||
https_port 9443
|
||||
grace_period 1
|
||||
grace_period 1ns
|
||||
}
|
||||
|
||||
localhost:9080 {
|
||||
|
||||
@@ -11,9 +11,11 @@ func TestBrowse(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
skip_install_trust
|
||||
admin localhost:2999
|
||||
http_port 9080
|
||||
https_port 9443
|
||||
grace_period 1
|
||||
grace_period 1ns
|
||||
}
|
||||
http://localhost:9080 {
|
||||
file_server browse
|
||||
|
||||
@@ -11,9 +11,11 @@ func TestMap(t *testing.T) {
|
||||
// arrange
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`{
|
||||
skip_install_trust
|
||||
admin localhost:2999
|
||||
http_port 9080
|
||||
https_port 9443
|
||||
grace_period 1
|
||||
grace_period 1ns
|
||||
}
|
||||
|
||||
localhost:9080 {
|
||||
@@ -39,6 +41,8 @@ func TestMapRespondWithDefault(t *testing.T) {
|
||||
// arrange
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`{
|
||||
skip_install_trust
|
||||
admin localhost:2999
|
||||
http_port 9080
|
||||
https_port 9443
|
||||
}
|
||||
@@ -66,7 +70,17 @@ func TestMapAsJSON(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
"admin": {
|
||||
"listen": "localhost:2999"
|
||||
},
|
||||
"apps": {
|
||||
"pki": {
|
||||
"certificate_authorities" : {
|
||||
"local" : {
|
||||
"install_trust": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"http": {
|
||||
"http_port": 9080,
|
||||
"https_port": 9443,
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/caddyserver/caddy/v2/caddytest"
|
||||
)
|
||||
|
||||
func TestLeafCertLifetimeLessThanIntermediate(t *testing.T) {
|
||||
caddytest.AssertLoadError(t, `
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"ca": "internal",
|
||||
"handler": "acme_server",
|
||||
"lifetime": 604800000000000
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"pki": {
|
||||
"certificate_authorities": {
|
||||
"internal": {
|
||||
"install_trust": false,
|
||||
"intermediate_lifetime": 604800000000000,
|
||||
"name": "Internal CA"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`, "json", "certificate lifetime (168h0m0s) should be less than intermediate certificate lifetime (168h0m0s)")
|
||||
}
|
||||
|
||||
func TestIntermediateLifetimeLessThanRoot(t *testing.T) {
|
||||
caddytest.AssertLoadError(t, `
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"ca": "internal",
|
||||
"handler": "acme_server",
|
||||
"lifetime": 2592000000000000
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"pki": {
|
||||
"certificate_authorities": {
|
||||
"internal": {
|
||||
"install_trust": false,
|
||||
"intermediate_lifetime": 311040000000000000,
|
||||
"name": "Internal CA"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`, "json", "intermediate certificate lifetime must be less than root certificate lifetime (86400h0m0s)")
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/caddyserver/caddy/v2/caddytest"
|
||||
)
|
||||
@@ -16,68 +17,43 @@ func TestSRVReverseProxy(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
"admin": {
|
||||
"listen": "localhost:2999"
|
||||
},
|
||||
"apps": {
|
||||
"http": {
|
||||
"grace_period": 1,
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":8080"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "reverse_proxy",
|
||||
"upstreams": [
|
||||
{
|
||||
"lookup_srv": "srv.host.service.consul"
|
||||
}
|
||||
"pki": {
|
||||
"certificate_authorities": {
|
||||
"local": {
|
||||
"install_trust": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"http": {
|
||||
"grace_period": 1,
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":18080"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "reverse_proxy",
|
||||
"dynamic_upstreams": {
|
||||
"source": "srv",
|
||||
"name": "srv.host.service.consul"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`, "json")
|
||||
}
|
||||
|
||||
func TestSRVWithDial(t *testing.T) {
|
||||
caddytest.AssertLoadError(t, `
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"grace_period": 1,
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":8080"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "reverse_proxy",
|
||||
"upstreams": [
|
||||
{
|
||||
"dial": "tcp/address.to.upstream:80",
|
||||
"lookup_srv": "srv.host.service.consul"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`, "json", `upstream: specifying dial address is incompatible with lookup_srv: 0: {\"dial\": \"tcp/address.to.upstream:80\", \"lookup_srv\": \"srv.host.service.consul\"}`)
|
||||
}
|
||||
`, "json")
|
||||
}
|
||||
|
||||
func TestDialWithPlaceholderUnix(t *testing.T) {
|
||||
@@ -115,36 +91,46 @@ func TestDialWithPlaceholderUnix(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
"admin": {
|
||||
"listen": "localhost:2999"
|
||||
},
|
||||
"apps": {
|
||||
"http": {
|
||||
"grace_period": 1,
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":8080"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "reverse_proxy",
|
||||
"upstreams": [
|
||||
{
|
||||
"dial": "unix/{http.request.header.X-Caddy-Upstream-Dial}"
|
||||
}
|
||||
"pki": {
|
||||
"certificate_authorities": {
|
||||
"local": {
|
||||
"install_trust": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"http": {
|
||||
"grace_period": 1,
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":18080"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "reverse_proxy",
|
||||
"upstreams": [
|
||||
{
|
||||
"dial": "unix/{http.request.header.X-Caddy-Upstream-Dial}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`, "json")
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, "http://localhost:8080", nil)
|
||||
req, err := http.NewRequest(http.MethodGet, "http://localhost:18080", nil)
|
||||
if err != nil {
|
||||
t.Fail()
|
||||
return
|
||||
@@ -157,13 +143,23 @@ func TestReverseProxyWithPlaceholderDialAddress(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
"admin": {
|
||||
"listen": "localhost:2999"
|
||||
},
|
||||
"apps": {
|
||||
"pki": {
|
||||
"certificate_authorities": {
|
||||
"local": {
|
||||
"install_trust": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"http": {
|
||||
"grace_period": 1,
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":8080"
|
||||
":18080"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
@@ -226,14 +222,14 @@ func TestReverseProxyWithPlaceholderDialAddress(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
`, "json")
|
||||
`, "json")
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, "http://localhost:9080", nil)
|
||||
if err != nil {
|
||||
t.Fail()
|
||||
return
|
||||
}
|
||||
req.Header.Set("X-Caddy-Upstream-Dial", "localhost:8080")
|
||||
req.Header.Set("X-Caddy-Upstream-Dial", "localhost:18080")
|
||||
tester.AssertResponse(req, 200, "Hello, World!")
|
||||
}
|
||||
|
||||
@@ -241,13 +237,23 @@ func TestReverseProxyWithPlaceholderTCPDialAddress(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
"admin": {
|
||||
"listen": "localhost:2999"
|
||||
},
|
||||
"apps": {
|
||||
"pki": {
|
||||
"certificate_authorities": {
|
||||
"local": {
|
||||
"install_trust": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"http": {
|
||||
"grace_period": 1,
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":8080"
|
||||
":18080"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
@@ -292,7 +298,7 @@ func TestReverseProxyWithPlaceholderTCPDialAddress(t *testing.T) {
|
||||
"handler": "reverse_proxy",
|
||||
"upstreams": [
|
||||
{
|
||||
"dial": "tcp/{http.request.header.X-Caddy-Upstream-Dial}:8080"
|
||||
"dial": "tcp/{http.request.header.X-Caddy-Upstream-Dial}:18080"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -310,7 +316,7 @@ func TestReverseProxyWithPlaceholderTCPDialAddress(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
`, "json")
|
||||
`, "json")
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, "http://localhost:9080", nil)
|
||||
if err != nil {
|
||||
@@ -321,50 +327,15 @@ func TestReverseProxyWithPlaceholderTCPDialAddress(t *testing.T) {
|
||||
tester.AssertResponse(req, 200, "Hello, World!")
|
||||
}
|
||||
|
||||
func TestSRVWithActiveHealthcheck(t *testing.T) {
|
||||
caddytest.AssertLoadError(t, `
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"grace_period": 1,
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":8080"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "reverse_proxy",
|
||||
"health_checks": {
|
||||
"active": {
|
||||
"path": "/ok"
|
||||
}
|
||||
},
|
||||
"upstreams": [
|
||||
{
|
||||
"lookup_srv": "srv.host.service.consul"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`, "json", `upstream: lookup_srv is incompatible with active health checks: 0: {\"dial\": \"\", \"lookup_srv\": \"srv.host.service.consul\"}`)
|
||||
}
|
||||
|
||||
func TestReverseProxyHealthCheck(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
skip_install_trust
|
||||
admin localhost:2999
|
||||
http_port 9080
|
||||
https_port 9443
|
||||
grace_period 1ns
|
||||
}
|
||||
http://localhost:2020 {
|
||||
respond "Hello, World!"
|
||||
@@ -378,12 +349,13 @@ func TestReverseProxyHealthCheck(t *testing.T) {
|
||||
|
||||
health_uri /health
|
||||
health_port 2021
|
||||
health_interval 2s
|
||||
health_timeout 5s
|
||||
health_interval 10ms
|
||||
health_timeout 100ms
|
||||
}
|
||||
}
|
||||
`, "caddyfile")
|
||||
`, "caddyfile")
|
||||
|
||||
time.Sleep(100 * time.Millisecond) // TODO: for some reason this test seems particularly flaky, getting 503 when it should be 200, unless we wait
|
||||
tester.AssertGetResponse("http://localhost:9080/", 200, "Hello, World!")
|
||||
}
|
||||
|
||||
@@ -424,8 +396,11 @@ func TestReverseProxyHealthCheckUnixSocket(t *testing.T) {
|
||||
|
||||
tester.InitServer(fmt.Sprintf(`
|
||||
{
|
||||
skip_install_trust
|
||||
admin localhost:2999
|
||||
http_port 9080
|
||||
https_port 9443
|
||||
grace_period 1ns
|
||||
}
|
||||
http://localhost:9080 {
|
||||
reverse_proxy {
|
||||
@@ -479,8 +454,11 @@ func TestReverseProxyHealthCheckUnixSocketWithoutPort(t *testing.T) {
|
||||
|
||||
tester.InitServer(fmt.Sprintf(`
|
||||
{
|
||||
skip_install_trust
|
||||
admin localhost:2999
|
||||
http_port 9080
|
||||
https_port 9443
|
||||
grace_period 1ns
|
||||
}
|
||||
http://localhost:9080 {
|
||||
reverse_proxy {
|
||||
|
||||
+257
-240
@@ -11,92 +11,95 @@ func TestDefaultSNI(t *testing.T) {
|
||||
// arrange
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`{
|
||||
"apps": {
|
||||
"http": {
|
||||
"http_port": 9080,
|
||||
"https_port": 9443,
|
||||
"grace_period": 1,
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":9443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "hello from a.caddy.localhost",
|
||||
"handler": "static_response",
|
||||
"status_code": 200
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"path": [
|
||||
"/version"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"127.0.0.1"
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
],
|
||||
"tls_connection_policies": [
|
||||
{
|
||||
"certificate_selection": {
|
||||
"any_tag": ["cert0"]
|
||||
},
|
||||
"match": {
|
||||
"sni": [
|
||||
"127.0.0.1"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"default_sni": "*.caddy.localhost"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"tls": {
|
||||
"certificates": {
|
||||
"load_files": [
|
||||
{
|
||||
"certificate": "/caddy.localhost.crt",
|
||||
"key": "/caddy.localhost.key",
|
||||
"tags": [
|
||||
"cert0"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"pki": {
|
||||
"certificate_authorities" : {
|
||||
"local" : {
|
||||
"install_trust": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`, "json")
|
||||
"admin": {
|
||||
"listen": "localhost:2999"
|
||||
},
|
||||
"apps": {
|
||||
"http": {
|
||||
"http_port": 9080,
|
||||
"https_port": 9443,
|
||||
"grace_period": 1,
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":9443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "hello from a.caddy.localhost",
|
||||
"handler": "static_response",
|
||||
"status_code": 200
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"path": [
|
||||
"/version"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"127.0.0.1"
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
],
|
||||
"tls_connection_policies": [
|
||||
{
|
||||
"certificate_selection": {
|
||||
"any_tag": ["cert0"]
|
||||
},
|
||||
"match": {
|
||||
"sni": [
|
||||
"127.0.0.1"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"default_sni": "*.caddy.localhost"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"tls": {
|
||||
"certificates": {
|
||||
"load_files": [
|
||||
{
|
||||
"certificate": "/caddy.localhost.crt",
|
||||
"key": "/caddy.localhost.key",
|
||||
"tags": [
|
||||
"cert0"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"pki": {
|
||||
"certificate_authorities" : {
|
||||
"local" : {
|
||||
"install_trust": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`, "json")
|
||||
|
||||
// act and assert
|
||||
// makes a request with no sni
|
||||
@@ -108,97 +111,100 @@ func TestDefaultSNIWithNamedHostAndExplicitIP(t *testing.T) {
|
||||
// arrange
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"http_port": 9080,
|
||||
"https_port": 9443,
|
||||
"grace_period": 1,
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":9443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "hello from a",
|
||||
"handler": "static_response",
|
||||
"status_code": 200
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"path": [
|
||||
"/version"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"a.caddy.localhost",
|
||||
"127.0.0.1"
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
],
|
||||
"tls_connection_policies": [
|
||||
{
|
||||
"certificate_selection": {
|
||||
"any_tag": ["cert0"]
|
||||
},
|
||||
"default_sni": "a.caddy.localhost",
|
||||
"match": {
|
||||
"sni": [
|
||||
"a.caddy.localhost",
|
||||
"127.0.0.1",
|
||||
""
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"default_sni": "a.caddy.localhost"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"tls": {
|
||||
"certificates": {
|
||||
"load_files": [
|
||||
{
|
||||
"certificate": "/a.caddy.localhost.crt",
|
||||
"key": "/a.caddy.localhost.key",
|
||||
"tags": [
|
||||
"cert0"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"pki": {
|
||||
"certificate_authorities" : {
|
||||
"local" : {
|
||||
"install_trust": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`, "json")
|
||||
{
|
||||
"admin": {
|
||||
"listen": "localhost:2999"
|
||||
},
|
||||
"apps": {
|
||||
"http": {
|
||||
"http_port": 9080,
|
||||
"https_port": 9443,
|
||||
"grace_period": 1,
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":9443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"handler": "subroute",
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "hello from a",
|
||||
"handler": "static_response",
|
||||
"status_code": 200
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"path": [
|
||||
"/version"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"host": [
|
||||
"a.caddy.localhost",
|
||||
"127.0.0.1"
|
||||
]
|
||||
}
|
||||
],
|
||||
"terminal": true
|
||||
}
|
||||
],
|
||||
"tls_connection_policies": [
|
||||
{
|
||||
"certificate_selection": {
|
||||
"any_tag": ["cert0"]
|
||||
},
|
||||
"default_sni": "a.caddy.localhost",
|
||||
"match": {
|
||||
"sni": [
|
||||
"a.caddy.localhost",
|
||||
"127.0.0.1",
|
||||
""
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"default_sni": "a.caddy.localhost"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"tls": {
|
||||
"certificates": {
|
||||
"load_files": [
|
||||
{
|
||||
"certificate": "/a.caddy.localhost.crt",
|
||||
"key": "/a.caddy.localhost.key",
|
||||
"tags": [
|
||||
"cert0"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"pki": {
|
||||
"certificate_authorities" : {
|
||||
"local" : {
|
||||
"install_trust": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`, "json")
|
||||
|
||||
// act and assert
|
||||
// makes a request with no sni
|
||||
@@ -209,69 +215,72 @@ func TestDefaultSNIWithPortMappingOnly(t *testing.T) {
|
||||
// arrange
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
"apps": {
|
||||
"http": {
|
||||
"http_port": 9080,
|
||||
"https_port": 9443,
|
||||
"grace_period": 1,
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":9443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "hello from a.caddy.localhost",
|
||||
"handler": "static_response",
|
||||
"status_code": 200
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"path": [
|
||||
"/version"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"tls_connection_policies": [
|
||||
{
|
||||
"certificate_selection": {
|
||||
"any_tag": ["cert0"]
|
||||
},
|
||||
"default_sni": "a.caddy.localhost"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"tls": {
|
||||
"certificates": {
|
||||
"load_files": [
|
||||
{
|
||||
"certificate": "/a.caddy.localhost.crt",
|
||||
"key": "/a.caddy.localhost.key",
|
||||
"tags": [
|
||||
"cert0"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"pki": {
|
||||
"certificate_authorities" : {
|
||||
"local" : {
|
||||
"install_trust": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`, "json")
|
||||
{
|
||||
"admin": {
|
||||
"listen": "localhost:2999"
|
||||
},
|
||||
"apps": {
|
||||
"http": {
|
||||
"http_port": 9080,
|
||||
"https_port": 9443,
|
||||
"grace_period": 1,
|
||||
"servers": {
|
||||
"srv0": {
|
||||
"listen": [
|
||||
":9443"
|
||||
],
|
||||
"routes": [
|
||||
{
|
||||
"handle": [
|
||||
{
|
||||
"body": "hello from a.caddy.localhost",
|
||||
"handler": "static_response",
|
||||
"status_code": 200
|
||||
}
|
||||
],
|
||||
"match": [
|
||||
{
|
||||
"path": [
|
||||
"/version"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"tls_connection_policies": [
|
||||
{
|
||||
"certificate_selection": {
|
||||
"any_tag": ["cert0"]
|
||||
},
|
||||
"default_sni": "a.caddy.localhost"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"tls": {
|
||||
"certificates": {
|
||||
"load_files": [
|
||||
{
|
||||
"certificate": "/a.caddy.localhost.crt",
|
||||
"key": "/a.caddy.localhost.key",
|
||||
"tags": [
|
||||
"cert0"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"pki": {
|
||||
"certificate_authorities" : {
|
||||
"local" : {
|
||||
"install_trust": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`, "json")
|
||||
|
||||
// act and assert
|
||||
// makes a request with no sni
|
||||
@@ -281,6 +290,7 @@ func TestDefaultSNIWithPortMappingOnly(t *testing.T) {
|
||||
func TestHttpOnlyOnDomainWithSNI(t *testing.T) {
|
||||
caddytest.AssertAdapt(t, `
|
||||
{
|
||||
skip_install_trust
|
||||
default_sni a.caddy.localhost
|
||||
}
|
||||
:80 {
|
||||
@@ -316,6 +326,13 @@ func TestHttpOnlyOnDomainWithSNI(t *testing.T) {
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"pki": {
|
||||
"certificate_authorities": {
|
||||
"local": {
|
||||
"install_trust": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}`)
|
||||
|
||||
@@ -23,6 +23,9 @@ func TestH2ToH2CStream(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
"admin": {
|
||||
"listen": "localhost:2999"
|
||||
},
|
||||
"apps": {
|
||||
"http": {
|
||||
"http_port": 9080,
|
||||
@@ -173,9 +176,7 @@ func testH2ToH2CStreamServeH2C(t *testing.T) *http.Server {
|
||||
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(200)
|
||||
if f, ok := w.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
http.NewResponseController(w).Flush()
|
||||
|
||||
buf := make([]byte, 4*1024)
|
||||
|
||||
@@ -206,6 +207,9 @@ func TestH2ToH1ChunkedResponse(t *testing.T) {
|
||||
tester := caddytest.NewTester(t)
|
||||
tester.InitServer(`
|
||||
{
|
||||
"admin": {
|
||||
"listen": "localhost:2999"
|
||||
},
|
||||
"logging": {
|
||||
"logs": {
|
||||
"default": {
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
respond "'I am {args.0}', hears {args.1}"
|
||||
respond "'I am {args[0]}', hears {args[1]}"
|
||||
+4
-4
@@ -19,10 +19,10 @@
|
||||
// There is no need to modify the Caddy source code to customize your
|
||||
// builds. You can easily build a custom Caddy with these simple steps:
|
||||
//
|
||||
// 1. Copy this file (main.go) into a new folder
|
||||
// 2. Edit the imports below to include the modules you want plugged in
|
||||
// 3. Run `go mod init caddy`
|
||||
// 4. Run `go install` or `go build` - you now have a custom binary!
|
||||
// 1. Copy this file (main.go) into a new folder
|
||||
// 2. Edit the imports below to include the modules you want plugged in
|
||||
// 3. Run `go mod init caddy`
|
||||
// 4. Run `go install` or `go build` - you now have a custom binary!
|
||||
//
|
||||
// Or you can use xcaddy which does it all for you as a command:
|
||||
// https://github.com/caddyserver/xcaddy
|
||||
|
||||
+17
-8
@@ -101,20 +101,29 @@ const fullDocsFooter = `Full documentation is available at:
|
||||
https://caddyserver.com/docs/command-line`
|
||||
|
||||
func init() {
|
||||
rootCmd.SetHelpTemplate(rootCmd.HelpTemplate() + "\n" + fullDocsFooter)
|
||||
rootCmd.SetHelpTemplate(rootCmd.HelpTemplate() + "\n" + fullDocsFooter + "\n")
|
||||
}
|
||||
|
||||
func caddyCmdToCoral(caddyCmd Command) *cobra.Command {
|
||||
func caddyCmdToCobra(caddyCmd Command) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: caddyCmd.Name,
|
||||
Short: caddyCmd.Short,
|
||||
Long: caddyCmd.Long,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
fls := cmd.Flags()
|
||||
_, err := caddyCmd.Func(Flags{fls})
|
||||
return err
|
||||
},
|
||||
}
|
||||
cmd.Flags().AddGoFlagSet(caddyCmd.Flags)
|
||||
if caddyCmd.CobraFunc != nil {
|
||||
caddyCmd.CobraFunc(cmd)
|
||||
} else {
|
||||
cmd.RunE = WrapCommandFuncForCobra(caddyCmd.Func)
|
||||
cmd.Flags().AddGoFlagSet(caddyCmd.Flags)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
// WrapCommandFuncForCobra wraps a Caddy CommandFunc for use
|
||||
// in a cobra command's RunE field.
|
||||
func WrapCommandFuncForCobra(f CommandFunc) func(cmd *cobra.Command, _ []string) error {
|
||||
return func(cmd *cobra.Command, _ []string) error {
|
||||
_, err := f(Flags{cmd.Flags()})
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
+61
-27
@@ -35,6 +35,7 @@ import (
|
||||
"github.com/caddyserver/caddy/v2"
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig"
|
||||
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
|
||||
"github.com/caddyserver/caddy/v2/internal"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
@@ -208,6 +209,16 @@ func cmdRun(fl Flags) (int, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// create pidfile now, in case loading config takes a while (issue #5477)
|
||||
if runCmdPidfileFlag != "" {
|
||||
err := caddy.PIDFile(runCmdPidfileFlag)
|
||||
if err != nil {
|
||||
caddy.Log().Error("unable to write PID file",
|
||||
zap.String("pidfile", runCmdPidfileFlag),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// run the initial config
|
||||
err = caddy.Load(config, true)
|
||||
if err != nil {
|
||||
@@ -242,16 +253,6 @@ func cmdRun(fl Flags) (int, error) {
|
||||
go watchConfigFile(configFile, runCmdConfigAdapterFlag)
|
||||
}
|
||||
|
||||
// create pidfile
|
||||
if runCmdPidfileFlag != "" {
|
||||
err := caddy.PIDFile(runCmdPidfileFlag)
|
||||
if err != nil {
|
||||
caddy.Log().Error("unable to write PID file",
|
||||
zap.String("pidfile", runCmdPidfileFlag),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// warn if the environment does not provide enough information about the disk
|
||||
hasXDG := os.Getenv("XDG_DATA_HOME") != "" &&
|
||||
os.Getenv("XDG_CONFIG_HOME") != "" &&
|
||||
@@ -490,7 +491,7 @@ func cmdAdaptConfig(fl Flags) (int, error) {
|
||||
// validate output if requested
|
||||
if adaptCmdValidateFlag {
|
||||
var cfg *caddy.Config
|
||||
err = json.Unmarshal(adaptedConfig, &cfg)
|
||||
err = caddy.StrictUnmarshalJSON(adaptedConfig, &cfg)
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedStartup, fmt.Errorf("decoding config: %v", err)
|
||||
}
|
||||
@@ -506,6 +507,15 @@ func cmdAdaptConfig(fl Flags) (int, error) {
|
||||
func cmdValidateConfig(fl Flags) (int, error) {
|
||||
validateCmdConfigFlag := fl.String("config")
|
||||
validateCmdAdapterFlag := fl.String("adapter")
|
||||
runCmdLoadEnvfileFlag := fl.String("envfile")
|
||||
|
||||
// load all additional envs as soon as possible
|
||||
if runCmdLoadEnvfileFlag != "" {
|
||||
if err := loadEnvFromFile(runCmdLoadEnvfileFlag); err != nil {
|
||||
return caddy.ExitCodeFailedStartup,
|
||||
fmt.Errorf("loading additional environment variables: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
input, _, err := LoadConfig(validateCmdConfigFlag, validateCmdAdapterFlag)
|
||||
if err != nil {
|
||||
@@ -514,7 +524,7 @@ func cmdValidateConfig(fl Flags) (int, error) {
|
||||
input = caddy.RemoveMetaFields(input)
|
||||
|
||||
var cfg *caddy.Config
|
||||
err = json.Unmarshal(input, &cfg)
|
||||
err = caddy.StrictUnmarshalJSON(input, &cfg)
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedStartup, fmt.Errorf("decoding config: %v", err)
|
||||
}
|
||||
@@ -558,7 +568,10 @@ func cmdFmt(fl Flags) (int, error) {
|
||||
if err := os.WriteFile(formatCmdConfigFile, output, 0600); err != nil {
|
||||
return caddy.ExitCodeFailedStartup, fmt.Errorf("overwriting formatted file: %v", err)
|
||||
}
|
||||
} else if fl.Bool("diff") {
|
||||
return caddy.ExitCodeSuccess, nil
|
||||
}
|
||||
|
||||
if fl.Bool("diff") {
|
||||
diff := difflib.Diff(
|
||||
strings.Split(string(input), "\n"),
|
||||
strings.Split(string(output), "\n"))
|
||||
@@ -576,6 +589,13 @@ func cmdFmt(fl Flags) (int, error) {
|
||||
fmt.Print(string(output))
|
||||
}
|
||||
|
||||
if warning, diff := caddyfile.FormattingDifference(formatCmdConfigFile, input); diff {
|
||||
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`,
|
||||
warning.File,
|
||||
warning.Line,
|
||||
)
|
||||
}
|
||||
|
||||
return caddy.ExitCodeSuccess, nil
|
||||
}
|
||||
|
||||
@@ -591,7 +611,17 @@ func AdminAPIRequest(adminAddr, method, uri string, headers http.Header, body io
|
||||
}
|
||||
origin := "http://" + parsedAddr.JoinHostPort(0)
|
||||
if parsedAddr.IsUnixNetwork() {
|
||||
origin = "http://unixsocket" // hack so that http.NewRequest() is happy
|
||||
origin = "http://127.0.0.1" // bogus host is a hack so that http.NewRequest() is happy
|
||||
|
||||
// the unix address at this point might still contain the optional
|
||||
// unix socket permissions, which are part of the address/host.
|
||||
// those need to be removed first, as they aren't part of the
|
||||
// resulting unix file path
|
||||
addr, _, err := internal.SplitUnixSocketPermissionsBits(parsedAddr.Host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parsedAddr.Host = addr
|
||||
}
|
||||
|
||||
// form the request
|
||||
@@ -600,20 +630,24 @@ func AdminAPIRequest(adminAddr, method, uri string, headers http.Header, body io
|
||||
return nil, fmt.Errorf("making request: %v", err)
|
||||
}
|
||||
if parsedAddr.IsUnixNetwork() {
|
||||
// When listening on a unix socket, the admin endpoint doesn't
|
||||
// accept any Host header because there is no host:port for
|
||||
// a unix socket's address. The server's host check is fairly
|
||||
// strict for security reasons, so we don't allow just any
|
||||
// Host header. For unix sockets, the Host header must be
|
||||
// empty. Unfortunately, Go makes it impossible to make HTTP
|
||||
// requests with an empty Host header... except with this one
|
||||
// weird trick. (Hopefully they don't fix it. It's already
|
||||
// hard enough to use HTTP over unix sockets.)
|
||||
// We used to conform to RFC 2616 Section 14.26 which requires
|
||||
// an empty host header when there is no host, as is the case
|
||||
// with unix sockets. However, Go required a Host value so we
|
||||
// used a hack of a space character as the host (it would see
|
||||
// the Host was non-empty, then trim the space later). As of
|
||||
// Go 1.20.6 (July 2023), this hack no longer works. See:
|
||||
// https://github.com/golang/go/issues/60374
|
||||
// See also the discussion here:
|
||||
// https://github.com/golang/go/issues/61431
|
||||
//
|
||||
// An equivalent curl command would be something like:
|
||||
// $ curl --unix-socket caddy.sock http:/:$REQUEST_URI
|
||||
req.URL.Host = " "
|
||||
req.Host = ""
|
||||
// After that, we now require a Host value of either 127.0.0.1
|
||||
// or ::1 if one is set. Above I choose to use 127.0.0.1. Even
|
||||
// though the value should be completely irrelevant (it could be
|
||||
// "srldkjfsd"), if for some reason the Host *is* used, at least
|
||||
// we can have some reasonable assurance it will stay on the local
|
||||
// machine and that browsers, if they ever allow access to unix
|
||||
// sockets, can still enforce CORS, ensuring it is still coming
|
||||
// from the local machine.
|
||||
} else {
|
||||
req.Header.Set("Origin", origin)
|
||||
}
|
||||
|
||||
+182
-135
@@ -34,12 +34,6 @@ type Command struct {
|
||||
// Required.
|
||||
Name string
|
||||
|
||||
// Func is a function that executes a subcommand using
|
||||
// the parsed flags. It returns an exit code and any
|
||||
// associated error.
|
||||
// Required.
|
||||
Func CommandFunc
|
||||
|
||||
// Usage is a brief message describing the syntax of
|
||||
// the subcommand's flags and args. Use [] to indicate
|
||||
// optional parameters and <> to enclose literal values
|
||||
@@ -60,7 +54,21 @@ type Command struct {
|
||||
Long string
|
||||
|
||||
// Flags is the flagset for command.
|
||||
// This is ignored if CobraFunc is set.
|
||||
Flags *flag.FlagSet
|
||||
|
||||
// Func is a function that executes a subcommand using
|
||||
// the parsed flags. It returns an exit code and any
|
||||
// associated error.
|
||||
// Required if CobraFunc is not set.
|
||||
Func CommandFunc
|
||||
|
||||
// CobraFunc allows further configuration of the command
|
||||
// via cobra's APIs. If this is set, then Func and Flags
|
||||
// are ignored, with the assumption that they are set in
|
||||
// this function. A caddycmd.WrapCommandFuncForCobra helper
|
||||
// exists to simplify porting CommandFunc to Cobra's RunE.
|
||||
CobraFunc func(*cobra.Command)
|
||||
}
|
||||
|
||||
// CommandFunc is a command's function. It runs the
|
||||
@@ -79,7 +87,6 @@ var commands = make(map[string]Command)
|
||||
func init() {
|
||||
RegisterCommand(Command{
|
||||
Name: "start",
|
||||
Func: cmdStart,
|
||||
Usage: "[--config <path> [--adapter <name>]] [--envfile <path>] [--watch] [--pidfile <file>]",
|
||||
Short: "Starts the Caddy process in the background and then returns",
|
||||
Long: `
|
||||
@@ -91,22 +98,21 @@ the KEY=VALUE format will be loaded into the Caddy process.
|
||||
|
||||
On Windows, the spawned child process will remain attached to the terminal, so
|
||||
closing the window will forcefully stop Caddy; to avoid forgetting this, try
|
||||
using 'caddy run' instead to keep it in the foreground.`,
|
||||
Flags: func() *flag.FlagSet {
|
||||
fs := flag.NewFlagSet("start", flag.ExitOnError)
|
||||
fs.String("config", "", "Configuration file")
|
||||
fs.String("envfile", "", "Environment file to load")
|
||||
fs.String("adapter", "", "Name of config adapter to apply")
|
||||
fs.String("pidfile", "", "Path of file to which to write process ID")
|
||||
fs.Bool("watch", false, "Reload changed config file automatically")
|
||||
return fs
|
||||
}(),
|
||||
using 'caddy run' instead to keep it in the foreground.
|
||||
`,
|
||||
CobraFunc: func(cmd *cobra.Command) {
|
||||
cmd.Flags().StringP("config", "c", "", "Configuration file")
|
||||
cmd.Flags().StringP("adapter", "a", "", "Name of config adapter to apply")
|
||||
cmd.Flags().StringP("envfile", "", "", "Environment file to load")
|
||||
cmd.Flags().BoolP("watch", "w", false, "Reload changed config file automatically")
|
||||
cmd.Flags().StringP("pidfile", "", "", "Path of file to which to write process ID")
|
||||
cmd.RunE = WrapCommandFuncForCobra(cmdStart)
|
||||
},
|
||||
})
|
||||
|
||||
RegisterCommand(Command{
|
||||
Name: "run",
|
||||
Func: cmdRun,
|
||||
Usage: "[--config <path> [--adapter <name>]] [--envfile <path>] [--environ] [--resume] [--watch] [--pidfile <fil>]",
|
||||
Usage: "[--config <path> [--adapter <name>]] [--envfile <path>] [--environ] [--resume] [--watch] [--pidfile <file>]",
|
||||
Short: `Starts the Caddy process and blocks indefinitely`,
|
||||
Long: `
|
||||
Starts the Caddy process, optionally bootstrapped with an initial config file,
|
||||
@@ -138,44 +144,42 @@ save file. It is not an error if --resume is used and no autosave file exists.
|
||||
|
||||
If --watch is specified, the config file will be loaded automatically after
|
||||
changes. ⚠️ This can make unintentional config changes easier; only use this
|
||||
option in a local development environment.`,
|
||||
Flags: func() *flag.FlagSet {
|
||||
fs := flag.NewFlagSet("run", flag.ExitOnError)
|
||||
fs.String("config", "", "Configuration file")
|
||||
fs.String("adapter", "", "Name of config adapter to apply")
|
||||
fs.String("envfile", "", "Environment file to load")
|
||||
fs.Bool("environ", false, "Print environment")
|
||||
fs.Bool("resume", false, "Use saved config, if any (and prefer over --config file)")
|
||||
fs.Bool("watch", false, "Watch config file for changes and reload it automatically")
|
||||
fs.String("pidfile", "", "Path of file to which to write process ID")
|
||||
fs.String("pingback", "", "Echo confirmation bytes to this address on success")
|
||||
return fs
|
||||
}(),
|
||||
option in a local development environment.
|
||||
`,
|
||||
CobraFunc: func(cmd *cobra.Command) {
|
||||
cmd.Flags().StringP("config", "c", "", "Configuration file")
|
||||
cmd.Flags().StringP("adapter", "a", "", "Name of config adapter to apply")
|
||||
cmd.Flags().StringP("envfile", "", "", "Environment file to load")
|
||||
cmd.Flags().BoolP("environ", "e", false, "Print environment")
|
||||
cmd.Flags().BoolP("resume", "r", false, "Use saved config, if any (and prefer over --config file)")
|
||||
cmd.Flags().BoolP("watch", "w", false, "Watch config file for changes and reload it automatically")
|
||||
cmd.Flags().StringP("pidfile", "", "", "Path of file to which to write process ID")
|
||||
cmd.Flags().StringP("pingback", "", "", "Echo confirmation bytes to this address on success")
|
||||
cmd.RunE = WrapCommandFuncForCobra(cmdRun)
|
||||
},
|
||||
})
|
||||
|
||||
RegisterCommand(Command{
|
||||
Name: "stop",
|
||||
Func: cmdStop,
|
||||
Usage: "[--address <interface>] [--config <path> [--adapter <name>]]",
|
||||
Usage: "[--config <path> [--adapter <name>]] [--address <interface>]",
|
||||
Short: "Gracefully stops a started Caddy process",
|
||||
Long: `
|
||||
Stops the background Caddy process as gracefully as possible.
|
||||
|
||||
It requires that the admin API is enabled and accessible, since it will
|
||||
use the API's /stop endpoint. The address of this request can be customized
|
||||
using the --address flag, or from the given --config, if not the default.`,
|
||||
Flags: func() *flag.FlagSet {
|
||||
fs := flag.NewFlagSet("stop", flag.ExitOnError)
|
||||
fs.String("address", "", "The address to use to reach the admin API endpoint, if not the default")
|
||||
fs.String("config", "", "Configuration file to use to parse the admin address, if --address is not used")
|
||||
fs.String("adapter", "", "Name of config adapter to apply (when --config is used)")
|
||||
return fs
|
||||
}(),
|
||||
using the --address flag, or from the given --config, if not the default.
|
||||
`,
|
||||
CobraFunc: func(cmd *cobra.Command) {
|
||||
cmd.Flags().StringP("config", "c", "", "Configuration file to use to parse the admin address, if --address is not used")
|
||||
cmd.Flags().StringP("adapter", "a", "", "Name of config adapter to apply (when --config is used)")
|
||||
cmd.Flags().StringP("address", "", "", "The address to use to reach the admin API endpoint, if not the default")
|
||||
cmd.RunE = WrapCommandFuncForCobra(cmdStop)
|
||||
},
|
||||
})
|
||||
|
||||
RegisterCommand(Command{
|
||||
Name: "reload",
|
||||
Func: cmdReload,
|
||||
Usage: "--config <path> [--adapter <name>] [--address <interface>]",
|
||||
Short: "Changes the config of the running Caddy instance",
|
||||
Long: `
|
||||
@@ -185,20 +189,19 @@ workflows revolving around config files.
|
||||
|
||||
Since the admin endpoint is configurable, the endpoint configuration is loaded
|
||||
from the --address flag if specified; otherwise it is loaded from the given
|
||||
config file; otherwise the default is assumed.`,
|
||||
Flags: func() *flag.FlagSet {
|
||||
fs := flag.NewFlagSet("reload", flag.ExitOnError)
|
||||
fs.String("config", "", "Configuration file (required)")
|
||||
fs.String("adapter", "", "Name of config adapter to apply")
|
||||
fs.String("address", "", "Address of the administration listener, if different from config")
|
||||
fs.Bool("force", false, "Force config reload, even if it is the same")
|
||||
return fs
|
||||
}(),
|
||||
config file; otherwise the default is assumed.
|
||||
`,
|
||||
CobraFunc: func(cmd *cobra.Command) {
|
||||
cmd.Flags().StringP("config", "c", "", "Configuration file (required)")
|
||||
cmd.Flags().StringP("adapter", "a", "", "Name of config adapter to apply")
|
||||
cmd.Flags().StringP("address", "", "", "Address of the administration listener, if different from config")
|
||||
cmd.Flags().BoolP("force", "f", false, "Force config reload, even if it is the same")
|
||||
cmd.RunE = WrapCommandFuncForCobra(cmdReload)
|
||||
},
|
||||
})
|
||||
|
||||
RegisterCommand(Command{
|
||||
Name: "version",
|
||||
Func: cmdVersion,
|
||||
Short: "Prints the version",
|
||||
Long: `
|
||||
Prints the version of this Caddy binary.
|
||||
@@ -213,31 +216,29 @@ detailed version information is printed as given by Go modules.
|
||||
For more details about the full version string, see the Go module
|
||||
documentation: https://go.dev/doc/modules/version-numbers
|
||||
`,
|
||||
Func: cmdVersion,
|
||||
})
|
||||
|
||||
RegisterCommand(Command{
|
||||
Name: "list-modules",
|
||||
Func: cmdListModules,
|
||||
Usage: "[--packages] [--versions]",
|
||||
Usage: "[--packages] [--versions] [--skip-standard]",
|
||||
Short: "Lists the installed Caddy modules",
|
||||
Flags: func() *flag.FlagSet {
|
||||
fs := flag.NewFlagSet("list-modules", flag.ExitOnError)
|
||||
fs.Bool("packages", false, "Print package paths")
|
||||
fs.Bool("versions", false, "Print version information")
|
||||
fs.Bool("skip-standard", false, "Skip printing standard modules")
|
||||
return fs
|
||||
}(),
|
||||
CobraFunc: func(cmd *cobra.Command) {
|
||||
cmd.Flags().BoolP("packages", "", false, "Print package paths")
|
||||
cmd.Flags().BoolP("versions", "", false, "Print version information")
|
||||
cmd.Flags().BoolP("skip-standard", "s", false, "Skip printing standard modules")
|
||||
cmd.RunE = WrapCommandFuncForCobra(cmdListModules)
|
||||
},
|
||||
})
|
||||
|
||||
RegisterCommand(Command{
|
||||
Name: "build-info",
|
||||
Func: cmdBuildInfo,
|
||||
Short: "Prints information about this build",
|
||||
Func: cmdBuildInfo,
|
||||
})
|
||||
|
||||
RegisterCommand(Command{
|
||||
Name: "environ",
|
||||
Func: cmdEnviron,
|
||||
Short: "Prints the environment",
|
||||
Long: `
|
||||
Prints the environment as seen by this Caddy process.
|
||||
@@ -257,11 +258,11 @@ by adding the "--environ" flag.
|
||||
|
||||
Environments may contain sensitive data.
|
||||
`,
|
||||
Func: cmdEnviron,
|
||||
})
|
||||
|
||||
RegisterCommand(Command{
|
||||
Name: "adapt",
|
||||
Func: cmdAdaptConfig,
|
||||
Usage: "--config <path> [--adapter <name>] [--pretty] [--validate]",
|
||||
Short: "Adapts a configuration to Caddy's native JSON",
|
||||
Long: `
|
||||
@@ -273,38 +274,90 @@ for human readability.
|
||||
|
||||
If --validate is used, the adapted config will be checked for validity.
|
||||
If the config is invalid, an error will be printed to stderr and a non-
|
||||
zero exit status will be returned.`,
|
||||
Flags: func() *flag.FlagSet {
|
||||
fs := flag.NewFlagSet("adapt", flag.ExitOnError)
|
||||
fs.String("config", "", "Configuration file to adapt (required)")
|
||||
fs.String("adapter", "caddyfile", "Name of config adapter")
|
||||
fs.Bool("pretty", false, "Format the output for human readability")
|
||||
fs.Bool("validate", false, "Validate the output")
|
||||
return fs
|
||||
}(),
|
||||
zero exit status will be returned.
|
||||
`,
|
||||
CobraFunc: func(cmd *cobra.Command) {
|
||||
cmd.Flags().StringP("config", "c", "", "Configuration file to adapt (required)")
|
||||
cmd.Flags().StringP("adapter", "a", "caddyfile", "Name of config adapter")
|
||||
cmd.Flags().BoolP("pretty", "p", false, "Format the output for human readability")
|
||||
cmd.Flags().BoolP("validate", "", false, "Validate the output")
|
||||
cmd.RunE = WrapCommandFuncForCobra(cmdAdaptConfig)
|
||||
},
|
||||
})
|
||||
|
||||
RegisterCommand(Command{
|
||||
Name: "validate",
|
||||
Func: cmdValidateConfig,
|
||||
Usage: "--config <path> [--adapter <name>]",
|
||||
Usage: "--config <path> [--adapter <name>] [--envfile <path>]",
|
||||
Short: "Tests whether a configuration file is valid",
|
||||
Long: `
|
||||
Loads and provisions the provided config, but does not start running it.
|
||||
This reveals any errors with the configuration through the loading and
|
||||
provisioning stages.`,
|
||||
Flags: func() *flag.FlagSet {
|
||||
fs := flag.NewFlagSet("validate", flag.ExitOnError)
|
||||
fs.String("config", "", "Input configuration file")
|
||||
fs.String("adapter", "", "Name of config adapter")
|
||||
return fs
|
||||
}(),
|
||||
provisioning stages.
|
||||
|
||||
If --envfile is specified, an environment file with environment variables in
|
||||
the KEY=VALUE format will be loaded into the Caddy process.
|
||||
`,
|
||||
CobraFunc: func(cmd *cobra.Command) {
|
||||
cmd.Flags().StringP("config", "c", "", "Input configuration file")
|
||||
cmd.Flags().StringP("adapter", "a", "", "Name of config adapter")
|
||||
cmd.Flags().StringP("envfile", "", "", "Environment file to load")
|
||||
cmd.RunE = WrapCommandFuncForCobra(cmdValidateConfig)
|
||||
},
|
||||
})
|
||||
|
||||
RegisterCommand(Command{
|
||||
Name: "storage",
|
||||
Short: "Commands for working with Caddy's storage (EXPERIMENTAL)",
|
||||
Long: `
|
||||
Allows exporting and importing Caddy's storage contents. The two commands can be
|
||||
combined in a pipeline to transfer directly from one storage to another:
|
||||
|
||||
$ caddy storage export --config Caddyfile.old --output - |
|
||||
> caddy storage import --config Caddyfile.new --input -
|
||||
|
||||
The - argument refers to stdout and stdin, respectively.
|
||||
|
||||
NOTE: When importing to or exporting from file_system storage (the default), the command
|
||||
should be run as the user that owns the associated root path.
|
||||
|
||||
EXPERIMENTAL: May be changed or removed.
|
||||
`,
|
||||
CobraFunc: func(cmd *cobra.Command) {
|
||||
exportCmd := &cobra.Command{
|
||||
Use: "export --config <path> --output <path>",
|
||||
Short: "Exports storage assets as a tarball",
|
||||
Long: `
|
||||
The contents of the configured storage module (TLS certificates, etc)
|
||||
are exported via a tarball.
|
||||
|
||||
--output is required, - can be given for stdout.
|
||||
`,
|
||||
RunE: WrapCommandFuncForCobra(cmdExportStorage),
|
||||
}
|
||||
exportCmd.Flags().StringP("config", "c", "", "Input configuration file (required)")
|
||||
exportCmd.Flags().StringP("output", "o", "", "Output path")
|
||||
cmd.AddCommand(exportCmd)
|
||||
|
||||
importCmd := &cobra.Command{
|
||||
Use: "import --config <path> --input <path>",
|
||||
Short: "Imports storage assets from a tarball.",
|
||||
Long: `
|
||||
Imports storage assets to the configured storage module. The import file must be
|
||||
a tar archive.
|
||||
|
||||
--input is required, - can be given for stdin.
|
||||
`,
|
||||
RunE: WrapCommandFuncForCobra(cmdImportStorage),
|
||||
}
|
||||
importCmd.Flags().StringP("config", "c", "", "Configuration file to load (required)")
|
||||
importCmd.Flags().StringP("input", "i", "", "Tar of assets to load (required)")
|
||||
cmd.AddCommand(importCmd)
|
||||
},
|
||||
})
|
||||
|
||||
RegisterCommand(Command{
|
||||
Name: "fmt",
|
||||
Func: cmdFmt,
|
||||
Usage: "[--overwrite] [<path>]",
|
||||
Usage: "[--overwrite] [--diff] [<path>]",
|
||||
Short: "Formats a Caddyfile",
|
||||
Long: `
|
||||
Formats the Caddyfile by adding proper indentation and spaces to improve
|
||||
@@ -320,32 +373,30 @@ is not a valid patch format.
|
||||
|
||||
If you wish you use stdin instead of a regular file, use - as the path.
|
||||
When reading from stdin, the --overwrite flag has no effect: the result
|
||||
is always printed to stdout.`,
|
||||
Flags: func() *flag.FlagSet {
|
||||
fs := flag.NewFlagSet("fmt", flag.ExitOnError)
|
||||
fs.Bool("overwrite", false, "Overwrite the input file with the results")
|
||||
fs.Bool("diff", false, "Print the differences between the input file and the formatted output")
|
||||
return fs
|
||||
}(),
|
||||
is always printed to stdout.
|
||||
`,
|
||||
CobraFunc: func(cmd *cobra.Command) {
|
||||
cmd.Flags().BoolP("overwrite", "w", false, "Overwrite the input file with the results")
|
||||
cmd.Flags().BoolP("diff", "d", false, "Print the differences between the input file and the formatted output")
|
||||
cmd.RunE = WrapCommandFuncForCobra(cmdFmt)
|
||||
},
|
||||
})
|
||||
|
||||
RegisterCommand(Command{
|
||||
Name: "upgrade",
|
||||
Func: cmdUpgrade,
|
||||
Short: "Upgrade Caddy (EXPERIMENTAL)",
|
||||
Long: `
|
||||
Downloads an updated Caddy binary with the same modules/plugins at the
|
||||
latest versions. EXPERIMENTAL: May be changed or removed.`,
|
||||
Flags: func() *flag.FlagSet {
|
||||
fs := flag.NewFlagSet("upgrade", flag.ExitOnError)
|
||||
fs.Bool("keep-backup", false, "Keep the backed up binary, instead of deleting it")
|
||||
return fs
|
||||
}(),
|
||||
latest versions. EXPERIMENTAL: May be changed or removed.
|
||||
`,
|
||||
CobraFunc: func(cmd *cobra.Command) {
|
||||
cmd.Flags().BoolP("keep-backup", "k", false, "Keep the backed up binary, instead of deleting it")
|
||||
cmd.RunE = WrapCommandFuncForCobra(cmdUpgrade)
|
||||
},
|
||||
})
|
||||
|
||||
RegisterCommand(Command{
|
||||
Name: "add-package",
|
||||
Func: cmdAddPackage,
|
||||
Usage: "<packages...>",
|
||||
Short: "Adds Caddy packages (EXPERIMENTAL)",
|
||||
Long: `
|
||||
@@ -353,11 +404,10 @@ Downloads an updated Caddy binary with the specified packages (module/plugin)
|
||||
added. Retains existing packages. Returns an error if the any of packages are
|
||||
already included. EXPERIMENTAL: May be changed or removed.
|
||||
`,
|
||||
Flags: func() *flag.FlagSet {
|
||||
fs := flag.NewFlagSet("add-package", flag.ExitOnError)
|
||||
fs.Bool("keep-backup", false, "Keep the backed up binary, instead of deleting it")
|
||||
return fs
|
||||
}(),
|
||||
CobraFunc: func(cmd *cobra.Command) {
|
||||
cmd.Flags().BoolP("keep-backup", "k", false, "Keep the backed up binary, instead of deleting it")
|
||||
cmd.RunE = WrapCommandFuncForCobra(cmdAddPackage)
|
||||
},
|
||||
})
|
||||
|
||||
RegisterCommand(Command{
|
||||
@@ -370,31 +420,14 @@ Downloads an updated Caddy binaries without the specified packages (module/plugi
|
||||
Returns an error if any of the packages are not included.
|
||||
EXPERIMENTAL: May be changed or removed.
|
||||
`,
|
||||
Flags: func() *flag.FlagSet {
|
||||
fs := flag.NewFlagSet("remove-package", flag.ExitOnError)
|
||||
fs.Bool("keep-backup", false, "Keep the backed up binary, instead of deleting it")
|
||||
return fs
|
||||
}(),
|
||||
CobraFunc: func(cmd *cobra.Command) {
|
||||
cmd.Flags().BoolP("keep-backup", "k", false, "Keep the backed up binary, instead of deleting it")
|
||||
cmd.RunE = WrapCommandFuncForCobra(cmdRemovePackage)
|
||||
},
|
||||
})
|
||||
|
||||
RegisterCommand(Command{
|
||||
Name: "manpage",
|
||||
Func: func(fl Flags) (int, error) {
|
||||
dir := strings.TrimSpace(fl.String("directory"))
|
||||
if dir == "" {
|
||||
return caddy.ExitCodeFailedQuit, fmt.Errorf("designated output directory and specified section are required")
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return caddy.ExitCodeFailedQuit, err
|
||||
}
|
||||
if err := doc.GenManTree(rootCmd, &doc.GenManHeader{
|
||||
Title: "Caddy",
|
||||
Section: "8", // https://en.wikipedia.org/wiki/Man_page#Manual_sections
|
||||
}, dir); err != nil {
|
||||
return caddy.ExitCodeFailedQuit, err
|
||||
}
|
||||
return caddy.ExitCodeSuccess, nil
|
||||
},
|
||||
Name: "manpage",
|
||||
Usage: "--directory <path>",
|
||||
Short: "Generates the manual pages for Caddy commands",
|
||||
Long: `
|
||||
@@ -404,11 +437,25 @@ tagged into section 8 (System Administration).
|
||||
The manual page files are generated into the directory specified by the
|
||||
argument of --directory. If the directory does not exist, it will be created.
|
||||
`,
|
||||
Flags: func() *flag.FlagSet {
|
||||
fs := flag.NewFlagSet("manpage", flag.ExitOnError)
|
||||
fs.String("directory", "", "The output directory where the manpages are generated")
|
||||
return fs
|
||||
}(),
|
||||
CobraFunc: func(cmd *cobra.Command) {
|
||||
cmd.Flags().StringP("directory", "o", "", "The output directory where the manpages are generated")
|
||||
cmd.RunE = WrapCommandFuncForCobra(func(fl Flags) (int, error) {
|
||||
dir := strings.TrimSpace(fl.String("directory"))
|
||||
if dir == "" {
|
||||
return caddy.ExitCodeFailedQuit, fmt.Errorf("designated output directory and specified section are required")
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return caddy.ExitCodeFailedQuit, err
|
||||
}
|
||||
if err := doc.GenManTree(rootCmd, &doc.GenManHeader{
|
||||
Title: "Caddy",
|
||||
Section: "8", // https://en.wikipedia.org/wiki/Man_page#Manual_sections
|
||||
}, dir); err != nil {
|
||||
return caddy.ExitCodeFailedQuit, err
|
||||
}
|
||||
return caddy.ExitCodeSuccess, nil
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
// source: https://github.com/spf13/cobra/blob/main/shell_completions.md
|
||||
@@ -456,7 +503,7 @@ argument of --directory. If the directory does not exist, it will be created.
|
||||
`, rootCmd.Root().Name()),
|
||||
DisableFlagsInUseLine: true,
|
||||
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
|
||||
Args: cobra.ExactValidArgs(1),
|
||||
Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
switch args[0] {
|
||||
case "bash":
|
||||
@@ -492,7 +539,7 @@ func RegisterCommand(cmd Command) {
|
||||
if cmd.Name == "" {
|
||||
panic("command name is required")
|
||||
}
|
||||
if cmd.Func == nil {
|
||||
if cmd.Func == nil && cmd.CobraFunc == nil {
|
||||
panic("command function missing")
|
||||
}
|
||||
if cmd.Short == "" {
|
||||
@@ -504,7 +551,7 @@ func RegisterCommand(cmd Command) {
|
||||
if !commandNameRegex.MatchString(cmd.Name) {
|
||||
panic("invalid command name")
|
||||
}
|
||||
rootCmd.AddCommand(caddyCmdToCoral(cmd))
|
||||
rootCmd.AddCommand(caddyCmdToCobra(cmd))
|
||||
}
|
||||
|
||||
var commandNameRegex = regexp.MustCompile(`^[a-z0-9]$|^([a-z0-9]+-?[a-z0-9]*)+[a-z0-9]$`)
|
||||
|
||||
+40
-55
@@ -89,6 +89,10 @@ func handlePingbackConn(conn net.Conn, expect []byte) error {
|
||||
// and returns the resulting JSON config bytes along with
|
||||
// the name of the loaded config file (if any).
|
||||
func LoadConfig(configFile, adapterName string) ([]byte, string, error) {
|
||||
return loadConfigWithLogger(caddy.Log(), configFile, adapterName)
|
||||
}
|
||||
|
||||
func loadConfigWithLogger(logger *zap.Logger, configFile, adapterName string) ([]byte, string, error) {
|
||||
// specifying an adapter without a config file is ambiguous
|
||||
if adapterName != "" && configFile == "" {
|
||||
return nil, "", fmt.Errorf("cannot adapt config without config file (use --config)")
|
||||
@@ -107,9 +111,11 @@ func LoadConfig(configFile, adapterName string) ([]byte, string, error) {
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("reading config file: %v", err)
|
||||
}
|
||||
caddy.Log().Info("using provided configuration",
|
||||
zap.String("config_file", configFile),
|
||||
zap.String("config_adapter", adapterName))
|
||||
if logger != nil {
|
||||
logger.Info("using provided configuration",
|
||||
zap.String("config_file", configFile),
|
||||
zap.String("config_adapter", adapterName))
|
||||
}
|
||||
} else if adapterName == "" {
|
||||
// as a special case when no config file or adapter
|
||||
// is specified, see if the Caddyfile adapter is
|
||||
@@ -126,7 +132,9 @@ func LoadConfig(configFile, adapterName string) ([]byte, string, error) {
|
||||
} else {
|
||||
// success reading default Caddyfile
|
||||
configFile = "Caddyfile"
|
||||
caddy.Log().Info("using adjacent Caddyfile")
|
||||
if logger != nil {
|
||||
logger.Info("using adjacent Caddyfile")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -161,7 +169,9 @@ func LoadConfig(configFile, adapterName string) ([]byte, string, error) {
|
||||
if warn.Directive != "" {
|
||||
msg = fmt.Sprintf("%s: %s", warn.Directive, warn.Message)
|
||||
}
|
||||
caddy.Log().Warn(msg, zap.String("adapter", adapterName), zap.String("file", warn.File), zap.Int("line", warn.Line))
|
||||
if logger != nil {
|
||||
logger.Warn(msg, zap.String("adapter", adapterName), zap.String("file", warn.File), zap.Int("line", warn.Line))
|
||||
}
|
||||
}
|
||||
config = adaptedConfig
|
||||
}
|
||||
@@ -174,6 +184,8 @@ func LoadConfig(configFile, adapterName string) ([]byte, string, error) {
|
||||
// blocks indefinitely; it only quits if the poller has errors for
|
||||
// long enough time. The filename passed in must be the actual
|
||||
// config file used, not one to be discovered.
|
||||
// Each second the config files is loaded and parsed into an object
|
||||
// and is compared to the last config object that was loaded
|
||||
func watchConfigFile(filename, adapterName string) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
@@ -189,64 +201,36 @@ func watchConfigFile(filename, adapterName string) {
|
||||
With(zap.String("config_file", filename))
|
||||
}
|
||||
|
||||
// get the initial timestamp on the config file
|
||||
info, err := os.Stat(filename)
|
||||
// get current config
|
||||
lastCfg, _, err := loadConfigWithLogger(nil, filename, adapterName)
|
||||
if err != nil {
|
||||
logger().Error("cannot watch config file", zap.Error(err))
|
||||
logger().Error("unable to load latest config", zap.Error(err))
|
||||
return
|
||||
}
|
||||
lastModified := info.ModTime()
|
||||
|
||||
logger().Info("watching config file for changes")
|
||||
|
||||
// if the file disappears or something, we can
|
||||
// stop polling if the error lasts long enough
|
||||
var lastErr time.Time
|
||||
finalError := func(err error) bool {
|
||||
if lastErr.IsZero() {
|
||||
lastErr = time.Now()
|
||||
return false
|
||||
}
|
||||
if time.Since(lastErr) > 30*time.Second {
|
||||
logger().Error("giving up watching config file; too many errors",
|
||||
zap.Error(err))
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// begin poller
|
||||
//nolint:staticcheck
|
||||
for range time.Tick(1 * time.Second) {
|
||||
// get the file info
|
||||
info, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
if finalError(err) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
lastErr = time.Time{} // no error, so clear any memory of one
|
||||
|
||||
// if it hasn't changed, nothing to do
|
||||
if !info.ModTime().After(lastModified) {
|
||||
continue
|
||||
}
|
||||
|
||||
logger().Info("config file changed; reloading")
|
||||
|
||||
// remember this timestamp
|
||||
lastModified = info.ModTime()
|
||||
|
||||
// load the contents of the file
|
||||
config, _, err := LoadConfig(filename, adapterName)
|
||||
// get current config
|
||||
newCfg, _, err := loadConfigWithLogger(nil, filename, adapterName)
|
||||
if err != nil {
|
||||
logger().Error("unable to load latest config", zap.Error(err))
|
||||
continue
|
||||
return
|
||||
}
|
||||
|
||||
// if it hasn't changed, nothing to do
|
||||
if bytes.Equal(lastCfg, newCfg) {
|
||||
continue
|
||||
}
|
||||
logger().Info("config file changed; reloading")
|
||||
|
||||
// remember the current config
|
||||
lastCfg = newCfg
|
||||
|
||||
// apply the updated config
|
||||
err = caddy.Load(config, false)
|
||||
err = caddy.Load(lastCfg, false)
|
||||
if err != nil {
|
||||
logger().Error("applying latest config", zap.Error(err))
|
||||
continue
|
||||
@@ -374,18 +358,19 @@ func parseEnvFile(envInput io.Reader) (map[string]string, error) {
|
||||
}
|
||||
|
||||
// quoted value: support newlines
|
||||
if strings.HasPrefix(val, `"`) {
|
||||
for !(strings.HasSuffix(line, `"`) && !strings.HasSuffix(line, `\"`)) {
|
||||
val = strings.ReplaceAll(val, `\"`, `"`)
|
||||
if strings.HasPrefix(val, `"`) || strings.HasPrefix(val, "'") {
|
||||
quote := string(val[0])
|
||||
for !(strings.HasSuffix(line, quote) && !strings.HasSuffix(line, `\`+quote)) {
|
||||
val = strings.ReplaceAll(val, `\`+quote, quote)
|
||||
if !scanner.Scan() {
|
||||
break
|
||||
}
|
||||
lineNumber++
|
||||
line = strings.ReplaceAll(scanner.Text(), `\"`, `"`)
|
||||
line = strings.ReplaceAll(scanner.Text(), `\`+quote, quote)
|
||||
val += "\n" + line
|
||||
}
|
||||
val = strings.TrimPrefix(val, `"`)
|
||||
val = strings.TrimSuffix(val, `"`)
|
||||
val = strings.TrimPrefix(val, quote)
|
||||
val = strings.TrimSuffix(val, quote)
|
||||
}
|
||||
|
||||
envMap[key] = val
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package caddycmd
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/caddyserver/caddy/v2"
|
||||
"github.com/caddyserver/certmagic"
|
||||
)
|
||||
|
||||
type storVal struct {
|
||||
StorageRaw json.RawMessage `json:"storage,omitempty" caddy:"namespace=caddy.storage inline_key=module"`
|
||||
}
|
||||
|
||||
// determineStorage returns the top-level storage module from the given config.
|
||||
// It may return nil even if no error.
|
||||
func determineStorage(configFile string, configAdapter string) (*storVal, error) {
|
||||
cfg, _, err := LoadConfig(configFile, configAdapter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// storage defaults to FileStorage if not explicitly
|
||||
// defined in the config, so the config can be valid
|
||||
// json but unmarshaling will fail.
|
||||
if !json.Valid(cfg) {
|
||||
return nil, &json.SyntaxError{}
|
||||
}
|
||||
var tmpStruct storVal
|
||||
err = json.Unmarshal(cfg, &tmpStruct)
|
||||
if err != nil {
|
||||
// default case, ignore the error
|
||||
var jsonError *json.SyntaxError
|
||||
if errors.As(err, &jsonError) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &tmpStruct, nil
|
||||
}
|
||||
|
||||
func cmdImportStorage(fl Flags) (int, error) {
|
||||
importStorageCmdConfigFlag := fl.String("config")
|
||||
importStorageCmdImportFile := fl.String("input")
|
||||
|
||||
if importStorageCmdConfigFlag == "" {
|
||||
return caddy.ExitCodeFailedStartup, errors.New("--config is required")
|
||||
}
|
||||
if importStorageCmdImportFile == "" {
|
||||
return caddy.ExitCodeFailedStartup, errors.New("--input is required")
|
||||
}
|
||||
|
||||
// extract storage from config if possible
|
||||
storageCfg, err := determineStorage(importStorageCmdConfigFlag, "")
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedStartup, err
|
||||
}
|
||||
|
||||
// load specified storage or fallback to default
|
||||
var stor certmagic.Storage
|
||||
ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()})
|
||||
defer cancel()
|
||||
if storageCfg != nil && storageCfg.StorageRaw != nil {
|
||||
val, err := ctx.LoadModule(storageCfg, "StorageRaw")
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedStartup, err
|
||||
}
|
||||
stor, err = val.(caddy.StorageConverter).CertMagicStorage()
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedStartup, err
|
||||
}
|
||||
} else {
|
||||
stor = caddy.DefaultStorage
|
||||
}
|
||||
|
||||
// setup input
|
||||
var f *os.File
|
||||
if importStorageCmdImportFile == "-" {
|
||||
f = os.Stdin
|
||||
} else {
|
||||
f, err = os.Open(importStorageCmdImportFile)
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedStartup, fmt.Errorf("opening input file: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
}
|
||||
|
||||
// store each archive element
|
||||
tr := tar.NewReader(f)
|
||||
for {
|
||||
hdr, err := tr.Next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedQuit, fmt.Errorf("reading archive: %v", err)
|
||||
}
|
||||
|
||||
b, err := io.ReadAll(tr)
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedQuit, fmt.Errorf("reading archive: %v", err)
|
||||
}
|
||||
|
||||
err = stor.Store(ctx, hdr.Name, b)
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedQuit, fmt.Errorf("reading archive: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("Successfully imported storage")
|
||||
return caddy.ExitCodeSuccess, nil
|
||||
}
|
||||
|
||||
func cmdExportStorage(fl Flags) (int, error) {
|
||||
exportStorageCmdConfigFlag := fl.String("config")
|
||||
exportStorageCmdOutputFlag := fl.String("output")
|
||||
|
||||
if exportStorageCmdConfigFlag == "" {
|
||||
return caddy.ExitCodeFailedStartup, errors.New("--config is required")
|
||||
}
|
||||
if exportStorageCmdOutputFlag == "" {
|
||||
return caddy.ExitCodeFailedStartup, errors.New("--output is required")
|
||||
}
|
||||
|
||||
// extract storage from config if possible
|
||||
storageCfg, err := determineStorage(exportStorageCmdConfigFlag, "")
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedStartup, err
|
||||
}
|
||||
|
||||
// load specified storage or fallback to default
|
||||
var stor certmagic.Storage
|
||||
ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()})
|
||||
defer cancel()
|
||||
if storageCfg != nil && storageCfg.StorageRaw != nil {
|
||||
val, err := ctx.LoadModule(storageCfg, "StorageRaw")
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedStartup, err
|
||||
}
|
||||
stor, err = val.(caddy.StorageConverter).CertMagicStorage()
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedStartup, err
|
||||
}
|
||||
} else {
|
||||
stor = caddy.DefaultStorage
|
||||
}
|
||||
|
||||
// enumerate all keys
|
||||
keys, err := stor.List(ctx, "", true)
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedStartup, err
|
||||
}
|
||||
|
||||
// setup output
|
||||
var f *os.File
|
||||
if exportStorageCmdOutputFlag == "-" {
|
||||
f = os.Stdout
|
||||
} else {
|
||||
f, err = os.Create(exportStorageCmdOutputFlag)
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedStartup, fmt.Errorf("opening output file: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
}
|
||||
|
||||
// `IsTerminal: true` keys hold the values we
|
||||
// care about, write them out
|
||||
tw := tar.NewWriter(f)
|
||||
for _, k := range keys {
|
||||
info, err := stor.Stat(ctx, k)
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedQuit, err
|
||||
}
|
||||
|
||||
if info.IsTerminal {
|
||||
v, err := stor.Load(ctx, k)
|
||||
if err != nil {
|
||||
return caddy.ExitCodeFailedQuit, err
|
||||
}
|
||||
|
||||
hdr := &tar.Header{
|
||||
Name: k,
|
||||
Mode: 0600,
|
||||
Size: int64(len(v)),
|
||||
}
|
||||
|
||||
if err = tw.WriteHeader(hdr); err != nil {
|
||||
return caddy.ExitCodeFailedQuit, fmt.Errorf("writing archive: %v", err)
|
||||
}
|
||||
if _, err = tw.Write(v); err != nil {
|
||||
return caddy.ExitCodeFailedQuit, fmt.Errorf("writing archive: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err = tw.Close(); err != nil {
|
||||
return caddy.ExitCodeFailedQuit, fmt.Errorf("writing archive: %v", err)
|
||||
}
|
||||
|
||||
return caddy.ExitCodeSuccess, nil
|
||||
}
|
||||
+26
-10
@@ -326,7 +326,7 @@ func (ctx Context) LoadModuleByID(id string, rawMsg json.RawMessage) (any, error
|
||||
|
||||
// fill in its config only if there is a config to fill in
|
||||
if len(rawMsg) > 0 {
|
||||
err := strictUnmarshalJSON(rawMsg, &val)
|
||||
err := StrictUnmarshalJSON(rawMsg, &val)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decoding module config: %s: %v", modInfo, err)
|
||||
}
|
||||
@@ -410,6 +410,11 @@ func (ctx Context) loadModuleInline(moduleNameKey, moduleScope string, raw json.
|
||||
// called during the Provision/Validate phase to reference a
|
||||
// module's own host app (since the parent app module is still
|
||||
// in the process of being provisioned, it is not yet ready).
|
||||
//
|
||||
// We return any type instead of the App type because it is NOT
|
||||
// intended for the caller of this method to be the one to start
|
||||
// or stop App modules. The caller is expected to assert to the
|
||||
// concrete type.
|
||||
func (ctx Context) App(name string) (any, error) {
|
||||
if app, ok := ctx.cfg.apps[name]; ok {
|
||||
return app, nil
|
||||
@@ -426,15 +431,23 @@ func (ctx Context) App(name string) (any, error) {
|
||||
return modVal, nil
|
||||
}
|
||||
|
||||
// AppIsConfigured returns whether an app named name has been
|
||||
// configured. Can be called before calling App() to avoid
|
||||
// instantiating an empty app when that's not desirable.
|
||||
func (ctx Context) AppIsConfigured(name string) bool {
|
||||
if _, ok := ctx.cfg.apps[name]; ok {
|
||||
return true
|
||||
// AppIfConfigured returns an app by its name if it has been
|
||||
// configured. Can be called instead of App() to avoid
|
||||
// instantiating an empty app when that's not desirable. If
|
||||
// the app has not been loaded, nil is returned.
|
||||
//
|
||||
// We return any type instead of the App type because it is not
|
||||
// intended for the caller of this method to be the one to start
|
||||
// or stop App modules. The caller is expected to assert to the
|
||||
// concrete type.
|
||||
func (ctx Context) AppIfConfigured(name string) any {
|
||||
if ctx.cfg == nil {
|
||||
// this can happen if the currently-active context
|
||||
// is being accessed, but no config has successfully
|
||||
// been loaded yet
|
||||
return nil
|
||||
}
|
||||
appRaw := ctx.cfg.AppsRaw[name]
|
||||
return appRaw != nil
|
||||
return ctx.cfg.apps[name]
|
||||
}
|
||||
|
||||
// Storage returns the configured Caddy storage implementation.
|
||||
@@ -448,7 +461,7 @@ func (ctx Context) Storage() certmagic.Storage {
|
||||
// different module; it panics if more than 1 value is passed in.
|
||||
//
|
||||
// Originally, this method's signature was `Logger(mod Module)`,
|
||||
// requiring that an instance of a Caddy module be passsed in.
|
||||
// requiring that an instance of a Caddy module be passed in.
|
||||
// However, that is no longer necessary, as the closest module
|
||||
// most recently associated with the context will be automatically
|
||||
// assumed. To prevent a sudden breaking change, this method's
|
||||
@@ -475,6 +488,9 @@ func (ctx Context) Logger(module ...Module) *zap.Logger {
|
||||
if len(module) > 0 {
|
||||
mod = module[0]
|
||||
}
|
||||
if mod == nil {
|
||||
return Log()
|
||||
}
|
||||
return ctx.cfg.Logging.Logger(mod)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,138 +1,152 @@
|
||||
module github.com/caddyserver/caddy/v2
|
||||
|
||||
go 1.18
|
||||
go 1.20
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.2.0
|
||||
github.com/Masterminds/sprig/v3 v3.2.2
|
||||
github.com/alecthomas/chroma v0.10.0
|
||||
github.com/BurntSushi/toml v1.3.2
|
||||
github.com/Masterminds/sprig/v3 v3.2.3
|
||||
github.com/alecthomas/chroma/v2 v2.7.0
|
||||
github.com/aryann/difflib v0.0.0-20210328193216-ff5ff6dc229b
|
||||
github.com/caddyserver/certmagic v0.17.1
|
||||
github.com/dustin/go-humanize v1.0.1-0.20200219035652-afde56e7acac
|
||||
github.com/caddyserver/certmagic v0.19.1
|
||||
github.com/dustin/go-humanize v1.0.1
|
||||
github.com/go-chi/chi v4.1.2+incompatible
|
||||
github.com/google/cel-go v0.12.4
|
||||
github.com/google/cel-go v0.15.1
|
||||
github.com/google/uuid v1.3.0
|
||||
github.com/klauspost/compress v1.15.9
|
||||
github.com/klauspost/cpuid/v2 v2.1.0
|
||||
github.com/lucas-clemente/quic-go v0.28.2-0.20220813150001-9957668d4301
|
||||
github.com/mholt/acmez v1.0.4
|
||||
github.com/prometheus/client_golang v1.12.2
|
||||
github.com/smallstep/certificates v0.21.0
|
||||
github.com/smallstep/cli v0.21.0
|
||||
github.com/smallstep/nosql v0.4.0
|
||||
github.com/smallstep/truststore v0.12.0
|
||||
github.com/spf13/cobra v1.1.3
|
||||
github.com/klauspost/compress v1.16.7
|
||||
github.com/klauspost/cpuid/v2 v2.2.5
|
||||
github.com/mastercactapus/proxyprotocol v0.0.4
|
||||
github.com/mholt/acmez v1.2.0
|
||||
github.com/prometheus/client_golang v1.14.0
|
||||
github.com/quic-go/quic-go v0.37.3
|
||||
github.com/smallstep/certificates v0.24.3-rc.5
|
||||
github.com/smallstep/nosql v0.6.0
|
||||
github.com/smallstep/truststore v0.12.1
|
||||
github.com/spf13/cobra v1.7.0
|
||||
github.com/spf13/pflag v1.0.5
|
||||
github.com/tailscale/tscert v0.0.0-20220316030059-54bbcb9f74e2
|
||||
github.com/yuin/goldmark v1.4.13
|
||||
github.com/yuin/goldmark-highlighting v0.0.0-20220208100518-594be1970594
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.34.0
|
||||
go.opentelemetry.io/otel v1.9.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.4.0
|
||||
go.opentelemetry.io/otel/sdk v1.4.0
|
||||
go.uber.org/zap v1.21.0
|
||||
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa
|
||||
golang.org/x/net v0.0.0-20220812165438-1d4ff48094d1
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211
|
||||
google.golang.org/genproto v0.0.0-20220502173005-c8bf987b8c21
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0
|
||||
github.com/stretchr/testify v1.8.4
|
||||
github.com/tailscale/tscert v0.0.0-20230509043813-4e9cb4f2b4ad
|
||||
github.com/yuin/goldmark v1.5.5
|
||||
github.com/yuin/goldmark-highlighting/v2 v2.0.0-20230729083705-37449abec8cc
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.42.0
|
||||
go.opentelemetry.io/contrib/propagators/autoprop v0.42.0
|
||||
go.opentelemetry.io/otel v1.16.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.16.0
|
||||
go.opentelemetry.io/otel/sdk v1.16.0
|
||||
go.uber.org/zap v1.25.0
|
||||
golang.org/x/crypto v0.11.0
|
||||
golang.org/x/exp v0.0.0-20230310171629-522b1b587ee0
|
||||
golang.org/x/net v0.12.0
|
||||
golang.org/x/sync v0.3.0
|
||||
golang.org/x/term v0.10.0
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20230706204954-ccb25ca9f130
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/Microsoft/go-winio v0.6.0 // indirect
|
||||
github.com/antlr/antlr4/runtime/Go/antlr/v4 v4.0.0-20230305170008-8188dc5388df // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/fxamacker/cbor/v2 v2.4.0 // indirect
|
||||
github.com/golang/glog v1.1.0 // indirect
|
||||
github.com/golang/mock v1.6.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
github.com/google/certificate-transparency-go v1.1.4 // indirect
|
||||
github.com/google/go-tpm v0.3.3 // indirect
|
||||
github.com/google/go-tspi v0.3.0 // indirect
|
||||
github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0 // indirect
|
||||
github.com/onsi/ginkgo/v2 v2.9.5 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/quic-go/qpack v0.4.0 // indirect
|
||||
github.com/quic-go/qtls-go1-20 v0.3.1 // indirect
|
||||
github.com/smallstep/go-attestation v0.4.4-0.20230509120429-e17291421738 // indirect
|
||||
github.com/x448/float16 v0.8.4 // indirect
|
||||
github.com/zeebo/blake3 v0.2.3 // indirect
|
||||
go.opentelemetry.io/contrib/propagators/aws v1.17.0 // indirect
|
||||
go.opentelemetry.io/contrib/propagators/b3 v1.17.0 // indirect
|
||||
go.opentelemetry.io/contrib/propagators/jaeger v1.17.0 // indirect
|
||||
go.opentelemetry.io/contrib/propagators/ot v1.17.0 // indirect
|
||||
google.golang.org/genproto v0.0.0-20230706204954-ccb25ca9f130 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.0.0-rc.1 // indirect
|
||||
filippo.io/edwards25519 v1.0.0 // indirect
|
||||
github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96 // indirect
|
||||
github.com/Masterminds/goutils v1.1.1 // indirect
|
||||
github.com/Masterminds/semver/v3 v3.1.1 // indirect
|
||||
github.com/antlr/antlr4/runtime/Go/antlr v0.0.0-20220418222510-f25a4f6275ed // indirect
|
||||
github.com/Masterminds/semver/v3 v3.2.0 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.1.2 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.2.1 // indirect
|
||||
github.com/cespare/xxhash v1.1.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e // indirect
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/chzyer/readline v1.5.1 // indirect
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect
|
||||
github.com/dgraph-io/badger v1.6.2 // indirect
|
||||
github.com/dgraph-io/badger/v2 v2.2007.4 // indirect
|
||||
github.com/dgraph-io/ristretto v0.0.4-0.20200906165740-41ebdbffecfd // indirect
|
||||
github.com/dgraph-io/ristretto v0.1.0 // indirect
|
||||
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
|
||||
github.com/dlclark/regexp2 v1.4.0 // indirect
|
||||
github.com/dlclark/regexp2 v1.7.0 // indirect
|
||||
github.com/felixge/httpsnoop v1.0.3 // indirect
|
||||
github.com/fsnotify/fsnotify v1.5.1 // indirect
|
||||
github.com/go-kit/kit v0.10.0 // indirect
|
||||
github.com/go-logfmt/logfmt v0.5.0 // indirect
|
||||
github.com/go-logr/logr v1.2.3 // indirect
|
||||
github.com/go-logfmt/logfmt v0.5.1 // indirect
|
||||
github.com/go-logr/logr v1.2.4 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-sql-driver/mysql v1.6.0 // indirect
|
||||
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 // indirect
|
||||
github.com/golang/protobuf v1.5.2 // indirect
|
||||
github.com/go-sql-driver/mysql v1.7.0 // indirect
|
||||
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect
|
||||
github.com/golang/protobuf v1.5.3 // indirect
|
||||
github.com/golang/snappy v0.0.4 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect
|
||||
github.com/huandu/xstrings v1.3.2 // indirect
|
||||
github.com/huandu/xstrings v1.3.3 // indirect
|
||||
github.com/imdario/mergo v0.3.12 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.0.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
||||
github.com/jackc/pgconn v1.10.1 // indirect
|
||||
github.com/jackc/pgconn v1.14.0 // indirect
|
||||
github.com/jackc/pgio v1.0.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgproto3/v2 v2.2.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
|
||||
github.com/jackc/pgtype v1.9.0 // indirect
|
||||
github.com/jackc/pgx/v4 v4.14.0 // indirect
|
||||
github.com/jackc/pgproto3/v2 v2.3.2 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/pgtype v1.14.0 // indirect
|
||||
github.com/jackc/pgx/v4 v4.18.0 // indirect
|
||||
github.com/libdns/libdns v0.2.1 // indirect
|
||||
github.com/manifoldco/promptui v0.9.0 // indirect
|
||||
github.com/marten-seemann/qpack v0.2.1 // indirect
|
||||
github.com/marten-seemann/qtls-go1-18 v0.1.2 // indirect
|
||||
github.com/marten-seemann/qtls-go1-19 v0.1.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.8 // indirect
|
||||
github.com/mattn/go-isatty v0.0.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.16 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
|
||||
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect
|
||||
github.com/micromdm/scep/v2 v2.1.0 // indirect
|
||||
github.com/miekg/dns v1.1.50 // indirect
|
||||
github.com/miekg/dns v1.1.55 // indirect
|
||||
github.com/mitchellh/copystructure v1.2.0 // indirect
|
||||
github.com/mitchellh/go-ps v1.0.0 // indirect
|
||||
github.com/mitchellh/reflectwalk v1.0.2 // indirect
|
||||
github.com/nxadm/tail v1.4.8 // indirect
|
||||
github.com/onsi/ginkgo v1.16.4 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/prometheus/client_model v0.2.0 // indirect
|
||||
github.com/prometheus/common v0.32.1 // indirect
|
||||
github.com/prometheus/procfs v0.7.3 // indirect
|
||||
github.com/rs/xid v1.2.1 // indirect
|
||||
github.com/prometheus/client_model v0.3.0 // indirect
|
||||
github.com/prometheus/common v0.37.0 // indirect
|
||||
github.com/prometheus/procfs v0.8.0 // indirect
|
||||
github.com/rs/xid v1.5.0 // indirect
|
||||
github.com/russross/blackfriday/v2 v2.1.0 // indirect
|
||||
github.com/shopspring/decimal v1.2.0 // indirect
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
|
||||
github.com/sirupsen/logrus v1.8.1 // indirect
|
||||
github.com/slackhq/nebula v1.5.2 // indirect
|
||||
github.com/sirupsen/logrus v1.9.3 // indirect
|
||||
github.com/slackhq/nebula v1.6.1 // indirect
|
||||
github.com/spf13/cast v1.4.1 // indirect
|
||||
github.com/stoewer/go-strcase v1.2.0 // indirect
|
||||
github.com/urfave/cli v1.22.5 // indirect
|
||||
go.etcd.io/bbolt v1.3.6 // indirect
|
||||
github.com/urfave/cli v1.22.14 // indirect
|
||||
go.etcd.io/bbolt v1.3.7 // indirect
|
||||
go.mozilla.org/pkcs7 v0.0.0-20210826202110-33d05740a352 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.4.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.4.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v0.31.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.9.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v0.12.0 // indirect
|
||||
go.step.sm/cli-utils v0.7.3 // indirect
|
||||
go.step.sm/crypto v0.16.2 // indirect
|
||||
go.step.sm/linkedca v0.16.1 // indirect
|
||||
go.uber.org/atomic v1.9.0 // indirect
|
||||
go.uber.org/multierr v1.6.0 // indirect
|
||||
golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3 // indirect
|
||||
golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10
|
||||
golang.org/x/text v0.3.8-0.20211004125949-5bd84dd9b33b // indirect
|
||||
golang.org/x/tools v0.1.10 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||
google.golang.org/grpc v1.46.0 // indirect
|
||||
google.golang.org/protobuf v1.28.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.16.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.16.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.16.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.16.0
|
||||
go.opentelemetry.io/proto/otlp v0.19.0 // indirect
|
||||
go.step.sm/cli-utils v0.8.0 // indirect
|
||||
go.step.sm/crypto v0.33.0
|
||||
go.step.sm/linkedca v0.20.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
golang.org/x/mod v0.11.0 // indirect
|
||||
golang.org/x/sys v0.10.0
|
||||
golang.org/x/text v0.11.0 // indirect
|
||||
golang.org/x/tools v0.10.0 // indirect
|
||||
google.golang.org/grpc v1.56.2 // indirect
|
||||
google.golang.org/protobuf v1.31.0 // indirect
|
||||
gopkg.in/square/go-jose.v2 v2.6.0 // indirect
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
|
||||
howett.net/plist v1.0.0 // indirect
|
||||
)
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
// Copyright 2015 Matthew Holt and The Caddy Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SplitUnixSocketPermissionsBits takes a unix socket address in the
|
||||
// unusual "path|bits" format (e.g. /run/caddy.sock|0222) and tries
|
||||
// to split it into socket path (host) and permissions bits (port).
|
||||
// Colons (":") can't be used as separator, as socket paths on Windows
|
||||
// may include a drive letter (e.g. `unix/c:\absolute\path.sock`).
|
||||
// Permission bits will default to 0200 if none are specified.
|
||||
// Throws an error, if the first carrying bit does not
|
||||
// include write perms (e.g. `0422` or `022`).
|
||||
// Symbolic permission representation (e.g. `u=w,g=w,o=w`)
|
||||
// is not supported and will throw an error for now!
|
||||
func SplitUnixSocketPermissionsBits(addr string) (path string, fileMode fs.FileMode, err error) {
|
||||
addrSplit := strings.SplitN(addr, "|", 2)
|
||||
|
||||
if len(addrSplit) == 2 {
|
||||
// parse octal permission bit string as uint32
|
||||
fileModeUInt64, err := strconv.ParseUint(addrSplit[1], 8, 32)
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("could not parse octal permission bits in %s: %v", addr, err)
|
||||
}
|
||||
fileMode = fs.FileMode(fileModeUInt64)
|
||||
|
||||
// FileMode.String() returns a string like `-rwxr-xr--` for `u=rwx,g=rx,o=r` (`0754`)
|
||||
if string(fileMode.String()[2]) != "w" {
|
||||
return "", 0, fmt.Errorf("owner of the socket requires '-w-' (write, octal: '2') permissions at least; got '%s' in %s", fileMode.String()[1:4], addr)
|
||||
}
|
||||
|
||||
return addrSplit[0], fileMode, nil
|
||||
}
|
||||
|
||||
// default to 0200 (symbolic: `u=w,g=,o=`)
|
||||
// if no permission bits are specified
|
||||
return addr, 0200, nil
|
||||
}
|
||||
@@ -12,15 +12,12 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// TODO: Go 1.19 introduced the "unix" build tag. We have to support Go 1.18 until Go 1.20 is released.
|
||||
// When Go 1.19 is our minimum, change this build tag to simply "!unix".
|
||||
// (see similar change needed in listen_unix.go)
|
||||
//go:build !(aix || android || darwin || dragonfly || freebsd || hurd || illumos || ios || linux || netbsd || openbsd || solaris)
|
||||
//go:build !unix
|
||||
|
||||
package caddy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"context"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -29,21 +26,14 @@ import (
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func ListenTimeout(network, addr string, keepAlivePeriod time.Duration) (net.Listener, error) {
|
||||
// check to see if plugin provides listener
|
||||
if ln, err := getListenerFromPlugin(network, addr); err != nil || ln != nil {
|
||||
return ln, err
|
||||
}
|
||||
|
||||
lnKey := listenerKey(network, addr)
|
||||
func reuseUnixSocket(network, addr string) (any, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func listenTCPOrUnix(ctx context.Context, lnKey string, network, address string, config net.ListenConfig) (net.Listener, error) {
|
||||
sharedLn, _, err := listenerPool.LoadOrNew(lnKey, func() (Destructor, error) {
|
||||
ln, err := net.Listen(network, addr)
|
||||
ln, err := config.Listen(ctx, network, address)
|
||||
if err != nil {
|
||||
// https://github.com/caddyserver/caddy/pull/4534
|
||||
if isUnixNetwork(network) && isListenBindAddressAlreadyInUseError(err) {
|
||||
return nil, fmt.Errorf("%w: this can happen if Caddy was forcefully killed", err)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &sharedListener{Listener: ln, key: lnKey}, nil
|
||||
@@ -51,8 +41,7 @@ func ListenTimeout(network, addr string, keepAlivePeriod time.Duration) (net.Lis
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &fakeCloseListener{sharedListener: sharedLn.(*sharedListener), keepAlivePeriod: keepAlivePeriod}, nil
|
||||
return &fakeCloseListener{sharedListener: sharedLn.(*sharedListener), keepAlivePeriod: config.KeepAlive}, nil
|
||||
}
|
||||
|
||||
// fakeCloseListener is a private wrapper over a listener that
|
||||
@@ -156,8 +145,6 @@ func (sl *sharedListener) clearDeadline() error {
|
||||
switch ln := sl.Listener.(type) {
|
||||
case *net.TCPListener:
|
||||
err = ln.SetDeadline(time.Time{})
|
||||
case *net.UnixListener:
|
||||
err = ln.SetDeadline(time.Time{})
|
||||
}
|
||||
sl.deadline = false
|
||||
}
|
||||
@@ -173,8 +160,6 @@ func (sl *sharedListener) setDeadline() error {
|
||||
switch ln := sl.Listener.(type) {
|
||||
case *net.TCPListener:
|
||||
err = ln.SetDeadline(timeInPast)
|
||||
case *net.UnixListener:
|
||||
err = ln.SetDeadline(timeInPast)
|
||||
}
|
||||
sl.deadline = true
|
||||
}
|
||||
|
||||
+112
-54
@@ -12,10 +12,10 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// TODO: Go 1.19 introduced the "unix" build tag. We have to support Go 1.18 until Go 1.20 is released.
|
||||
// When Go 1.19 is our minimum, remove this build tag, since "_unix" in the filename will do this.
|
||||
// (see also change needed in listen.go)
|
||||
//go:build aix || android || darwin || dragonfly || freebsd || hurd || illumos || ios || linux || netbsd || openbsd || solaris
|
||||
// Even though the filename ends in _unix.go, we still have to specify the
|
||||
// build constraint here, because the filename convention only works for
|
||||
// literal GOOS values, and "unix" is a shortcut unique to build tags.
|
||||
//go:build unix
|
||||
|
||||
package caddy
|
||||
|
||||
@@ -24,80 +24,111 @@ import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// ListenTimeout is the same as Listen, but with a configurable keep-alive timeout duration.
|
||||
func ListenTimeout(network, addr string, keepalivePeriod time.Duration) (net.Listener, error) {
|
||||
// check to see if plugin provides listener
|
||||
if ln, err := getListenerFromPlugin(network, addr); err != nil || ln != nil {
|
||||
return ln, err
|
||||
// reuseUnixSocket copies and reuses the unix domain socket (UDS) if we already
|
||||
// have it open; if not, unlink it so we can have it. No-op if not a unix network.
|
||||
func reuseUnixSocket(network, addr string) (any, error) {
|
||||
if !IsUnixNetwork(network) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
socketKey := listenerKey(network, addr)
|
||||
if isUnixNetwork(network) {
|
||||
unixSocketsMu.Lock()
|
||||
defer unixSocketsMu.Unlock()
|
||||
|
||||
socket, exists := unixSockets[socketKey]
|
||||
if exists {
|
||||
// make copy of file descriptor
|
||||
socketFile, err := socket.File() // dup() deep down
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
socket, exists := unixSockets[socketKey]
|
||||
if exists {
|
||||
// make copy of file descriptor
|
||||
socketFile, err := socket.File() // does dup() deep down
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// use copy to make new listener
|
||||
// use copied fd to make new Listener or PacketConn, then replace
|
||||
// it in the map so that future copies always come from the most
|
||||
// recent fd (as the previous ones will be closed, and we'd get
|
||||
// "use of closed network connection" errors) -- note that we
|
||||
// preserve the *pointer* to the counter (not just the value) so
|
||||
// that all socket wrappers will refer to the same value
|
||||
switch unixSocket := socket.(type) {
|
||||
case *unixListener:
|
||||
ln, err := net.FileListener(socketFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
atomic.AddInt32(unixSocket.count, 1)
|
||||
unixSockets[socketKey] = &unixListener{ln.(*net.UnixListener), socketKey, unixSocket.count}
|
||||
|
||||
// the old socket fd will likely be closed soon, so replace it in the map
|
||||
unixSockets[socketKey] = ln.(*net.UnixListener)
|
||||
|
||||
return ln.(*net.UnixListener), nil
|
||||
case *unixConn:
|
||||
pc, err := net.FilePacketConn(socketFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
atomic.AddInt32(unixSocket.count, 1)
|
||||
unixSockets[socketKey] = &unixConn{pc.(*net.UnixConn), addr, socketKey, unixSocket.count}
|
||||
}
|
||||
|
||||
// from what I can tell after some quick research, it's quite common for programs to
|
||||
// leave their socket file behind after they close, so the typical pattern is to
|
||||
// unlink it before you bind to it -- this is often crucial if the last program using
|
||||
// it was killed forcefully without a chance to clean up the socket, but there is a
|
||||
// race, as the comment in net.UnixListener.close() explains... oh well?
|
||||
if err := syscall.Unlink(addr); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
return unixSockets[socketKey], nil
|
||||
}
|
||||
|
||||
config := &net.ListenConfig{Control: reusePort, KeepAlive: keepalivePeriod}
|
||||
|
||||
ln, err := config.Listen(context.Background(), network, addr)
|
||||
if err != nil {
|
||||
// from what I can tell after some quick research, it's quite common for programs to
|
||||
// leave their socket file behind after they close, so the typical pattern is to
|
||||
// unlink it before you bind to it -- this is often crucial if the last program using
|
||||
// it was killed forcefully without a chance to clean up the socket, but there is a
|
||||
// race, as the comment in net.UnixListener.close() explains... oh well, I guess?
|
||||
if err := syscall.Unlink(addr); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if uln, ok := ln.(*net.UnixListener); ok {
|
||||
// TODO: ideally, we should unlink the socket once we know we're done using it
|
||||
// (i.e. either on exit or a new config that doesn't use this socket; in UsagePool
|
||||
// terms, when the reference count reaches 0), but given that we unlink existing
|
||||
// socket before we create the new one anyway (see above), we don't necessarily
|
||||
// need to clean up after ourselves; still, doing so would probably be more tidy
|
||||
uln.SetUnlinkOnClose(false)
|
||||
unixSockets[socketKey] = uln
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func listenTCPOrUnix(ctx context.Context, lnKey string, network, address string, config net.ListenConfig) (net.Listener, error) {
|
||||
// wrap any Control function set by the user so we can also add our reusePort control without clobbering theirs
|
||||
oldControl := config.Control
|
||||
config.Control = func(network, address string, c syscall.RawConn) error {
|
||||
if oldControl != nil {
|
||||
if err := oldControl(network, address, c); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return reusePort(network, address, c)
|
||||
}
|
||||
|
||||
return ln, nil
|
||||
// even though SO_REUSEPORT lets us bind the socket multiple times,
|
||||
// we still put it in the listenerPool so we can count how many
|
||||
// configs are using this socket; necessary to ensure we can know
|
||||
// whether to enforce shutdown delays, for example (see #5393).
|
||||
ln, err := config.Listen(ctx, network, address)
|
||||
if err == nil {
|
||||
listenerPool.LoadOrStore(lnKey, nil)
|
||||
}
|
||||
|
||||
// if new listener is a unix socket, make sure we can reuse it later
|
||||
// (we do our own "unlink on close" -- not required, but more tidy)
|
||||
one := int32(1)
|
||||
if unix, ok := ln.(*net.UnixListener); ok {
|
||||
unix.SetUnlinkOnClose(false)
|
||||
ln = &unixListener{unix, lnKey, &one}
|
||||
unixSockets[lnKey] = ln.(*unixListener)
|
||||
}
|
||||
|
||||
// lightly wrap the listener so that when it is closed,
|
||||
// we can decrement the usage pool counter
|
||||
return deleteListener{ln, lnKey}, err
|
||||
}
|
||||
|
||||
// reusePort sets SO_REUSEPORT. Ineffective for unix sockets.
|
||||
func reusePort(network, address string, conn syscall.RawConn) error {
|
||||
if IsUnixNetwork(network) {
|
||||
return nil
|
||||
}
|
||||
return conn.Control(func(descriptor uintptr) {
|
||||
if err := unix.SetsockoptInt(int(descriptor), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil {
|
||||
if err := unix.SetsockoptInt(int(descriptor), unix.SOL_SOCKET, unixSOREUSEPORT, 1); err != nil {
|
||||
Log().Error("setting SO_REUSEPORT",
|
||||
zap.String("network", network),
|
||||
zap.String("address", address),
|
||||
@@ -107,9 +138,36 @@ func reusePort(network, address string, conn syscall.RawConn) error {
|
||||
})
|
||||
}
|
||||
|
||||
// unixSockets keeps track of the currently-active unix sockets
|
||||
// so we can transfer their FDs gracefully during reloads.
|
||||
var (
|
||||
unixSockets = make(map[string]*net.UnixListener)
|
||||
unixSocketsMu sync.Mutex
|
||||
)
|
||||
type unixListener struct {
|
||||
*net.UnixListener
|
||||
mapKey string
|
||||
count *int32 // accessed atomically
|
||||
}
|
||||
|
||||
func (uln *unixListener) Close() error {
|
||||
newCount := atomic.AddInt32(uln.count, -1)
|
||||
if newCount == 0 {
|
||||
defer func() {
|
||||
addr := uln.Addr().String()
|
||||
unixSocketsMu.Lock()
|
||||
delete(unixSockets, uln.mapKey)
|
||||
unixSocketsMu.Unlock()
|
||||
_ = syscall.Unlink(addr)
|
||||
}()
|
||||
}
|
||||
return uln.UnixListener.Close()
|
||||
}
|
||||
|
||||
// deleteListener is a type that simply deletes itself
|
||||
// from the listenerPool when it closes. It is used
|
||||
// solely for the purpose of reference counting (i.e.
|
||||
// counting how many configs are using a given socket).
|
||||
type deleteListener struct {
|
||||
net.Listener
|
||||
lnKey string
|
||||
}
|
||||
|
||||
func (dl deleteListener) Close() error {
|
||||
_, _ = listenerPool.Delete(dl.lnKey)
|
||||
return dl.Listener.Close()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build unix && !freebsd
|
||||
|
||||
package caddy
|
||||
|
||||
import "golang.org/x/sys/unix"
|
||||
|
||||
const unixSOREUSEPORT = unix.SO_REUSEPORT
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user