Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3be12a45c6 | ||
|
|
fba139fdec | ||
|
|
e0dd0e4348 | ||
|
|
710bdf380a | ||
|
|
7b83f36060 | ||
|
|
2a23956a8b | ||
|
|
9269643c0e | ||
|
|
6c8fe4ebf7 | ||
|
|
037ac76d26 | ||
|
|
9faaefa83a | ||
|
|
85700efcd1 | ||
|
|
91a8c76bdb | ||
|
|
88e2780a54 | ||
|
|
60fcb2e214 | ||
|
|
c8224fd434 |
No files matched your search
@@ -62,7 +62,7 @@ jobs:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: "24"
|
||||
|
||||
@@ -165,7 +165,7 @@ jobs:
|
||||
exit $FAILED
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
path: |
|
||||
@@ -280,7 +280,7 @@ jobs:
|
||||
'
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -294,7 +294,7 @@ jobs:
|
||||
|
||||
- name: Upload raw coverage data
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: api-coverage-${{ matrix.suite }}
|
||||
path: ${{ env.GOCOVERDIR }}
|
||||
@@ -328,7 +328,7 @@ jobs:
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -342,7 +342,7 @@ jobs:
|
||||
|
||||
- name: Upload raw coverage data
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: api-coverage-cli-${{ matrix.suite }}
|
||||
path: ${{ env.GOCOVERDIR }}
|
||||
@@ -376,7 +376,7 @@ jobs:
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -390,7 +390,7 @@ jobs:
|
||||
|
||||
- name: Upload raw coverage data
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: api-coverage-ldap-pool-${{ matrix.suite }}
|
||||
path: ${{ env.GOCOVERDIR }}
|
||||
@@ -468,7 +468,7 @@ jobs:
|
||||
'
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -485,7 +485,7 @@ jobs:
|
||||
|
||||
- name: Upload raw coverage data
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: api-coverage-core-${{ matrix.suite }}
|
||||
path: ${{ env.GOCOVERDIR }}
|
||||
@@ -534,7 +534,7 @@ jobs:
|
||||
vault_storage: true
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
# 24.16.0 breaks playwright install (yauzl zip extraction hangs); pin to last known good.
|
||||
# https://github.com/microsoft/playwright/issues/40724
|
||||
@@ -551,7 +551,7 @@ jobs:
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -683,7 +683,7 @@ jobs:
|
||||
|
||||
- name: Upload tracing result
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: playwright-traces-${{ matrix.suite }}-${{ github.run_attempt }}
|
||||
path: web/reports/e2e
|
||||
@@ -691,7 +691,7 @@ jobs:
|
||||
|
||||
- name: Upload a11y result
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: playwright-a11y-result-${{ matrix.suite }}-${{ github.run_attempt }}
|
||||
path: web/reports/e2e/a11y-report.json
|
||||
@@ -712,7 +712,7 @@ jobs:
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -737,7 +737,7 @@ jobs:
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -762,7 +762,7 @@ jobs:
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -787,7 +787,7 @@ jobs:
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -809,7 +809,7 @@ jobs:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: "24"
|
||||
|
||||
@@ -842,7 +842,7 @@ jobs:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: "24"
|
||||
|
||||
@@ -876,7 +876,7 @@ jobs:
|
||||
cache: true
|
||||
|
||||
- name: Download raw coverage data
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
pattern: api-coverage-*
|
||||
path: ${{ env.GOCOVERDIR }}
|
||||
|
||||
@@ -482,9 +482,9 @@ jobs:
|
||||
# - suite: oidc-iframe
|
||||
# args: "--type playwright specs/oidc/iframeTokenRenewal.spec.ts"
|
||||
# oidc_iframe: true
|
||||
# - suite: app-provider
|
||||
# args: "--type playwright --suites app-provider"
|
||||
# collaboration: true
|
||||
- suite: app-provider
|
||||
args: "--type playwright --suites app-provider"
|
||||
collaboration: true
|
||||
# - suite: ocm
|
||||
# args: "--type playwright --suites ocm"
|
||||
# federated: true
|
||||
@@ -497,7 +497,7 @@ jobs:
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
# 24.16.0 breaks playwright install (yauzl zip extraction hangs); pin to last known good.
|
||||
# https://github.com/microsoft/playwright/issues/40724
|
||||
@@ -540,14 +540,84 @@ jobs:
|
||||
run: make -C tests/config/k8s create-cluster
|
||||
|
||||
- name: Prepare Helm Charts
|
||||
env:
|
||||
ENABLE_WOPI: ${{ matrix.suite == 'app-provider' }}
|
||||
run: make -C tests/config/k8s prepare-charts
|
||||
|
||||
- name: Deploy Suite-Specific External Backends
|
||||
run: |
|
||||
if [[ "${{ matrix.suite }}" == "app-provider" ]]; then
|
||||
# Start Collabora
|
||||
docker run -d \
|
||||
--name collabora \
|
||||
--network host \
|
||||
--entrypoint bash \
|
||||
-e DONT_GEN_SSL_CERT=set \
|
||||
-e "extra_params=--o:ssl.enable=true --o:ssl.termination=true --o:welcome.enable=false --o:net.frame_ancestors=https://127.0.0.1:9200" \
|
||||
collabora/code:25.04.7.3.1 \
|
||||
-c "coolconfig generate-proof-key && bash /start-collabora-online.sh"
|
||||
timeout 150 bash -c 'until curl -kfsSL https://localhost:9980/hosting/discovery > /dev/null; do sleep 5; done'
|
||||
echo "collabora ready."
|
||||
|
||||
# Start OnlyOffice
|
||||
docker run -d \
|
||||
--name onlyoffice \
|
||||
-p 7443:443 \
|
||||
--add-host "$TEST_SERVER_DOMAIN:host-gateway" \
|
||||
-e WOPI_ENABLED=true \
|
||||
-e USE_UNAUTHORIZED_STORAGE=true \
|
||||
-v "$(pwd)/tests/config/ci/only-office.json:/tmp/local.json:ro" \
|
||||
--entrypoint /bin/sh \
|
||||
onlyoffice/documentserver:9.2.1 \
|
||||
-c "set -e
|
||||
cp /tmp/local.json /etc/onlyoffice/documentserver/local.json
|
||||
openssl req -x509 -newkey rsa:4096 -keyout onlyoffice.key -out onlyoffice.crt -sha256 -days 365 -batch -nodes
|
||||
mkdir -p /var/www/onlyoffice/Data/certs
|
||||
cp onlyoffice.key /var/www/onlyoffice/Data/certs/
|
||||
cp onlyoffice.crt /var/www/onlyoffice/Data/certs/
|
||||
chmod 400 /var/www/onlyoffice/Data/certs/onlyoffice.key
|
||||
/app/ds/run-document-server.sh"
|
||||
timeout 150 bash -c 'until curl -kfsSL https://localhost:7443/hosting/discovery > /dev/null; do sleep 5; done'
|
||||
echo "onlyoffice ready."
|
||||
|
||||
#Start FakeOffice
|
||||
docker run -d --name fakeoffice --network host \
|
||||
-v "$(pwd):/ocis:ro" \
|
||||
python:3-alpine \
|
||||
python3 -c "
|
||||
import http.server, pathlib
|
||||
body = pathlib.Path('/ocis/tests/config/ci/hosting-discovery.xml').read_bytes()
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Type', 'text/xml')
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
def log_message(self, *a): pass
|
||||
http.server.HTTPServer(('', 8080), H).serve_forever()
|
||||
"
|
||||
timeout 60 bash -c 'until curl -fsSL http://localhost:8080/hosting/discovery > /dev/null; do sleep 5; done'
|
||||
echo "fakeoffice ready."
|
||||
|
||||
bash tests/config/k8s/expose-external-svc.sh collabora:9980
|
||||
bash tests/config/k8s/expose-external-svc.sh onlyoffice:7443
|
||||
bash tests/config/k8s/expose-external-svc.sh fakeoffice:8080
|
||||
fi
|
||||
|
||||
- name: Deploy oCIS
|
||||
run: |
|
||||
cd tests/config/k8s
|
||||
kubectl get pods -n "$TEST_SERVER_DOMAIN" -Aw &
|
||||
make deploy-ocis
|
||||
|
||||
- name: Expose node ports
|
||||
if: ${{ matrix.suite == 'app-provider' }}
|
||||
run: |
|
||||
bash tests/config/k8s/expose-nodeports.sh collaboration-collabora 9300 30300
|
||||
bash tests/config/k8s/expose-nodeports.sh collaboration-fakeoffice 9300 30301
|
||||
bash tests/config/k8s/expose-nodeports.sh collaboration-onlyoffice 9300 30302
|
||||
bash tests/config/k8s/expose-nodeports.sh collaboration-fakeoffice 9304 30304
|
||||
|
||||
- name: Wait for oCIS to be ready
|
||||
env:
|
||||
FILE_URL: ${{ env.TEST_SERVER_URL }}/remote.php/dav/files/admin/hello1.txt
|
||||
@@ -618,11 +688,12 @@ jobs:
|
||||
E2E_ARGS: "${{ matrix.args }}"
|
||||
K8S: ${{ env.K8S }}
|
||||
TEST_SERVER_URL: ${{ env.TEST_SERVER_URL }}
|
||||
COLLABORATION_NEEDED: ${{ matrix.collaboration == true && 'true' || 'false' }}
|
||||
run: python3 tests/acceptance/run-e2e.py
|
||||
|
||||
- name: Upload Playwright traces
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: playwright-traces-${{ matrix.suite }}-k8s-${{ github.run_attempt }}
|
||||
path: web/reports/e2e
|
||||
@@ -630,7 +701,7 @@ jobs:
|
||||
|
||||
- name: Upload a11y result
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: playwright-a11y-result-${{ matrix.suite }}-k8s-${{ github.run_attempt }}
|
||||
path: web/reports/e2e/a11y-report.json
|
||||
@@ -638,7 +709,7 @@ jobs:
|
||||
|
||||
- name: Upload oCIS logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: ocis-logs-${{ matrix.suite }}-k8s-${{ github.run_attempt }}
|
||||
path: tests/config/k8s/logs
|
||||
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: 24.15.0
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
|
||||
+15
-186
@@ -14,9 +14,6 @@ on:
|
||||
default: ''
|
||||
|
||||
env:
|
||||
PRODUCTION_RELEASE_TAGS: '5.0,7,8'
|
||||
DOCKER_REPO_ROLLING: owncloud/ocis-rolling
|
||||
DOCKER_REPO_PRODUCTION: owncloud/ocis
|
||||
NODE_VERSION: '24'
|
||||
PNPM_VERSION: '10.28.1'
|
||||
GOLANG_BUILD_IMAGE: 'golang:1.26.8-alpine3.23@sha256:a8fa79c5bd40d880b52bd3b6d7669ecdcfd00e85facdd427d279efb5ddd79cb1'
|
||||
@@ -27,9 +24,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
version: ${{ steps.info.outputs.version }}
|
||||
is_production: ${{ steps.info.outputs.is_production }}
|
||||
is_prerelease: ${{ steps.info.outputs.is_prerelease }}
|
||||
docker_repos: ${{ steps.info.outputs.docker_repos }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
if: ${{ github.ref_type == 'branch' || (github.event_name == 'workflow_dispatch' && inputs.version_override == '') }}
|
||||
@@ -75,23 +70,10 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
IS_PRODUCTION=false
|
||||
for TAG in ${PRODUCTION_RELEASE_TAGS//,/ }; do
|
||||
[[ "$VERSION" == "$TAG"* ]] && IS_PRODUCTION=true && break
|
||||
done
|
||||
|
||||
[[ "$VERSION" == *"-"* ]] && IS_PRERELEASE=true || IS_PRERELEASE=false
|
||||
|
||||
if [[ "$IS_PRODUCTION" == "true" && "$IS_PRERELEASE" == "false" ]]; then
|
||||
REPOS=[\"$DOCKER_REPO_ROLLING\",\"$DOCKER_REPO_PRODUCTION\"]
|
||||
else
|
||||
REPOS=[\"$DOCKER_REPO_ROLLING\"]
|
||||
fi
|
||||
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "is_production=$IS_PRODUCTION" >> $GITHUB_OUTPUT
|
||||
echo "is_prerelease=$IS_PRERELEASE" >> $GITHUB_OUTPUT
|
||||
echo "docker_repos=$REPOS" >> $GITHUB_OUTPUT
|
||||
|
||||
generate-code:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -102,7 +84,7 @@ jobs:
|
||||
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
- run: npm install --silent -g yarn npx --force
|
||||
@@ -119,7 +101,7 @@ jobs:
|
||||
run: |
|
||||
VERSION="${{ needs.determine-release-type.outputs.version }}"
|
||||
sed -i "s/LatestTag = \".*\"/LatestTag = \"$VERSION\"/" ocis-pkg/version/version.go
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: generated-code
|
||||
path: |
|
||||
@@ -128,159 +110,6 @@ jobs:
|
||||
!web
|
||||
retention-days: 1
|
||||
|
||||
docker-build:
|
||||
if: false
|
||||
name: docker-build (${{ matrix.arch }}, ${{ matrix.repo }})
|
||||
runs-on: ${{ matrix.arch == 'amd64' && 'ubuntu-24.04' || 'ubuntu-24.04-arm' }}
|
||||
timeout-minutes: 120
|
||||
needs: [determine-release-type, generate-code, security-scan-trivy]
|
||||
strategy:
|
||||
matrix:
|
||||
arch: [amd64, arm64]
|
||||
repo: ${{ fromJSON(needs.determine-release-type.outputs.docker_repos) }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: generated-code
|
||||
path: .
|
||||
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||
- uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||
with:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- id: goversion
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- run: |
|
||||
ALPINE_VERSION=$(grep '^FROM.*alpine:' ocis/docker/Dockerfile.linux.${{ matrix.arch }} | grep -o 'alpine:[0-9.]*' | cut -d: -f2 | cut -d. -f1,2)
|
||||
docker run --rm \
|
||||
-v "${{ github.workspace }}:/workspace" \
|
||||
-w /workspace \
|
||||
"golang:${{ steps.goversion.outputs.go-version }}-alpine${ALPINE_VERSION}" \
|
||||
sh -c "apk add --no-cache bash gcc musl-dev vips-dev make git && \
|
||||
git config --global --add safe.directory /workspace && \
|
||||
CGO_ENABLED=1 ENABLE_VIPS=true VERSION=${{ needs.determine-release-type.outputs.version }} \
|
||||
make -C ocis release-linux-docker-${{ matrix.arch }}"
|
||||
- id: tags
|
||||
run: |
|
||||
VERSION="${{ needs.determine-release-type.outputs.version }}"
|
||||
REPO="${{ matrix.repo }}"
|
||||
ARCH="${{ matrix.arch }}"
|
||||
printf "tags<<EOF\n%s\nEOF\n" \
|
||||
"${REPO}:${VERSION}-linux-${ARCH}" >> $GITHUB_OUTPUT
|
||||
- id: build
|
||||
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||
with:
|
||||
context: ocis
|
||||
file: ocis/docker/Dockerfile.linux.${{ matrix.arch }}
|
||||
platforms: linux/${{ matrix.arch }}
|
||||
load: true
|
||||
push: false
|
||||
provenance: false
|
||||
build-args: |
|
||||
REVISION=${{ github.sha }}
|
||||
VERSION=${{ needs.determine-release-type.outputs.version }}
|
||||
tags: ${{ steps.tags.outputs.tags }}
|
||||
- id: trivy
|
||||
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
|
||||
continue-on-error: true
|
||||
with:
|
||||
image-ref: ${{ steps.tags.outputs.tags }}
|
||||
format: table
|
||||
exit-code: 1
|
||||
severity: HIGH,CRITICAL
|
||||
ignore-unfixed: true
|
||||
skip-files: /usr/bin/gomplate,/usr/bin/wait-for
|
||||
hide-progress: true
|
||||
env:
|
||||
TRIVY_IGNOREFILE: .trivyignore
|
||||
- name: Block on vulnerabilities
|
||||
if: steps.trivy.outcome == 'failure'
|
||||
run: |
|
||||
echo "::error title=Security scan blocked release::Image ${{ steps.tags.outputs.tags }} has HIGH or CRITICAL vulnerabilities (see Trivy report above). Fix all findings before releasing."
|
||||
exit 1
|
||||
- name: push
|
||||
if: steps.trivy.outcome == 'success'
|
||||
run: docker push ${{ steps.tags.outputs.tags }}
|
||||
|
||||
docker-scan:
|
||||
name: docker-scan (${{ matrix.arch }}, ${{ matrix.repo }})
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
needs: [determine-release-type, docker-build]
|
||||
strategy:
|
||||
matrix:
|
||||
arch: [amd64]
|
||||
repo: ${{ fromJSON(needs.determine-release-type.outputs.docker_repos) }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
|
||||
id: trivy
|
||||
continue-on-error: true
|
||||
with:
|
||||
image-ref: ${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-${{ matrix.arch }}
|
||||
format: table
|
||||
exit-code: 1
|
||||
severity: HIGH,CRITICAL
|
||||
ignore-unfixed: true
|
||||
skip-files: /usr/bin/gomplate,/usr/bin/wait-for
|
||||
hide-progress: true
|
||||
env:
|
||||
TRIVY_IGNOREFILE: .trivyignore
|
||||
|
||||
- name: Block on vulnerabilities
|
||||
if: steps.trivy.outcome == 'failure'
|
||||
run: |
|
||||
echo "::error title=Security scan blocked release::Image ${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-${{ matrix.arch }} has HIGH or CRITICAL vulnerabilities (see Trivy report above). Fix all findings before releasing."
|
||||
exit 1
|
||||
|
||||
docker-manifest:
|
||||
if: false
|
||||
name: docker-manifest (${{ matrix.repo }})
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
needs: [determine-release-type, docker-build, docker-scan]
|
||||
strategy:
|
||||
matrix:
|
||||
repo: ${{ fromJSON(needs.determine-release-type.outputs.docker_repos) }}
|
||||
steps:
|
||||
- uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||
with:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- if: ${{ contains(matrix.repo, 'rolling') }}
|
||||
run: |
|
||||
docker buildx imagetools create \
|
||||
-t "${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}" \
|
||||
"${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-amd64" \
|
||||
"${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-arm64"
|
||||
- if: ${{ !contains(matrix.repo, 'rolling') }}
|
||||
run: |
|
||||
docker buildx imagetools create \
|
||||
-t "${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}" \
|
||||
"${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-amd64" \
|
||||
"${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-arm64"
|
||||
|
||||
docker-readme:
|
||||
if: false
|
||||
name: docker-readme (${{ matrix.repo }})
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
needs: [determine-release-type, docker-manifest]
|
||||
strategy:
|
||||
matrix:
|
||||
repo: ${{ fromJSON(needs.determine-release-type.outputs.docker_repos) }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: peter-evans/dockerhub-description@1b9a80c056b620d92cedb9d9b5a223409c68ddfa # v5.0.0
|
||||
with:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
repository: ${{ matrix.repo }}
|
||||
readme-filepath: ocis/README.md
|
||||
|
||||
build-binaries:
|
||||
name: build-binaries (${{ matrix.os }})
|
||||
runs-on: ubuntu-latest
|
||||
@@ -291,7 +120,7 @@ jobs:
|
||||
os: [linux, darwin]
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: generated-code
|
||||
path: .
|
||||
@@ -304,7 +133,7 @@ jobs:
|
||||
if [[ "${{ matrix.os }}" == "linux" ]]; then
|
||||
cp assets/End-User-License-Agreement-for-ownCloud-Infinite-Scale.pdf ocis/dist/release/
|
||||
fi
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: binaries-${{ matrix.os }}
|
||||
path: ocis/dist/release/*
|
||||
@@ -329,11 +158,11 @@ jobs:
|
||||
needs: [determine-release-type, generate-code]
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: generated-code
|
||||
path: .
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
@@ -347,7 +176,7 @@ jobs:
|
||||
- run: make ci-node-check-licenses && make ci-node-save-licenses
|
||||
- run: make ci-go-check-licenses && make ci-go-save-licenses
|
||||
- run: tar -czf third-party-licenses.tar.gz -C third-party-licenses .
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: third-party-licenses
|
||||
path: third-party-licenses.tar.gz
|
||||
@@ -371,7 +200,7 @@ jobs:
|
||||
if [[ $(wc -l < ocis/dist/CHANGELOG.md) -lt 5 ]]; then
|
||||
echo "Development release — no release notes yet. See [unreleased changes](https://github.com/owncloud/ocis/tree/master/changelog/unreleased/)." > ocis/dist/CHANGELOG.md
|
||||
fi
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: changelog
|
||||
path: ocis/dist/CHANGELOG.md
|
||||
@@ -382,19 +211,19 @@ jobs:
|
||||
timeout-minutes: 30
|
||||
needs: [determine-release-type, build-binaries, license-check, generate-changelog, security-scan-trivy]
|
||||
steps:
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: binaries-linux
|
||||
path: release-assets
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: binaries-darwin
|
||||
path: release-assets
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: third-party-licenses
|
||||
path: release-assets
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: changelog
|
||||
path: .
|
||||
@@ -419,15 +248,15 @@ jobs:
|
||||
- create-github-release
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: binaries-linux
|
||||
path: release-assets
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: binaries-darwin
|
||||
path: release-assets
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: third-party-licenses
|
||||
path: release-assets
|
||||
|
||||
@@ -77,7 +77,7 @@ jobs:
|
||||
version: 10.33.3
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: 24.15.0
|
||||
cache: pnpm
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
Bugfix: Show image preview for files with spaces in the name on public links
|
||||
|
||||
The preview in the details panel was not shown for files opened via a public
|
||||
link when the file name contained spaces. The preview URL was used unquoted in a
|
||||
CSS `url()`, so the browser dropped it and never requested the thumbnail. The
|
||||
URL is now quoted.
|
||||
|
||||
https://github.com/owncloud/ocis/issues/13137
|
||||
https://github.com/owncloud/ocis/pull/13150
|
||||
@@ -0,0 +1,10 @@
|
||||
Bugfix: Disable rubber-band overscroll of the page in file apps
|
||||
|
||||
Scrolling to the top or bottom of the content in a file app such as
|
||||
OnlyOffice, Collabora or the text editor could make the whole page bounce
|
||||
along with it, including the top bar and the app frame, briefly revealing the
|
||||
blank page background behind them. The vertical elastic overscroll of the page
|
||||
is now disabled while a file is open in one of these apps, so the surrounding
|
||||
layout stays in place.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13140
|
||||
@@ -0,0 +1,11 @@
|
||||
Bugfix: Files no longer stay in processing after upload or copy
|
||||
|
||||
After uploading or copying files, some of them sometimes stayed greyed out as
|
||||
"processing" until the page was reloaded. This happened when processing
|
||||
finished while the file list was still being loaded: the update from the
|
||||
server was ignored and the list then showed the file as still processing.
|
||||
|
||||
Files whose processing has finished are now refreshed automatically when they
|
||||
show up in the file list as processing.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13134
|
||||
@@ -0,0 +1,10 @@
|
||||
Bugfix: Clean up the trash view in the Safe
|
||||
|
||||
The trash offered a "Copy permanent link" action for deleted items, which
|
||||
cannot be linked to. The action is no longer shown for deleted items.
|
||||
|
||||
The personal space in the trash was labelled "Personal" in the Safe, while the
|
||||
rest of the interface calls it "Safe-Personal". The trash now uses the same
|
||||
name.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13136
|
||||
@@ -0,0 +1,8 @@
|
||||
Bugfix: Show correct message when Safe access is denied for lacking permission
|
||||
|
||||
A user without permission to use the Safe who opened the Safe URL directly was
|
||||
shown "Not logged in" with a "Log in again" button, even though they were
|
||||
still logged in. The page now shows "Access denied" with a "Continue" button
|
||||
that returns to the app for this case.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13111
|
||||
@@ -23,9 +23,9 @@ require (
|
||||
github.com/gabriel-vasile/mimetype v1.4.15
|
||||
github.com/ggwhite/go-masker v1.1.0
|
||||
github.com/go-chi/chi/v5 v5.3.2
|
||||
github.com/go-chi/httprate v0.16.0
|
||||
github.com/go-chi/httprate v0.16.1
|
||||
github.com/go-chi/render v1.0.3
|
||||
github.com/go-ldap/ldap/v3 v3.4.14
|
||||
github.com/go-ldap/ldap/v3 v3.4.15
|
||||
github.com/go-ldap/ldif v0.0.0-20200320164324-fd88d9b715b3
|
||||
github.com/go-micro/plugins/v4/client/grpc v1.2.1
|
||||
github.com/go-micro/plugins/v4/logger/zerolog v1.2.0
|
||||
@@ -58,7 +58,7 @@ require (
|
||||
github.com/mitchellh/mapstructure v1.5.0
|
||||
github.com/mna/pigeon v1.3.0
|
||||
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826
|
||||
github.com/nats-io/nats-server/v2 v2.15.0
|
||||
github.com/nats-io/nats-server/v2 v2.15.1
|
||||
github.com/nats-io/nats.go v1.54.0
|
||||
github.com/olekukonko/tablewriter v1.1.5
|
||||
github.com/onsi/ginkgo v1.16.5
|
||||
@@ -70,7 +70,7 @@ require (
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261012083840-8b649a4c3899
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/pkg/xattr v0.4.12
|
||||
github.com/prometheus/client_golang v1.24.1
|
||||
github.com/prometheus/client_golang v1.25.0
|
||||
github.com/r3labs/sse/v2 v2.10.0
|
||||
github.com/rogpeppe/go-internal v1.16.0
|
||||
github.com/rs/cors v1.11.1
|
||||
@@ -82,7 +82,7 @@ require (
|
||||
github.com/stretchr/testify v1.12.1
|
||||
github.com/test-go/testify v1.1.4
|
||||
github.com/thejerf/suture/v4 v4.0.6
|
||||
github.com/tidwall/gjson v1.19.1
|
||||
github.com/tidwall/gjson v1.20.0
|
||||
github.com/tus/tusd/v2 v2.10.1
|
||||
github.com/unrolled/secure v1.17.0
|
||||
github.com/urfave/cli/v2 v2.27.7
|
||||
@@ -90,7 +90,7 @@ require (
|
||||
go-micro.dev/v4 v4.11.0
|
||||
go.etcd.io/bbolt v1.5.0
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0
|
||||
go.opentelemetry.io/contrib/zpages v0.72.0
|
||||
go.opentelemetry.io/otel v1.47.0
|
||||
go.opentelemetry.io/otel/exporters/jaeger v1.17.0
|
||||
@@ -102,7 +102,7 @@ require (
|
||||
golang.org/x/image v0.46.0
|
||||
golang.org/x/net v0.60.0
|
||||
golang.org/x/oauth2 v0.37.0
|
||||
golang.org/x/sync v0.23.0
|
||||
golang.org/x/sync v0.24.0
|
||||
golang.org/x/term v0.46.0
|
||||
golang.org/x/text v0.42.0
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc
|
||||
@@ -238,7 +238,7 @@ require (
|
||||
github.com/json-iterator/go v1.1.13-0.20220915233716-71ac16282d12 // indirect
|
||||
github.com/juliangruber/go-intersect v1.1.0 // indirect
|
||||
github.com/kevinburke/ssh_config v1.2.0 // indirect
|
||||
github.com/klauspost/compress v1.20.0 // indirect
|
||||
github.com/klauspost/compress v1.20.1 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
|
||||
github.com/klauspost/crc32 v1.3.0 // indirect
|
||||
github.com/kovidgoyal/go-parallel v1.1.1 // indirect
|
||||
@@ -292,8 +292,8 @@ require (
|
||||
github.com/pquerna/cachecontrol v0.2.0 // indirect
|
||||
github.com/prometheus/alertmanager v0.34.1 // indirect
|
||||
github.com/prometheus/client_model v0.6.3 // indirect
|
||||
github.com/prometheus/common v0.70.1 // indirect
|
||||
github.com/prometheus/procfs v0.21.1 // indirect
|
||||
github.com/prometheus/common v0.72.0 // indirect
|
||||
github.com/prometheus/procfs v0.22.0 // indirect
|
||||
github.com/prometheus/statsd_exporter v0.22.8 // indirect
|
||||
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
|
||||
@@ -288,8 +288,8 @@ github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoM
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
|
||||
github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||
github.com/go-chi/httprate v0.16.0 h1:8V5DH9j6pSK6UQoBsTpvMyFxycqaKEIToyPKzHJjUa8=
|
||||
github.com/go-chi/httprate v0.16.0/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
|
||||
github.com/go-chi/httprate v0.16.1 h1:q2M8FmDsI4oEr1oRX43N+VeA0Ujd1tb/EasrSzXy87o=
|
||||
github.com/go-chi/httprate v0.16.1/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
|
||||
github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
|
||||
github.com/go-chi/render v1.0.3/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0=
|
||||
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI=
|
||||
@@ -315,8 +315,8 @@ github.com/go-kit/log v0.2.0/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBj
|
||||
github.com/go-kit/log v0.2.1 h1:MRVx0/zhvdseW+Gza6N9rVzU/IVzaeE1SFI4raAhmBU=
|
||||
github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0=
|
||||
github.com/go-ldap/ldap/v3 v3.1.7/go.mod h1:5Zun81jBTabRaI8lzN7E1JjyEl1g6zI6u9pd8luAK4Q=
|
||||
github.com/go-ldap/ldap/v3 v3.4.14 h1:D6PYdEgsaVzsXyr6w/yDC06Ria4uUhWm+Rb+er8lfAs=
|
||||
github.com/go-ldap/ldap/v3 v3.4.14/go.mod h1:S4eJUMUNjDkE0ZJtIZdybwyb03sGGLW6gxXT1Hs8VKA=
|
||||
github.com/go-ldap/ldap/v3 v3.4.15 h1:eRB4f4Ecn1POL1mO86+uUDlecmyWsdiJwh60bAUS4UY=
|
||||
github.com/go-ldap/ldap/v3 v3.4.15/go.mod h1:jeD0c98EdZQCKKKKe4kTWs5aCf6y+j8KuYsYLznZSQk=
|
||||
github.com/go-ldap/ldif v0.0.0-20200320164324-fd88d9b715b3 h1:sfz1YppV05y4sYaW7kXZtrocU/+vimnIWt4cxAYh7+o=
|
||||
github.com/go-ldap/ldif v0.0.0-20200320164324-fd88d9b715b3/go.mod h1:ZXFhGda43Z2TVbfGZefXyMJzsDHhCh0go3bZUcwTx7o=
|
||||
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
|
||||
@@ -573,8 +573,8 @@ github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4
|
||||
github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
|
||||
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/klauspost/compress v1.20.0 h1:a3C1ke2ohxFymNlb2HWAHjDeKCI90scRskErZkR0ezA=
|
||||
github.com/klauspost/compress v1.20.0/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
|
||||
github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
@@ -696,8 +696,8 @@ github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRW
|
||||
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
||||
github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc=
|
||||
github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc=
|
||||
github.com/nats-io/nats-server/v2 v2.15.0 h1:M99yf0y05rTr46/qc/Is6ZAowI58Ryp2SjufLCUeVJc=
|
||||
github.com/nats-io/nats-server/v2 v2.15.0/go.mod h1:5qLF4CDGzZVFt//3fUrY1ePpwbi05r7QHPNroSUtolk=
|
||||
github.com/nats-io/nats-server/v2 v2.15.1 h1:fK3AeYFIji1Smng60jB0hVoAPZezA/UzsaI3BqXFNEI=
|
||||
github.com/nats-io/nats-server/v2 v2.15.1/go.mod h1:yeuYRtKVKIFtmMz2/YPk+6hvmNBnk+WwTUzErBdH6IE=
|
||||
github.com/nats-io/nats.go v1.54.0 h1:vsXoOxjHp/GmPUN+EcI7uOf/uB+iAP+kEsAFNQN0yzA=
|
||||
github.com/nats-io/nats.go v1.54.0/go.mod h1:y+DZoD1oBOYfZTU681eTUiUjI0vbqYGixNVFHcjHJ0k=
|
||||
github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg=
|
||||
@@ -777,8 +777,8 @@ github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqr
|
||||
github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY=
|
||||
github.com/prometheus/client_golang v1.12.2/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY=
|
||||
github.com/prometheus/client_golang v1.13.0/go.mod h1:vTeo+zgvILHsnnj/39Ou/1fPN5nJFOEMgftOUOmlvYQ=
|
||||
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
|
||||
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
|
||||
github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
|
||||
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
|
||||
github.com/prometheus/client_model v0.0.0-20170216185247-6f3806018612/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
||||
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
||||
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
@@ -793,8 +793,8 @@ github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9
|
||||
github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls=
|
||||
github.com/prometheus/common v0.35.0/go.mod h1:phzohg0JFMnBEFGxTDbfu3QyL5GI8gTQJFhYO5B3mfA=
|
||||
github.com/prometheus/common v0.37.0/go.mod h1:phzohg0JFMnBEFGxTDbfu3QyL5GI8gTQJFhYO5B3mfA=
|
||||
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
|
||||
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
|
||||
github.com/prometheus/common v0.72.0 h1:tAYsE+sPJxIncDAobm4H5aQjmox9ZxEIIqPbiffa8G4=
|
||||
github.com/prometheus/common v0.72.0/go.mod h1:77NWqAQ2tXT7BIK40qjJdw5Acrsrg1TlHAnsQi3i6mk=
|
||||
github.com/prometheus/procfs v0.0.0-20170703101242-e645f4e5aaa8/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
||||
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
||||
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
|
||||
@@ -802,8 +802,8 @@ github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4O
|
||||
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
|
||||
github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
|
||||
github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0uaxHdg830/4=
|
||||
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
|
||||
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
|
||||
github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics=
|
||||
github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58=
|
||||
github.com/prometheus/statsd_exporter v0.22.7/go.mod h1:N/TevpjkIh9ccs6nuzY3jQn9dFqnUakOjnEuMPJJJnI=
|
||||
github.com/prometheus/statsd_exporter v0.22.8 h1:Qo2D9ZzaQG+id9i5NYNGmbf1aa/KxKbB9aKfMS+Yib0=
|
||||
github.com/prometheus/statsd_exporter v0.22.8/go.mod h1:/DzwbTEaFTE0Ojz5PqcSk6+PFHOPWGxdXVr6yC8eFOM=
|
||||
@@ -891,8 +891,8 @@ github.com/thanhpk/randstr v1.0.6 h1:psAOktJFD4vV9NEVb3qkhRSMvYh4ORRaj1+w/hn4B+o
|
||||
github.com/thanhpk/randstr v1.0.6/go.mod h1:M/H2P1eNLZzlDwAzpkkkUvoyNNMbzRGhESZuEQk3r0U=
|
||||
github.com/thejerf/suture/v4 v4.0.6 h1:QsuCEsCqb03xF9tPAsWAj8QOAJBgQI1c0VqJNaingg8=
|
||||
github.com/thejerf/suture/v4 v4.0.6/go.mod h1:gu9Y4dXNUWFrByqRt30Rm9/UZ0wzRSt9AJS6xu/ZGxU=
|
||||
github.com/tidwall/gjson v1.19.1 h1:uKxUTe/+mtjSY3Sf1EIND83MyH+jWf1SixZ7DHpjbJU=
|
||||
github.com/tidwall/gjson v1.19.1/go.mod h1:V37/opeE/JbLUOfH0QTXiNez2l0RUjYUhpT4szFQAfc=
|
||||
github.com/tidwall/gjson v1.20.0 h1:+agJ3rEzKcCXKDKo0ml26UROcpcAlnZyjq+TjbY5Fto=
|
||||
github.com/tidwall/gjson v1.20.0/go.mod h1:V37/opeE/JbLUOfH0QTXiNez2l0RUjYUhpT4szFQAfc=
|
||||
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
||||
@@ -968,8 +968,8 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0 h1:Tq+E65HaNbZTeqcLw6QUhsV+/EIWdkfUH2CQzcrlE5M=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0/go.mod h1:A+EVhDakAj1waJBPhmTszZaSr08ww8MRRKy1nB1rqck=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
|
||||
go.opentelemetry.io/contrib/zpages v0.72.0 h1:aXBUaFvbF7xy77q6vXBvaw7dcZK0zUqJSF5UhtbbuZ4=
|
||||
go.opentelemetry.io/contrib/zpages v0.72.0/go.mod h1:e/qIKK0RHtY2dvkJhp1jtjVvglq/IDzMI7gDN8mMMtY=
|
||||
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
|
||||
@@ -1127,8 +1127,8 @@ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJ
|
||||
golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
|
||||
@@ -274,6 +274,14 @@ func DefaultPolicies() []config.Policy {
|
||||
Endpoint: "/graph/",
|
||||
Service: "com.owncloud.web.graph",
|
||||
},
|
||||
{
|
||||
Endpoint: "/vault/graph/v1beta1/extensions/org.libregraph/activities",
|
||||
Service: "com.owncloud.web.activitylog",
|
||||
},
|
||||
{
|
||||
Endpoint: "/vault/graph/v1.0/invitations",
|
||||
Service: "com.owncloud.web.invitations",
|
||||
},
|
||||
{
|
||||
Endpoint: "/vault/graph/",
|
||||
Service: "com.owncloud.web.graph",
|
||||
|
||||
@@ -165,3 +165,34 @@ func TestRouter(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Vault /graph/ sub-routes must reach the same service as their non-vault counterpart.
|
||||
func TestRouterVaultGraphSubRoutes(t *testing.T) {
|
||||
cfg := defaults.DefaultConfig()
|
||||
cfg.Policies = defaults.DefaultPolicies()
|
||||
|
||||
reg := registry.GetRegistry()
|
||||
sel := selector.NewSelector(selector.Registry(reg))
|
||||
router := New(sel, cfg.PolicySelector, cfg.Policies, log.NewLogger())
|
||||
|
||||
// Each path must match its own route, not a catch-all.
|
||||
paths := []string{
|
||||
"/graph/v1beta1/extensions/org.libregraph/activities",
|
||||
"/vault/graph/v1beta1/extensions/org.libregraph/activities",
|
||||
"/graph/v1.0/invitations",
|
||||
"/vault/graph/v1.0/invitations",
|
||||
}
|
||||
|
||||
for _, path := range paths {
|
||||
r := httptest.NewRequest("GET", path, nil)
|
||||
ri, ok := router.Route(r)
|
||||
if !ok {
|
||||
t.Errorf("router.Route failed to route %s", path)
|
||||
continue
|
||||
}
|
||||
|
||||
if ri.endpoint != path {
|
||||
t.Errorf("%s matched endpoint %q, want %q — got routed to the generic graph catch-all instead", path, ri.endpoint, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1093,6 +1093,20 @@ class CliContext implements Context {
|
||||
$this->featureContext->setResponse(CliHelper::runCommand($body));
|
||||
}
|
||||
|
||||
/**
|
||||
* @When the administrator resumes all the upload session using the post processing command
|
||||
*
|
||||
* @return void
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function theAdministratorResumesAllUploadSessionUsingPostprocessingCommand(): void {
|
||||
$command = "postprocessing resume";
|
||||
$body = [
|
||||
"command" => $command,
|
||||
];
|
||||
$this->featureContext->setResponse(CliHelper::runCommand($body));
|
||||
}
|
||||
|
||||
/**
|
||||
* @When the administrator restarts the expired upload sessions using the CLI
|
||||
*
|
||||
|
||||
@@ -247,3 +247,27 @@ Feature: List upload sessions via CLI command
|
||||
When the administrator waits for "3" seconds
|
||||
Then for user "Alice" file "file2.txt" of space "Personal" should be in postprocessing
|
||||
And the content of file "file1.txt" for user "Alice" should be "uploaded content"
|
||||
|
||||
|
||||
Scenario: resume all upload where postprocessing is finished, but not for unfinished upload using postprocessing command
|
||||
Given the config "POSTPROCESSING_DELAY" has been set to "3s"
|
||||
And user "Alice" has created a new TUS resource in the space "Personal" with the following headers:
|
||||
| Upload-Length | 10 |
|
||||
# dGV4dEZpbGUudHh0 is the base64 encode of textFile.txt
|
||||
| Upload-Metadata | filename dGV4dEZpbGUudHh0 |
|
||||
| Tus-Resumable | 1.0.0 |
|
||||
And user "Alice" has uploaded file with checksum "SHA1 8cb2237d0679ca88db6464eac60da96345513964" to the last created TUS Location with offset "0" and content "12345" via TUS inside of the space "Personal" using the WebDAV API
|
||||
And user "Alice" has uploaded file with content "uploaded content" to "file.txt"
|
||||
And the administrator has waited for "1" seconds
|
||||
And the administrator has stopped the server
|
||||
And the administrator has started the server
|
||||
When the administrator resumes all the upload session using the post processing command
|
||||
Then the command should be successful
|
||||
When the administrator waits for "3" seconds
|
||||
Then the content of file "file.txt" for user "Alice" should be "uploaded content"
|
||||
When the administrator lists all the upload sessions
|
||||
Then the command should be successful
|
||||
And the CLI response should contain these entries:
|
||||
| textFile.txt |
|
||||
And the CLI response should not contain these entries:
|
||||
| file.txt |
|
||||
@@ -74,6 +74,7 @@ if [[ "$ENABLE_WOPI" == "true" ]]; then
|
||||
-e 's/{{- include "ocis.extraVolMounts" \. | nindent 12 }}/{{- include "ocis.extraVolMounts" $ | nindent 12 }}/' \
|
||||
-e 's/{{- include "ocis.extraVolumes" \. | nindent 8 }}/{{- include "ocis.extraVolumes" $ | nindent 8 }}/' \
|
||||
$TPL_DIR/collaboration/deployment.yaml
|
||||
sed -i "s|availableUnifiedRoles: \[\]|availableUnifiedRoles: ['b1e2218d-eef8-4d4c-b82d-0f1a1b48f3b5','a8d5fe5e-96e3-418d-825b-534dbdf22b99','fb6c3e19-e378-47e5-b277-9732f9de6e21','58c63c02-1d89-4572-916a-870abc5a1b7d','2d00ce52-1fc2-4dbc-8b95-a73b73395f5a','1c996275-f1c9-4e71-abdf-a42f6495e960','312c0871-5ef7-4b3a-85b6-0e4074c64049','aa97fe03-7980-45ac-9e50-b325749fd7e6']|" $CFG_DIR/values.yaml
|
||||
fi
|
||||
|
||||
if [[ "$ENABLE_OCM" == "true" ]]; then
|
||||
@@ -86,6 +87,7 @@ fi
|
||||
|
||||
if [[ "$ENABLE_VAULT" == "true" ]]; then
|
||||
sed -i '/vault:/{n;s|false|true|}' $CFG_DIR/values.yaml
|
||||
sed -i '/mfa:/{n;s|false|true|}' $CFG_DIR/values.yaml
|
||||
# baking keycloak url into the base CSP would affect every other suite that
|
||||
# shares this same values.yaml, breaking their fixed CSP header assertions.
|
||||
sed -i "/defaultSrc:/i\\ - 'https://keycloak:8443/'" $CFG_DIR/values.yaml
|
||||
|
||||
@@ -137,13 +137,10 @@
|
||||
- name: IDM_CREATE_DEMO_USERS
|
||||
value: "false"
|
||||
{{- end -}}
|
||||
{{- if eq .appName "storageusers-vault" }}
|
||||
- name: STORAGE_USERS_ENABLE_VAULT_MODE
|
||||
value: "true"
|
||||
- name: STORAGE_USERS_SERVICE_NAME
|
||||
value: storage-users-vault
|
||||
- name: STORAGE_USERS_EVENTS_CONSUMER_GROUP
|
||||
value: vault-dcfs
|
||||
{{- if eq .appName "storageusersvault" }}
|
||||
{{/* ocis-charts added native support for this service upstream (appName "storageusersvault").
|
||||
The native deployment.yaml already sets STORAGE_USERS_ENABLE_VAULT_MODE,
|
||||
STORAGE_USERS_SERVICE_NAME and STORAGE_USERS_EVENTS_CONSUMER_GROUP itself. */}}
|
||||
{{/* Without these overrides this instance falls back to the shared OCIS_CACHE_STORE=nats-js-kv
|
||||
used by the regular storage-users service. Since personal-space IDs are just the user's
|
||||
opaque ID (identical in both instances), the vault instance's existence check on
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
{{- if .Values.features.vault.enabled }}
|
||||
{{- include "ocis.basicServiceTemplates" (dict "scope" . "appName" "appNameStorageUsers" "appNameSuffix" "vault") -}}
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
{{ include "ocis.metadata" . }}
|
||||
spec:
|
||||
{{- include "ocis.selector" . | nindent 2 }}
|
||||
{{- if and (not .Values.autoscaling.enabled) (.Values.replicas) }}
|
||||
replicas: {{ .Values.replicas }}
|
||||
{{- end }}
|
||||
{{- include "ocis.deploymentStrategy" . | nindent 2 }}
|
||||
template:
|
||||
{{- include "ocis.templateMetadata" (dict "scope" $ "configCheck" false) | nindent 4 }}
|
||||
spec:
|
||||
{{- include "ocis.affinity" $ | nindent 6 }}
|
||||
{{- include "ocis.securityContextAndtopologySpreadConstraints" . | nindent 6 }}
|
||||
{{- include "ocis.priorityClassName" $.priorityClassName | nindent 6 }}
|
||||
{{- include "ocis.hostAliases" $ | nindent 6 }}
|
||||
nodeSelector: {{ toYaml $.nodeSelector | nindent 8 }}
|
||||
containers:
|
||||
- name: {{ .appName }}
|
||||
{{- include "ocis.image" $ | nindent 10 }}
|
||||
command: ["ocis"]
|
||||
args: ["storage-users", "server"]
|
||||
{{- include "ocis.containerSecurityContext" . | nindent 10 }}
|
||||
env:
|
||||
{{- include "ocis.serviceRegistry" . | nindent 12 }}
|
||||
{{- include "ocis.events" . | nindent 12 }}
|
||||
{{- include "ocis.cacheStore" . | nindent 12 }}
|
||||
{{- include "ocis.cors" . | nindent 12 }}
|
||||
|
||||
# this is a secondary storage-users instance, dedicated to vault storage
|
||||
# see tests/config/k8s/templates/extra.tpl for STORAGE_USERS_ENABLE_VAULT_MODE
|
||||
# and STORAGE_USERS_SERVICE_NAME
|
||||
|
||||
- name: STORAGE_USERS_GATEWAY_GRPC_ADDR
|
||||
value: {{ .appNameGateway }}:9142
|
||||
|
||||
- name: STORAGE_USERS_LOG_COLOR
|
||||
value: {{ .Values.logging.color | quote }}
|
||||
- name: STORAGE_USERS_LOG_LEVEL
|
||||
value: {{ .Values.logging.level | quote }}
|
||||
- name: STORAGE_USERS_LOG_PRETTY
|
||||
value: {{ .Values.logging.pretty | quote }}
|
||||
|
||||
- name: STORAGE_USERS_TRACING_ENABLED
|
||||
value: "{{ .Values.tracing.enabled }}"
|
||||
- name: STORAGE_USERS_TRACING_TYPE
|
||||
value: {{ .Values.tracing.type | quote }}
|
||||
- name: STORAGE_USERS_TRACING_ENDPOINT
|
||||
value: {{ .Values.tracing.endpoint | quote }}
|
||||
- name: STORAGE_USERS_TRACING_COLLECTOR
|
||||
value: {{ .Values.tracing.collector | quote }}
|
||||
|
||||
- name: STORAGE_USERS_DEBUG_PPROF
|
||||
value: {{ .Values.debug.profiling | quote }}
|
||||
|
||||
- name: STORAGE_USERS_GRPC_ADDR
|
||||
value: 0.0.0.0:9157
|
||||
- name: STORAGE_USERS_DEBUG_ADDR
|
||||
value: 0.0.0.0:9159
|
||||
|
||||
- name: STORAGE_USERS_HTTP_ADDR
|
||||
value: 0.0.0.0:9158
|
||||
- name: STORAGE_USERS_DATA_SERVER_URL
|
||||
value: "http://{{ .appName }}:9158/data"
|
||||
|
||||
- name: STORAGE_USERS_DRIVER
|
||||
value: ocis
|
||||
- name: STORAGE_USERS_OCIS_MAX_CONCURRENCY
|
||||
value: {{ .Values.services.storageusers.storageBackend.driverConfig.ocis.maxConcurrency | quote }}
|
||||
|
||||
- name: STORAGE_USERS_UPLOAD_EXPIRATION
|
||||
value: {{ .Values.services.storageusers.maintenance.cleanUpExpiredUploads.uploadExpiration | quote }}
|
||||
|
||||
- name: STORAGE_USERS_PURGE_TRASH_BIN_PERSONAL_DELETE_BEFORE
|
||||
value: {{ .Values.services.storageusers.maintenance.purgeExpiredTrashBinItems.personalDeleteBefore | quote}}
|
||||
- name: STORAGE_USERS_PURGE_TRASH_BIN_PROJECT_DELETE_BEFORE
|
||||
value: {{ .Values.services.storageusers.maintenance.purgeExpiredTrashBinItems.projectDeleteBefore | quote }}
|
||||
|
||||
- name: STORAGE_USERS_SERVICE_ACCOUNT_ID
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "config.authService" . }}
|
||||
key: service-account-id
|
||||
- name: STORAGE_USERS_SERVICE_ACCOUNT_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "secrets.serviceAccountSecret" . }}
|
||||
key: service-account-secret
|
||||
|
||||
- name: STORAGE_USERS_STAT_CACHE_STORE
|
||||
value: noop
|
||||
|
||||
- name: STORAGE_USERS_MOUNT_ID
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "config.storageUsers" . }}
|
||||
key: storage-uuid
|
||||
|
||||
- name: STORAGE_USERS_JWT_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "secrets.jwtSecret" . }}
|
||||
key: jwt-secret
|
||||
|
||||
- name: OCIS_TRANSFER_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "secrets.transferSecret" . }}
|
||||
key: transfer-secret
|
||||
|
||||
- name: OCIS_ASYNC_UPLOADS
|
||||
value: "true"
|
||||
- name: STORAGE_USERS_EVENTS_NUM_CONSUMERS
|
||||
value: {{ .Values.services.storageusers.events.consumer.concurrency | quote }}
|
||||
|
||||
- name: STORAGE_USERS_DATA_GATEWAY_URL
|
||||
value: "http://{{ .appNameFrontend }}:9140/data/"
|
||||
|
||||
{{- include "ocis.caEnv" $ | nindent 12}}
|
||||
{{- include "ocis.extraEnvs" . | nindent 12}}
|
||||
|
||||
{{- include "ocis.livenessProbe" . | nindent 10 }}
|
||||
|
||||
resources: {{ toYaml .resources | nindent 12 }}
|
||||
|
||||
ports:
|
||||
- name: grpc
|
||||
containerPort: 9157
|
||||
- name: http
|
||||
containerPort: 9158
|
||||
- name: metrics-debug
|
||||
containerPort: 9159
|
||||
|
||||
volumeMounts:
|
||||
- name: tmp-volume
|
||||
mountPath: /tmp
|
||||
- name: messaging-system-ca
|
||||
mountPath: /etc/ocis/messaging-system-ca
|
||||
readOnly: true
|
||||
- name: {{ include "ocis.persistence.dataVolumeName" . }}
|
||||
mountPath: /var/lib/ocis
|
||||
{{- include "ocis.caPath" $ | nindent 12}}
|
||||
{{- include "ocis.extraVolMounts" . | nindent 12}}
|
||||
|
||||
{{- include "ocis.imagePullSecrets" $ | nindent 6 }}
|
||||
volumes:
|
||||
- name: tmp-volume
|
||||
emptyDir: {}
|
||||
- name: messaging-system-ca
|
||||
{{ if and (.Values.messagingSystem.external.enabled) (not .Values.messagingSystem.external.tls.certTrusted) }}
|
||||
secret:
|
||||
secretName: {{ include "secrets.messagingSystemCASecret" . }}
|
||||
{{ else }}
|
||||
emptyDir: {}
|
||||
{{ end }}
|
||||
{{- include "ocis.caVolume" $ | nindent 8}}
|
||||
{{- include "ocis.persistence.dataVolume" . | nindent 8 }}
|
||||
{{- include "ocis.extraVolumes" . | nindent 8}}
|
||||
{{- end -}}
|
||||
@@ -1,28 +0,0 @@
|
||||
{{- if .Values.features.vault.enabled }}
|
||||
{{- include "ocis.basicServiceTemplates" (dict "scope" . "appName" "appNameStorageUsers" "appNameSuffix" "vault") -}}
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ .appName }}
|
||||
namespace: {{ template "ocis.namespace" . }}
|
||||
labels:
|
||||
app: {{ .appName }}
|
||||
ocis-metrics: enabled
|
||||
{{- include "ocis.labels" . | nindent 4 }}
|
||||
spec:
|
||||
selector:
|
||||
app: {{ .appName }}
|
||||
ports:
|
||||
- name: grpc
|
||||
port: 9157
|
||||
protocol: TCP
|
||||
appProtocol: {{ .Values.service.appProtocol.grpc | quote}}
|
||||
- name: http
|
||||
port: 9158
|
||||
protocol: TCP
|
||||
appProtocol: {{ .Values.service.appProtocol.http | quote}}
|
||||
- name: metrics-debug
|
||||
port: 9159
|
||||
protocol: TCP
|
||||
appProtocol: {{ .Values.service.appProtocol.http | quote}}
|
||||
{{- end -}}
|
||||
@@ -18,6 +18,8 @@ features:
|
||||
enabled: false
|
||||
vault:
|
||||
enabled: false
|
||||
mfa:
|
||||
enabled: false
|
||||
emailNotifications:
|
||||
enabled: false
|
||||
smtp:
|
||||
@@ -49,21 +51,45 @@ features:
|
||||
max: '0'
|
||||
appsIntegration:
|
||||
enabled: false
|
||||
mimetypes:
|
||||
- mime_type: application/vnd.oasis.opendocument.text
|
||||
extension: odt
|
||||
name: OpenDocument
|
||||
description: OpenDocument text document
|
||||
icon: ""
|
||||
default_app: Collabora
|
||||
allow_creation: true
|
||||
- mime_type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
|
||||
extension: docx
|
||||
name: Microsoft Word
|
||||
description: Microsoft Word document
|
||||
icon: ""
|
||||
default_app: OnlyOffice
|
||||
allow_creation: true
|
||||
- mime_type: text/plain
|
||||
extension: txt
|
||||
name: Plain text
|
||||
description: Plain text file
|
||||
icon: ""
|
||||
default_app: FakeOffice
|
||||
allow_creation: true
|
||||
wopiIntegration:
|
||||
officeSuites:
|
||||
- name: 'Collabora'
|
||||
uri: 'https://collabora:9980'
|
||||
iconURI: 'https://collabora:9980/favicon.ico'
|
||||
wopiSrc: 'http://ocis-server:9300'
|
||||
product: 'Collabora'
|
||||
enabled: true
|
||||
insecure: true
|
||||
disableProof: true
|
||||
secureViewEnabled: false
|
||||
secureViewEnabled: true
|
||||
disableChat: true
|
||||
ingress:
|
||||
enabled: false
|
||||
- name: 'FakeOffice'
|
||||
uri: 'http://fakeoffice:8080'
|
||||
iconURI: 'http://fakeoffice:8080/favicon.ico'
|
||||
wopiSrc: 'http://ocis-server:9301'
|
||||
product: 'FakeOffice'
|
||||
enabled: true
|
||||
@@ -75,6 +101,7 @@ features:
|
||||
enabled: false
|
||||
- name: 'OnlyOffice'
|
||||
uri: 'https://onlyoffice:7443'
|
||||
iconURI: 'https://onlyoffice:7443/web-apps/apps/documenteditor/main/resources/img/favicon.ico'
|
||||
wopiSrc: 'http://ocis-server:9302'
|
||||
product: 'OnlyOffice'
|
||||
enabled: true
|
||||
@@ -84,6 +111,8 @@ features:
|
||||
disableChat: true
|
||||
ingress:
|
||||
enabled: false
|
||||
roles:
|
||||
availableUnifiedRoles: []
|
||||
|
||||
http:
|
||||
cors:
|
||||
@@ -149,7 +178,7 @@ services:
|
||||
enabled: true
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
storageusers-vault:
|
||||
storageusersvault:
|
||||
persistence:
|
||||
enabled: false
|
||||
ocm:
|
||||
|
||||
+5
-1
@@ -50,7 +50,8 @@ func Key(key string) func(r *http.Request) (string, error) {
|
||||
|
||||
// CanonicalizeIP normalizes a client IP string for use as a rate-limit key:
|
||||
//
|
||||
// - IPv4 addresses are returned unchanged.
|
||||
// - IPv4 addresses are returned unchanged. IPv4 mapped IPv6 addresses use
|
||||
// their dotted IPv4 form.
|
||||
// - IPv6 addresses are reduced to their /64 prefix. An IPv6 client typically
|
||||
// controls a whole /64 (2^64 addresses via SLAAC), so keying on the full
|
||||
// address would let it rotate within its own /64 to win a fresh bucket per
|
||||
@@ -94,6 +95,9 @@ func CanonicalizeIP(ip string) string {
|
||||
if ipv6 == nil {
|
||||
return ip
|
||||
}
|
||||
if ipv4 := ipv6.To4(); ipv4 != nil {
|
||||
return ipv4.String()
|
||||
}
|
||||
|
||||
return ipv6.Mask(net.CIDRMask(64, 128)).String()
|
||||
}
|
||||
|
||||
+6
-6
@@ -83,16 +83,16 @@ func (l *Conn) Add(addRequest *AddRequest) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(packet.Children) < 2 {
|
||||
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if packet.Children[1].Tag == ApplicationAddResponse {
|
||||
err := GetLDAPError(packet)
|
||||
if err != nil {
|
||||
if protocolOp.Tag == ApplicationAddResponse {
|
||||
if err := GetLDAPError(packet); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("ldap: unexpected response: %d", packet.Children[1].Tag)
|
||||
return fmt.Errorf("ldap: unexpected response: %d", protocolOp.Tag)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+125
-68
@@ -6,15 +6,15 @@ import (
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
enchex "encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"io"
|
||||
"strings"
|
||||
"unicode/utf16"
|
||||
|
||||
"github.com/Azure/go-ntlmssp"
|
||||
ber "github.com/go-asn1-ber/asn1-ber"
|
||||
//lint:ignore SA1019 NTLM requires MD4; there is no secure replacement for the protocol.
|
||||
"golang.org/x/crypto/md4" //nolint:staticcheck
|
||||
)
|
||||
|
||||
@@ -77,15 +77,26 @@ func (l *Conn) SimpleBind(simpleBindRequest *SimpleBindRequest) (*SimpleBindResu
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return decodeSimpleBindResult(packet)
|
||||
}
|
||||
|
||||
// decodeSimpleBindResult decodes a bind response envelope, including any
|
||||
// response controls. It is separated from the network loop so the full
|
||||
// response decoder can be fuzzed directly.
|
||||
func decodeSimpleBindResult(packet *ber.Packet) (*SimpleBindResult, error) {
|
||||
result := &SimpleBindResult{
|
||||
Controls: make([]Control, 0),
|
||||
}
|
||||
|
||||
if len(packet.Children) == 3 {
|
||||
for _, child := range packet.Children[2].Children {
|
||||
controls, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ok {
|
||||
for _, child := range controls.Children {
|
||||
decodedChild, decodeErr := DecodeControl(child)
|
||||
if decodeErr != nil {
|
||||
return nil, fmt.Errorf("failed to decode child control: %s", decodeErr)
|
||||
return nil, fmt.Errorf("failed to decode child control: %w", decodeErr)
|
||||
}
|
||||
result.Controls = append(result.Controls, decodedChild)
|
||||
}
|
||||
@@ -196,26 +207,35 @@ func (l *Conn) DigestMD5Bind(digestMD5BindRequest *DigestMD5BindRequest) (*Diges
|
||||
Controls: make([]Control, 0),
|
||||
}
|
||||
var params map[string]string
|
||||
if len(packet.Children) == 2 {
|
||||
if len(packet.Children[1].Children) == 4 {
|
||||
child := packet.Children[1].Children[0]
|
||||
if child.Tag != ber.TagEnumerated {
|
||||
_, hasControls, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !hasControls {
|
||||
challenge, perr := packetChild(packet, 1)
|
||||
if perr == nil {
|
||||
challengeChild, hasChallengeChild, cerr := packetChildIfPresent(challenge, 3)
|
||||
if cerr != nil {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
if child.Value.(int64) != 14 {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
child = packet.Children[1].Children[3]
|
||||
if child.Tag != ber.TagObjectDescriptor {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
if child.Data == nil {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
data, _ := ioutil.ReadAll(child.Data)
|
||||
params, err = parseParams(string(data))
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("parsing digest-challenge: %s", err)
|
||||
if hasChallengeChild {
|
||||
child, perr := packetChild(challenge, 0)
|
||||
if perr != nil || child.Tag != ber.TagEnumerated {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
code, perr := packetInt64(child)
|
||||
if perr != nil || code != 14 {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
child = challengeChild
|
||||
if child.Tag != ber.TagObjectDescriptor || child.Data == nil {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
data, _ := io.ReadAll(child.Data)
|
||||
params, err = parseParams(string(data))
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("parsing digest-challenge: %s", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -257,30 +277,45 @@ func (l *Conn) DigestMD5Bind(digestMD5BindRequest *DigestMD5BindRequest) (*Diges
|
||||
return nil, fmt.Errorf("read packet: %s", err)
|
||||
}
|
||||
|
||||
if len(packet.Children) == 2 {
|
||||
response := packet.Children[1]
|
||||
if response == nil {
|
||||
_, hasControls, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !hasControls {
|
||||
response, rerr := packetChild(packet, 1)
|
||||
if rerr != nil {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
if response.ClassType == ber.ClassApplication && response.TagType == ber.TypeConstructed && len(response.Children) >= 3 {
|
||||
if ber.Type(response.Children[0].Tag) == ber.Type(ber.TagInteger) || ber.Type(response.Children[0].Tag) == ber.Type(ber.TagEnumerated) {
|
||||
resultCode := uint16(response.Children[0].Value.(int64))
|
||||
if resultCode == 14 {
|
||||
msgCtx, err := l.doRequest(digestMD5BindRequest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if response.ClassType == ber.ClassApplication && response.TagType == ber.TypeConstructed {
|
||||
if _, rerr := packetChildCount(response, 3, -1, "bind response"); rerr == nil {
|
||||
resultCodeChild, rerr := packetChild(response, 0)
|
||||
if rerr != nil {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
if ber.Type(resultCodeChild.Tag) == ber.Type(ber.TagInteger) || ber.Type(resultCodeChild.Tag) == ber.Type(ber.TagEnumerated) {
|
||||
resultCode, rerr := packetResultCode(resultCodeChild)
|
||||
if rerr != nil {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
defer l.finishMessage(msgCtx)
|
||||
packetResponse, ok := <-msgCtx.responses
|
||||
if !ok {
|
||||
return nil, NewError(ErrorNetwork, errors.New("ldap: response channel closed"))
|
||||
}
|
||||
packet, err = packetResponse.ReadPacket()
|
||||
l.Debug.Printf("%d: got response %p", msgCtx.id, packet)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read packet: %s", err)
|
||||
if resultCode == 14 {
|
||||
msgCtx, err := l.doRequest(digestMD5BindRequest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer l.finishMessage(msgCtx)
|
||||
packetResponse, ok := <-msgCtx.responses
|
||||
if !ok {
|
||||
return nil, NewError(ErrorNetwork, errors.New("ldap: response channel closed"))
|
||||
}
|
||||
packet, err = packetResponse.ReadPacket()
|
||||
l.Debug.Printf("%d: got response %p", msgCtx.id, packet)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read packet: %s", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -373,7 +408,7 @@ func computeResponse(params map[string]string, uri, username, password string) (
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cnonce := enchex.EncodeToString(rb)
|
||||
cnonce := hex.EncodeToString(rb)
|
||||
x := username + ":" + params["realm"] + ":" + password
|
||||
y := md5Hash([]byte(x))
|
||||
|
||||
@@ -384,8 +419,8 @@ func computeResponse(params map[string]string, uri, username, password string) (
|
||||
}
|
||||
a2 := bytes.NewBuffer([]byte("AUTHENTICATE"))
|
||||
a2.WriteString(":" + uri)
|
||||
ha1 := enchex.EncodeToString(md5Hash(a1.Bytes()))
|
||||
ha2 := enchex.EncodeToString(md5Hash(a2.Bytes()))
|
||||
ha1 := hex.EncodeToString(md5Hash(a1.Bytes()))
|
||||
ha2 := hex.EncodeToString(md5Hash(a2.Bytes()))
|
||||
|
||||
kd := ha1
|
||||
kd += ":" + params["nonce"]
|
||||
@@ -393,7 +428,7 @@ func computeResponse(params map[string]string, uri, username, password string) (
|
||||
kd += ":" + cnonce
|
||||
kd += ":" + qop
|
||||
kd += ":" + ha2
|
||||
resp := enchex.EncodeToString(md5Hash([]byte(kd)))
|
||||
resp := hex.EncodeToString(md5Hash([]byte(kd)))
|
||||
return fmt.Sprintf(
|
||||
`username="%s",realm="%s",nonce="%s",cnonce="%s",nc=00000001,qop=%s,digest-uri="%s",response=%s`,
|
||||
quotedStringEscape(username),
|
||||
@@ -502,8 +537,8 @@ func (req *NTLMBindRequest) appendTo(envelope *ber.Packet) (err error) {
|
||||
var negMessage []byte
|
||||
|
||||
// generate an NTLMSSP Negotiation message for the specified domain (it can be blank)
|
||||
switch {
|
||||
case req.Negotiator == nil:
|
||||
switch req.Negotiator {
|
||||
case nil:
|
||||
negMessage, err = ntlmssp.NewNegotiateMessage(req.Domain, "")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create NTLM negotiate message: %s", err)
|
||||
@@ -596,15 +631,29 @@ func (l *Conn) NTLMChallengeBind(ntlmBindRequest *NTLMBindRequest) (*NTLMBindRes
|
||||
var ntlmsspChallenge []byte
|
||||
|
||||
// now find the NTLM Response Message
|
||||
if len(packet.Children) == 2 {
|
||||
if len(packet.Children[1].Children) == 3 {
|
||||
child := packet.Children[1].Children[1]
|
||||
ntlmsspChallenge = child.ByteValue
|
||||
// Check to make sure we got the right message. It will always start with NTLMSSP
|
||||
if len(ntlmsspChallenge) < 7 || !bytes.Equal(ntlmsspChallenge[:7], []byte("NTLMSSP")) {
|
||||
_, hasControls, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !hasControls {
|
||||
protocolOp, perr := packetChild(packet, 1)
|
||||
if perr == nil {
|
||||
protocolOpChildren, cerr := packetChildCount(protocolOp, 3, -1, "bind response")
|
||||
if cerr != nil {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
l.Debug.Printf("%d: found ntlmssp challenge", msgCtx.id)
|
||||
if len(protocolOpChildren) == 3 {
|
||||
child, perr := packetChild(protocolOp, 1)
|
||||
if perr != nil {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
ntlmsspChallenge = child.ByteValue
|
||||
// Check to make sure we got the right message. It will always start with NTLMSSP
|
||||
if len(ntlmsspChallenge) < 7 || !bytes.Equal(ntlmsspChallenge[:7], []byte("NTLMSSP")) {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
l.Debug.Printf("%d: found ntlmssp challenge", msgCtx.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ntlmsspChallenge != nil {
|
||||
@@ -615,11 +664,12 @@ func (l *Conn) NTLMChallengeBind(ntlmBindRequest *NTLMBindRequest) (*NTLMBindRes
|
||||
case ntlmBindRequest.Hash == "" && ntlmBindRequest.Password == "" && !ntlmBindRequest.AllowEmptyPassword:
|
||||
err = fmt.Errorf("need a password or hash to generate reply")
|
||||
case ntlmBindRequest.Negotiator == nil && ntlmBindRequest.Hash != "":
|
||||
responseMessage, err = ntlmssp.ProcessChallengeWithHash(ntlmsspChallenge, ntlmBindRequest.Username, ntlmBindRequest.Hash)
|
||||
responseMessage, err = ntlmssp.NewAuthenticateMessage(ntlmsspChallenge, ntlmBindRequest.Username, ntlmBindRequest.Hash, &ntlmssp.AuthenticateMessageOptions{
|
||||
PasswordHashed: true,
|
||||
})
|
||||
case ntlmBindRequest.Negotiator == nil && (ntlmBindRequest.Password != "" || ntlmBindRequest.AllowEmptyPassword):
|
||||
// generate a response message to the challenge with the given Username/Password if password is provided
|
||||
_, _, domainNeeded := ntlmssp.GetDomain(ntlmBindRequest.Username)
|
||||
responseMessage, err = ntlmssp.ProcessChallenge(ntlmsspChallenge, ntlmBindRequest.Username, ntlmBindRequest.Password, domainNeeded)
|
||||
responseMessage, err = ntlmssp.NewAuthenticateMessage(ntlmsspChallenge, ntlmBindRequest.Username, ntlmBindRequest.Password, nil)
|
||||
default:
|
||||
hash := ntlmBindRequest.Hash
|
||||
if len(hash) == 0 {
|
||||
@@ -739,7 +789,7 @@ func (l *Conn) GSSAPIBindRequest(client GSSAPIClient, req *GSSAPIBindRequest) er
|
||||
return l.GSSAPIBindRequestWithAPOptions(client, req, []int{})
|
||||
}
|
||||
|
||||
// GSSAPIBindRequest performs the GSSAPI SASL bind using the provided GSSAPI client.
|
||||
// GSSAPIBindRequestWithAPOptions performs the GSSAPI SASL bind using the provided GSSAPI client and AP options.
|
||||
func (l *Conn) GSSAPIBindRequestWithAPOptions(client GSSAPIClient, req *GSSAPIBindRequest, APOptions []int) error {
|
||||
//nolint:errcheck
|
||||
defer client.DeleteSecContext()
|
||||
@@ -819,33 +869,40 @@ func (l *Conn) saslBindTokenExchange(reqControls []Control, reqToken []byte) ([]
|
||||
// packet is an envelope
|
||||
// child 0 is message id
|
||||
// child 1 is protocolOp
|
||||
if len(packet.Children) != 2 {
|
||||
if _, err := packetChildCount(packet, 2, 2, "bind response"); err != nil {
|
||||
return nil, fmt.Errorf("bad bind response")
|
||||
}
|
||||
|
||||
protocolOp := packet.Children[1]
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bad bind response")
|
||||
}
|
||||
RESP:
|
||||
switch protocolOp.Description {
|
||||
case "Bind Response": // Bind Response
|
||||
// Bind Reponse is an LDAP Response (https://www.rfc-editor.org/rfc/rfc4511#section-4.1.9)
|
||||
// with an additional optional serverSaslCreds string (https://www.rfc-editor.org/rfc/rfc4511#section-4.2.2)
|
||||
// child 0 is resultCode
|
||||
resultCode := protocolOp.Children[0]
|
||||
if resultCode.Tag != ber.TagEnumerated {
|
||||
resultCode, rcErr := packetChild(protocolOp, 0)
|
||||
if rcErr != nil || resultCode.Tag != ber.TagEnumerated {
|
||||
break RESP
|
||||
}
|
||||
switch resultCode.Value.(int64) {
|
||||
code, rcErr := packetInt64(resultCode)
|
||||
if rcErr != nil {
|
||||
break RESP
|
||||
}
|
||||
switch code {
|
||||
case 14: // Sasl bind in progress
|
||||
if len(protocolOp.Children) < 3 {
|
||||
referral, ok, refErr := packetChildIfPresent(protocolOp, 3)
|
||||
if refErr != nil || !ok {
|
||||
break RESP
|
||||
}
|
||||
referral := protocolOp.Children[3]
|
||||
switch referral.Description {
|
||||
case "Referral":
|
||||
if referral.ClassType != ber.ClassContext || referral.Tag != ber.TagObjectDescriptor {
|
||||
if referral.ClassType != ber.ClassContext || referral.Tag != ber.TagObjectDescriptor || referral.Data == nil {
|
||||
break RESP
|
||||
}
|
||||
return ioutil.ReadAll(referral.Data)
|
||||
return io.ReadAll(referral.Data)
|
||||
}
|
||||
// Optional:
|
||||
//if len(protocolOp.Children) == 4 {
|
||||
|
||||
+5
-4
@@ -46,10 +46,11 @@ func (l *Conn) Compare(dn, attribute, value string) (bool, error) {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if len(packet.Children) < 2 {
|
||||
return false, fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if packet.Children[1].Tag == ApplicationCompareResponse {
|
||||
if protocolOp.Tag == ApplicationCompareResponse {
|
||||
err := GetLDAPError(packet)
|
||||
|
||||
switch {
|
||||
@@ -61,5 +62,5 @@ func (l *Conn) Compare(dn, attribute, value string) (bool, error) {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
return false, fmt.Errorf("unexpected Response: %d", packet.Children[1].Tag)
|
||||
return false, fmt.Errorf("unexpected Response: %d", protocolOp.Tag)
|
||||
}
|
||||
+12
-5
@@ -204,7 +204,7 @@ func (dc *DialContext) dial(u *url.URL) (net.Conn, error) {
|
||||
return tls.DialWithDialer(dc.dialer, "tcp", net.JoinHostPort(host, port), dc.tlsConfig)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("Unknown scheme '%s'", u.Scheme)
|
||||
return nil, fmt.Errorf("unknown scheme '%s'", u.Scheme)
|
||||
}
|
||||
|
||||
// Dial connects to the given address on the given network using net.Dial
|
||||
@@ -463,6 +463,13 @@ func (l *Conn) sendMessageWithFlags(packet *ber.Packet, flags sendMessageFlags)
|
||||
if l.IsClosing() {
|
||||
return nil, NewError(ErrorNetwork, errors.New("ldap: connection closed"))
|
||||
}
|
||||
messageID, err := packetInt64At(packet, 0)
|
||||
if err != nil {
|
||||
// The packet is built by this package, so a malformed one is our bug,
|
||||
// not a network failure: return the malformed-packet error as-is
|
||||
// instead of nesting it inside ErrorNetwork.
|
||||
return nil, err
|
||||
}
|
||||
l.messageMutex.Lock()
|
||||
l.Debug.Printf("flags&startTLS = %d", flags&startTLS)
|
||||
if l.isStartingTLS {
|
||||
@@ -481,7 +488,6 @@ func (l *Conn) sendMessageWithFlags(packet *ber.Packet, flags sendMessageFlags)
|
||||
l.messageMutex.Unlock()
|
||||
|
||||
responses := make(chan *PacketResponse)
|
||||
messageID := packet.Children[0].Value.(int64)
|
||||
message := &messagePacket{
|
||||
Op: MessageRequest,
|
||||
MessageID: messageID,
|
||||
@@ -659,8 +665,9 @@ func (l *Conn) reader() {
|
||||
if err := addLDAPDescriptions(packet); err != nil {
|
||||
l.Debug.Printf("descriptions error: %s", err)
|
||||
}
|
||||
if len(packet.Children) == 0 {
|
||||
l.Debug.Printf("Received bad ldap packet")
|
||||
messageID, err := packetInt64At(packet, 0)
|
||||
if err != nil {
|
||||
l.Debug.Printf("Received bad ldap packet: %s", err)
|
||||
continue
|
||||
}
|
||||
l.messageMutex.Lock()
|
||||
@@ -670,7 +677,7 @@ func (l *Conn) reader() {
|
||||
l.messageMutex.Unlock()
|
||||
message := &messagePacket{
|
||||
Op: MessageResponse,
|
||||
MessageID: packet.Children[0].Value.(int64),
|
||||
MessageID: messageID,
|
||||
Packet: packet,
|
||||
}
|
||||
if !l.sendProcessMessage(message) {
|
||||
|
||||
+297
-174
@@ -557,65 +557,68 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
value *ber.Packet
|
||||
)
|
||||
|
||||
switch len(packet.Children) {
|
||||
case 0:
|
||||
// at least one child is required for control type
|
||||
return nil, fmt.Errorf("at least one child is required for control type")
|
||||
children, err := packetChildCount(packet, 1, 3, "control")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
case 1:
|
||||
// just type, no criticality or value
|
||||
packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
|
||||
ct, ok := packet.Children[0].Value.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("control type is not a string: %T", packet.Children[0].Value)
|
||||
typeChild, err := packetChild(packet, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
typeChild.Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
|
||||
if typeChild.Value != nil {
|
||||
ct, err := packetString(typeChild)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("control type is not a string: %T: %w", typeChild.Value, err)
|
||||
}
|
||||
ControlType = ct
|
||||
} else if typeChild.Data != nil {
|
||||
ControlType = typeChild.Data.String()
|
||||
} else {
|
||||
return nil, malformedf("not found where to get the control type")
|
||||
}
|
||||
|
||||
case 2:
|
||||
packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
|
||||
if packet.Children[0].Value != nil {
|
||||
ct, ok := packet.Children[0].Value.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("control type is not a string: %T", packet.Children[0].Value)
|
||||
}
|
||||
ControlType = ct
|
||||
} else if packet.Children[0].Data != nil {
|
||||
ControlType = packet.Children[0].Data.String()
|
||||
} else {
|
||||
return nil, fmt.Errorf("not found where to get the control type")
|
||||
}
|
||||
|
||||
// Children[1] could be criticality or value (both are optional)
|
||||
// duck-type on whether this is a boolean
|
||||
if crit, ok := packet.Children[1].Value.(bool); ok {
|
||||
packet.Children[1].Description = "Criticality"
|
||||
Criticality = crit
|
||||
} else {
|
||||
packet.Children[1].Description = "Control Value"
|
||||
value = packet.Children[1]
|
||||
}
|
||||
|
||||
switch len(children) {
|
||||
case 3:
|
||||
packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
|
||||
ct, ok := packet.Children[0].Value.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("control type is not a string: %T", packet.Children[0].Value)
|
||||
// criticality and value present
|
||||
criticality, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ControlType = ct
|
||||
|
||||
packet.Children[1].Description = "Criticality"
|
||||
crit, ok := packet.Children[1].Value.(bool)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("criticality is not a bool: %T", packet.Children[1].Value)
|
||||
criticality.Description = "Criticality"
|
||||
crit, err := packetBool(criticality)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("criticality is not a bool: %T: %w", criticality.Value, err)
|
||||
}
|
||||
Criticality = crit
|
||||
|
||||
packet.Children[2].Description = "Control Value"
|
||||
value = packet.Children[2]
|
||||
|
||||
default:
|
||||
// more than 3 children is invalid
|
||||
return nil, fmt.Errorf("more than 3 children is invalid for controls")
|
||||
valueChild, err := packetChild(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
valueChild.Description = "Control Value"
|
||||
value = valueChild
|
||||
case 2:
|
||||
// Children[1] is criticality or value. RFC 4511 declares
|
||||
// Control ::= SEQUENCE { controlType LDAPOID, criticality BOOLEAN
|
||||
// DEFAULT FALSE, controlValue OCTET STRING OPTIONAL }, so identify
|
||||
// it by its ASN.1 tag rather than by the Go type of Value.
|
||||
second, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if second.ClassType == ber.ClassUniversal && second.Tag == ber.TagBoolean {
|
||||
second.Description = "Criticality"
|
||||
crit, err := packetBool(second)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("criticality is not a bool: %T: %w", second.Value, err)
|
||||
}
|
||||
Criticality = crit
|
||||
} else {
|
||||
second.Description = "Control Value"
|
||||
value = second
|
||||
}
|
||||
}
|
||||
|
||||
switch ControlType {
|
||||
@@ -623,74 +626,113 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
return NewControlManageDsaIT(Criticality), nil
|
||||
case ControlTypePaging:
|
||||
if value == nil {
|
||||
return nil, fmt.Errorf("paging control value is missing")
|
||||
return nil, malformedf("paging control value is missing")
|
||||
}
|
||||
value.Description += " (Paging)"
|
||||
c := new(ControlPaging)
|
||||
if value.Value != nil {
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
data, err := packetData(value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
value.Data.Truncate(0)
|
||||
value.Value = nil
|
||||
value.AppendChild(valueChildren)
|
||||
}
|
||||
if len(value.Children) == 0 {
|
||||
return nil, fmt.Errorf("paging control value is empty")
|
||||
first, err := packetChild(value, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
value = value.Children[0]
|
||||
value = first
|
||||
value.Description = "Search Control Value"
|
||||
if len(value.Children) < 2 {
|
||||
return nil, fmt.Errorf("paging control value has %d children, expected 2", len(value.Children))
|
||||
sizeChild, err := packetChild(value, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
value.Children[0].Description = "Paging Size"
|
||||
value.Children[1].Description = "Cookie"
|
||||
pagingSize, ok := value.Children[0].Value.(int64)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("paging size is not an integer: %T", value.Children[0].Value)
|
||||
cookieChild, err := packetChild(value, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sizeChild.Description = "Paging Size"
|
||||
cookieChild.Description = "Cookie"
|
||||
pagingSize, err := packetInt64(sizeChild)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("paging size is not an integer: %T: %w", sizeChild.Value, err)
|
||||
}
|
||||
c.PagingSize = uint32(pagingSize)
|
||||
c.Cookie = value.Children[1].Data.Bytes()
|
||||
value.Children[1].Value = c.Cookie
|
||||
cookie, err := packetData(cookieChild)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.Cookie = cookie
|
||||
cookieChild.Value = c.Cookie
|
||||
return c, nil
|
||||
case ControlTypeBeheraPasswordPolicy:
|
||||
if value == nil {
|
||||
return nil, fmt.Errorf("invalid value for Control Type ControlTypeBeheraPasswordPolicy: %v", value)
|
||||
}
|
||||
value.Description += " (Password Policy - Behera)"
|
||||
c := NewControlBeheraPasswordPolicy()
|
||||
if value.Value != nil {
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
data, err := packetData(value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
value.Data.Truncate(0)
|
||||
value.Value = nil
|
||||
value.AppendChild(valueChildren)
|
||||
}
|
||||
|
||||
sequence := value.Children[0]
|
||||
sequence, err := packetChild(value, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, child := range sequence.Children {
|
||||
if child.Tag == 0 {
|
||||
if child == nil {
|
||||
continue
|
||||
}
|
||||
switch child.Tag {
|
||||
case 0:
|
||||
// Warning
|
||||
warningPacket := child.Children[0]
|
||||
val, err := ber.ParseInt64(warningPacket.Data.Bytes())
|
||||
warningPacket, err := packetChild(child, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
return nil, err
|
||||
}
|
||||
if warningPacket.Tag == 0 {
|
||||
data, err := packetData(warningPacket)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
val, err := ber.ParseInt64(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
switch warningPacket.Tag {
|
||||
case 0:
|
||||
// timeBeforeExpiration
|
||||
c.Expire = val
|
||||
warningPacket.Value = c.Expire
|
||||
} else if warningPacket.Tag == 1 {
|
||||
case 1:
|
||||
// graceAuthNsRemaining
|
||||
c.Grace = val
|
||||
warningPacket.Value = c.Grace
|
||||
}
|
||||
} else if child.Tag == 1 {
|
||||
case 1:
|
||||
// Error
|
||||
bs := child.Data.Bytes()
|
||||
bs, err := packetData(child)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(bs) != 1 || bs[0] > 8 {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", "invalid PasswordPolicyResponse enum value")
|
||||
return nil, malformedf("invalid PasswordPolicyResponse enum value")
|
||||
}
|
||||
val := int8(bs[0])
|
||||
c.Error = val
|
||||
@@ -711,7 +753,7 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
|
||||
expire, err := strconv.ParseInt(expireStr, 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse value as int: %s", err)
|
||||
return nil, fmt.Errorf("failed to parse value as int: %w", err)
|
||||
}
|
||||
c.Expire = expire
|
||||
value.Value = c.Expire
|
||||
@@ -726,31 +768,58 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
case ControlTypeSubtreeDelete:
|
||||
return NewControlSubtreeDelete(), nil
|
||||
case ControlTypeServerSideSorting:
|
||||
if value == nil {
|
||||
return nil, malformedf("server side sorting control value is missing")
|
||||
}
|
||||
return NewControlServerSideSorting(value)
|
||||
case ControlTypeServerSideSortingResult:
|
||||
return NewControlServerSideSortingResult(value)
|
||||
case ControlTypeDirSync:
|
||||
if value == nil {
|
||||
return nil, malformedf("dirSync control value is missing")
|
||||
}
|
||||
value.Description += " (DirSync)"
|
||||
return NewResponseControlDirSync(value)
|
||||
case ControlTypeSyncState:
|
||||
if value == nil {
|
||||
return nil, malformedf("sync state control value is missing")
|
||||
}
|
||||
value.Description += " (Sync State)"
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
data, err := packetData(value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
return NewControlSyncState(valueChildren)
|
||||
case ControlTypeSyncDone:
|
||||
if value == nil {
|
||||
return nil, malformedf("sync done control value is missing")
|
||||
}
|
||||
value.Description += " (Sync Done)"
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
data, err := packetData(value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
return NewControlSyncDone(valueChildren)
|
||||
case ControlTypeSyncInfo:
|
||||
if value == nil {
|
||||
return nil, malformedf("sync info control value is missing")
|
||||
}
|
||||
value.Description += " (Sync Info)"
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
data, err := packetData(value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
return NewControlSyncInfo(valueChildren)
|
||||
default:
|
||||
@@ -763,10 +832,10 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
// the calling goroutine, see #561. Fall back to the raw bytes
|
||||
// when the value isn't a string so we surface an error
|
||||
// instead of crashing.
|
||||
if s, ok := value.Value.(string); ok {
|
||||
if s, err := packetString(value); err == nil {
|
||||
c.ControlValue = s
|
||||
} else if value.Data != nil {
|
||||
c.ControlValue = value.Data.String()
|
||||
} else if data, err := packetData(value); err == nil {
|
||||
c.ControlValue = string(data)
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
@@ -860,30 +929,64 @@ func NewRequestControlDirSync(
|
||||
|
||||
// NewResponseControlDirSync returns a dir sync control
|
||||
func NewResponseControlDirSync(value *ber.Packet) (*ControlDirSync, error) {
|
||||
if value == nil {
|
||||
return nil, malformedf("dirSync control value is missing")
|
||||
}
|
||||
if value.Value != nil {
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
data, err := packetData(value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
value.Data.Truncate(0)
|
||||
value.Value = nil
|
||||
value.AppendChild(valueChildren)
|
||||
}
|
||||
child := value.Children[0]
|
||||
if len(child.Children) != 3 { // also on initial creation, Cookie is an empty string
|
||||
return nil, fmt.Errorf("invalid number of children in dirSync control")
|
||||
child, err := packetChild(value, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid number of children in dirSync control: %w", err)
|
||||
}
|
||||
// also on initial creation, Cookie is an empty string
|
||||
if _, err := packetChildCount(child, 3, 3, "dirSync control value"); err != nil {
|
||||
return nil, fmt.Errorf("invalid number of children in dirSync control: %w", err)
|
||||
}
|
||||
flagsChild, err := packetChild(child, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid number of children in dirSync control: %w", err)
|
||||
}
|
||||
maxAttrChild, err := packetChild(child, 1)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid number of children in dirSync control: %w", err)
|
||||
}
|
||||
cookieChild, err := packetChild(child, 2)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid number of children in dirSync control: %w", err)
|
||||
}
|
||||
child.Description = "DirSync Control Value"
|
||||
child.Children[0].Description = "Flags"
|
||||
child.Children[1].Description = "MaxAttrCount"
|
||||
child.Children[2].Description = "Cookie"
|
||||
flagsChild.Description = "Flags"
|
||||
maxAttrChild.Description = "MaxAttrCount"
|
||||
cookieChild.Description = "Cookie"
|
||||
|
||||
cookie := child.Children[2].Data.Bytes()
|
||||
child.Children[2].Value = cookie
|
||||
cookie, err := packetData(cookieChild)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cookieChild.Value = cookie
|
||||
flags, err := packetInt64(flagsChild)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
maxAttrCount, err := packetInt64(maxAttrChild)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ControlDirSync{
|
||||
Criticality: true,
|
||||
Flags: child.Children[0].Value.(int64),
|
||||
MaxAttrCount: child.Children[1].Value.(int64),
|
||||
Flags: flags,
|
||||
MaxAttrCount: maxAttrCount,
|
||||
Cookie: cookie,
|
||||
}, nil
|
||||
}
|
||||
@@ -959,39 +1062,59 @@ func (c *ControlServerSideSorting) GetControlType() string {
|
||||
}
|
||||
|
||||
func NewControlServerSideSorting(value *ber.Packet) (*ControlServerSideSorting, error) {
|
||||
val, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
if value == nil {
|
||||
return nil, malformedf("server side sorting control value is missing")
|
||||
}
|
||||
data, err := packetData(value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode packet err: %s", err)
|
||||
return nil, fmt.Errorf("decode packet err: %w", err)
|
||||
}
|
||||
val, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode packet err: %w", err)
|
||||
}
|
||||
|
||||
if len(val.Children) == 0 {
|
||||
return nil, fmt.Errorf("no sequence value in packet")
|
||||
if _, err := packetChildCount(val, 1, -1, "sort key list"); err != nil {
|
||||
return nil, fmt.Errorf("no sequence value in packet: %w", err)
|
||||
}
|
||||
|
||||
var sortKeys []*SortKey
|
||||
|
||||
for i, sequence := range val.Children {
|
||||
if len(sequence.Children) < 1 || len(sequence.Children) > 3 {
|
||||
if sequence == nil {
|
||||
return nil, fmt.Errorf("attributeType is missing from sequence %d", i)
|
||||
}
|
||||
if _, err := packetChildCount(sequence, 1, 3, "sort key sequence"); err != nil {
|
||||
return nil, fmt.Errorf("attributeType is missing from sequence %d: %w", i, err)
|
||||
}
|
||||
|
||||
sortKey := new(SortKey)
|
||||
|
||||
for _, child := range sequence.Children {
|
||||
if child == nil {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case child.ClassType == ber.ClassUniversal && child.Tag == ber.TagOctetString:
|
||||
// A constructed-form OCTET STRING matches this case but leaves
|
||||
// Value nil; guard the assertion so a malformed attributeType is
|
||||
// rejected below rather than panicking.
|
||||
if attrType, ok := child.Value.(string); ok {
|
||||
if attrType, err := packetString(child); err == nil {
|
||||
sortKey.AttributeType = attrType
|
||||
}
|
||||
|
||||
case child.ClassType == ber.ClassContext && child.Tag == 0:
|
||||
sortKey.MatchingRule = child.Data.String()
|
||||
b, err := packetData(child)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sortKey.MatchingRule = string(b)
|
||||
|
||||
case child.ClassType == ber.ClassContext && child.Tag == 1:
|
||||
b := child.Data.Bytes()
|
||||
b, err := packetData(child)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sortKey.Reverse = len(b) > 0 && b[0] != 0
|
||||
}
|
||||
}
|
||||
@@ -1098,7 +1221,7 @@ func (c ControlServerSideSortingCode) Valid() error {
|
||||
func NewControlServerSideSortingResult(pkt *ber.Packet) (*ControlServerSideSortingResult, error) {
|
||||
control := new(ControlServerSideSortingResult)
|
||||
|
||||
if pkt == nil || len(pkt.Children) == 0 {
|
||||
if _, err := packetChildCount(pkt, 1, -1, "server side sorting result"); err != nil {
|
||||
// This is currently not compliant with the ServerSideSorting RFC (see https://datatracker.ietf.org/doc/html/rfc2891#section-1.2).
|
||||
// but it's necessary because there seems to be a bug in the implementation of the popular OpenLDAP server.
|
||||
//
|
||||
@@ -1106,7 +1229,11 @@ func NewControlServerSideSortingResult(pkt *ber.Packet) (*ControlServerSideSorti
|
||||
return control, nil
|
||||
}
|
||||
|
||||
codeInt, err := ber.ParseInt64(pkt.Children[0].Data.Bytes())
|
||||
data, err := packetDataAt(pkt, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
codeInt, err := ber.ParseInt64(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1129,7 +1256,7 @@ type ControlServerSideSortingResult struct {
|
||||
// AttributeType string
|
||||
}
|
||||
|
||||
func (control *ControlServerSideSortingResult) GetControlType() string {
|
||||
func (c *ControlServerSideSortingResult) GetControlType() string {
|
||||
return ControlTypeServerSideSortingResult
|
||||
}
|
||||
|
||||
@@ -1151,7 +1278,7 @@ func (c *ControlServerSideSortingResult) String() string {
|
||||
)
|
||||
}
|
||||
|
||||
// Mode for ControlTypeSyncRequest
|
||||
// ControlSyncRequestMode is the mode for ControlTypeSyncRequest
|
||||
type ControlSyncRequestMode int64
|
||||
|
||||
const (
|
||||
@@ -1225,7 +1352,7 @@ func (c *ControlSyncRequest) String() string {
|
||||
)
|
||||
}
|
||||
|
||||
// State for ControlSyncState
|
||||
// ControlSyncStateState is the state for ControlSyncState
|
||||
type ControlSyncStateState int64
|
||||
|
||||
const (
|
||||
@@ -1248,24 +1375,26 @@ func NewControlSyncState(pkt *ber.Packet) (*ControlSyncState, error) {
|
||||
state ControlSyncStateState
|
||||
entryUUID uuid.UUID
|
||||
cookie []byte
|
||||
err error
|
||||
)
|
||||
switch len(pkt.Children) {
|
||||
case 0, 1:
|
||||
return nil, fmt.Errorf("at least two children are required: %d", len(pkt.Children))
|
||||
case 2:
|
||||
state = ControlSyncStateState(pkt.Children[0].Value.(int64))
|
||||
entryUUID, err = uuid.FromBytes(pkt.Children[1].ByteValue)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode uuid: %w", err)
|
||||
}
|
||||
case 3:
|
||||
state = ControlSyncStateState(pkt.Children[0].Value.(int64))
|
||||
entryUUID, err = uuid.FromBytes(pkt.Children[1].ByteValue)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode uuid: %w", err)
|
||||
}
|
||||
cookie = pkt.Children[2].ByteValue
|
||||
code, err := packetInt64At(pkt, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
state = ControlSyncStateState(code)
|
||||
uuidChild, err := packetChild(pkt, 1)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode uuid: %w", err)
|
||||
}
|
||||
entryUUID, err = uuid.FromBytes(uuidChild.ByteValue)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode uuid: %w", err)
|
||||
}
|
||||
cookieChild, ok, err := packetChildIfPresent(pkt, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ok {
|
||||
cookie = cookieChild.ByteValue
|
||||
}
|
||||
return &ControlSyncState{
|
||||
Criticality: false,
|
||||
@@ -1305,19 +1434,30 @@ type ControlSyncDone struct {
|
||||
RefreshDeletes bool
|
||||
}
|
||||
|
||||
// parseSyncMembers identifies the members of an RFC 4533 sync sequence by tag.
|
||||
// cookie is OPTIONAL and the flags carry a DEFAULT, so a member's position is not
|
||||
// fixed and the count of present members does not identify them.
|
||||
func parseSyncMembers(children []*ber.Packet) (cookie []byte, flag *bool, uuidSet *ber.Packet) {
|
||||
for _, child := range children {
|
||||
switch child.Tag {
|
||||
case ber.TagOctetString:
|
||||
cookie = child.ByteValue
|
||||
case ber.TagBoolean:
|
||||
if b, err := packetBool(child); err == nil {
|
||||
flag = &b
|
||||
}
|
||||
case ber.TagSet:
|
||||
uuidSet = child
|
||||
}
|
||||
}
|
||||
return cookie, flag, uuidSet
|
||||
}
|
||||
|
||||
func NewControlSyncDone(pkt *ber.Packet) (*ControlSyncDone, error) {
|
||||
var (
|
||||
cookie []byte
|
||||
refreshDeletes bool
|
||||
)
|
||||
switch len(pkt.Children) {
|
||||
case 0:
|
||||
// have nothing to do
|
||||
case 1:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
case 2:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
refreshDeletes = pkt.Children[1].Value.(bool)
|
||||
var refreshDeletes bool
|
||||
cookie, flag, _ := parseSyncMembers(pkt.Children)
|
||||
if flag != nil {
|
||||
refreshDeletes = *flag
|
||||
}
|
||||
return &ControlSyncDone{
|
||||
Criticality: false,
|
||||
@@ -1348,7 +1488,7 @@ func (c *ControlSyncDone) String() string {
|
||||
)
|
||||
}
|
||||
|
||||
// Tag For ControlSyncInfo
|
||||
// ControlSyncInfoValue is the tag for ControlSyncInfo
|
||||
type ControlSyncInfoValue uint64
|
||||
|
||||
const (
|
||||
@@ -1430,13 +1570,12 @@ type ControlSyncInfo struct {
|
||||
|
||||
func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error) {
|
||||
var (
|
||||
cookie []byte
|
||||
refreshDone = true
|
||||
refreshDeletes bool
|
||||
syncUUIDs []uuid.UUID
|
||||
)
|
||||
c := &ControlSyncInfo{Criticality: false}
|
||||
switch ControlSyncInfoValue(pkt.Identifier.Tag) {
|
||||
switch ControlSyncInfoValue(pkt.Tag) {
|
||||
case SyncInfoNewcookie:
|
||||
c.Value = SyncInfoNewcookie
|
||||
c.NewCookie = &ControlSyncInfoNewCookie{
|
||||
@@ -1444,14 +1583,9 @@ func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error) {
|
||||
}
|
||||
case SyncInfoRefreshDelete:
|
||||
c.Value = SyncInfoRefreshDelete
|
||||
switch len(pkt.Children) {
|
||||
case 0:
|
||||
// have nothing to do
|
||||
case 1:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
case 2:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
refreshDone = pkt.Children[1].Value.(bool)
|
||||
cookie, flag, _ := parseSyncMembers(pkt.Children)
|
||||
if flag != nil {
|
||||
refreshDone = *flag
|
||||
}
|
||||
c.RefreshDelete = &ControlSyncInfoRefreshDelete{
|
||||
Cookie: cookie,
|
||||
@@ -1459,14 +1593,9 @@ func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error) {
|
||||
}
|
||||
case SyncInfoRefreshPresent:
|
||||
c.Value = SyncInfoRefreshPresent
|
||||
switch len(pkt.Children) {
|
||||
case 0:
|
||||
// have nothing to do
|
||||
case 1:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
case 2:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
refreshDone = pkt.Children[1].Value.(bool)
|
||||
cookie, flag, _ := parseSyncMembers(pkt.Children)
|
||||
if flag != nil {
|
||||
refreshDone = *flag
|
||||
}
|
||||
c.RefreshPresent = &ControlSyncInfoRefreshPresent{
|
||||
Cookie: cookie,
|
||||
@@ -1474,19 +1603,13 @@ func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error) {
|
||||
}
|
||||
case SyncInfoSyncIdSet:
|
||||
c.Value = SyncInfoSyncIdSet
|
||||
switch len(pkt.Children) {
|
||||
case 0:
|
||||
// have nothing to do
|
||||
case 1:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
case 2:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
refreshDeletes = pkt.Children[1].Value.(bool)
|
||||
case 3:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
refreshDeletes = pkt.Children[1].Value.(bool)
|
||||
syncUUIDs = make([]uuid.UUID, 0, len(pkt.Children[2].Children))
|
||||
for _, child := range pkt.Children[2].Children {
|
||||
cookie, flag, uuidSet := parseSyncMembers(pkt.Children)
|
||||
if flag != nil {
|
||||
refreshDeletes = *flag
|
||||
}
|
||||
if uuidSet != nil {
|
||||
syncUUIDs = make([]uuid.UUID, 0, len(uuidSet.Children))
|
||||
for _, child := range uuidSet.Children {
|
||||
u, err := uuid.FromBytes(child.ByteValue)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode uuid: %w", err)
|
||||
@@ -1500,7 +1623,7 @@ func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error) {
|
||||
SyncUUIDs: syncUUIDs,
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown sync info value: %d", pkt.Identifier.Tag)
|
||||
return nil, fmt.Errorf("unknown sync info value: %d", pkt.Tag)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ func (debug *debugging) Enable(b bool) {
|
||||
}
|
||||
|
||||
// Printf writes debug output.
|
||||
func (debug debugging) Printf(format string, args ...interface{}) {
|
||||
func (debug debugging) Printf(format string, args ...any) {
|
||||
if debug {
|
||||
logger.Printf(format, args...)
|
||||
}
|
||||
|
||||
+6
-6
@@ -52,16 +52,16 @@ func (l *Conn) Del(delRequest *DelRequest) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(packet.Children) < 2 {
|
||||
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if packet.Children[1].Tag == ApplicationDelResponse {
|
||||
err := GetLDAPError(packet)
|
||||
if err != nil {
|
||||
if protocolOp.Tag == ApplicationDelResponse {
|
||||
if err := GetLDAPError(packet); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("ldap: unexpected response: %d", packet.Children[1].Tag)
|
||||
return fmt.Errorf("ldap: unexpected response: %d", protocolOp.Tag)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
+73
-25
@@ -90,6 +90,7 @@ const (
|
||||
ErrorUnexpectedMessage = 204
|
||||
ErrorUnexpectedResponse = 205
|
||||
ErrorEmptyPassword = 206
|
||||
ErrorMalformedPacket = 207
|
||||
)
|
||||
|
||||
// LDAPResultCodeMap contains string descriptions for LDAP error codes
|
||||
@@ -175,6 +176,7 @@ var LDAPResultCodeMap = map[uint16]string{
|
||||
ErrorUnexpectedMessage: "Unexpected Message",
|
||||
ErrorUnexpectedResponse: "Unexpected Response",
|
||||
ErrorEmptyPassword: "Empty password not allowed by the client",
|
||||
ErrorMalformedPacket: "Malformed Packet",
|
||||
}
|
||||
|
||||
// Error holds LDAP error information
|
||||
@@ -195,47 +197,93 @@ func (e *Error) Error() string {
|
||||
|
||||
func (e *Error) Unwrap() error { return e.Err }
|
||||
|
||||
// parseLDAPResult extracts resultCode, matchedDN, and diagnosticMessage from a
|
||||
// BER packet representing an LDAPResult (e.g. SearchResultDone).
|
||||
//
|
||||
// Unlike GetLDAPError, parseLDAPResult does not return early when resultCode is
|
||||
// success (0). This allows callers to read the diagnosticMessage even on a
|
||||
// successful operation, which some servers use to signal warnings or degraded
|
||||
// state (for example, a directory in read-only / reinitializing mode).
|
||||
//
|
||||
// Per RFC 4511, an LDAPResult must contain resultCode, matchedDN, and
|
||||
// diagnosticMessage. An error is returned if the packet is malformed.
|
||||
func parseLDAPResult(packet *ber.Packet) (resultCode uint16, matchedDN, diagnosticMessage string, err error) {
|
||||
response, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return 0, "", "", err
|
||||
}
|
||||
|
||||
children, err := packetChildCount(response, 3, 4, "LDAP Result")
|
||||
if err != nil {
|
||||
return 0, "", "", err
|
||||
}
|
||||
|
||||
resultCode, err = packetResultCode(children[0])
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if matchedDN, err = packetString(children[1]); err != nil {
|
||||
return
|
||||
}
|
||||
diagnosticMessage, err = packetString(children[2])
|
||||
return
|
||||
}
|
||||
|
||||
// GetLDAPError creates an Error out of a BER packet representing a LDAPResult
|
||||
// The return is an error object. It can be casted to a Error structure.
|
||||
// This function returns nil if resultCode in the LDAPResult sequence is success(0).
|
||||
func GetLDAPError(packet *ber.Packet) error {
|
||||
if packet == nil {
|
||||
return &Error{ResultCode: ErrorUnexpectedResponse, Err: fmt.Errorf("Empty packet")}
|
||||
return &Error{ResultCode: ErrorUnexpectedResponse, Err: fmt.Errorf("empty packet")}
|
||||
}
|
||||
|
||||
if len(packet.Children) >= 2 {
|
||||
response := packet.Children[1]
|
||||
if response == nil {
|
||||
return &Error{ResultCode: ErrorUnexpectedResponse, Err: fmt.Errorf("Empty response in packet"), Packet: packet}
|
||||
if _, err := packetChildCount(packet, 2, -1, "LDAP response"); err == nil {
|
||||
response, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return &Error{ResultCode: ErrorUnexpectedResponse, Err: fmt.Errorf("empty response in packet"), Packet: packet}
|
||||
}
|
||||
if response.ClassType == ber.ClassApplication && response.TagType == ber.TypeConstructed && len(response.Children) >= 3 {
|
||||
if ber.Type(response.Children[0].Tag) == ber.Type(ber.TagInteger) || ber.Type(response.Children[0].Tag) == ber.Type(ber.TagEnumerated) {
|
||||
if response.Children[0].Value == nil {
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("Invalid result code in packet"), Packet: packet}
|
||||
if response.ClassType == ber.ClassApplication && response.TagType == ber.TypeConstructed {
|
||||
if _, err := packetChildCount(response, 3, -1, "LDAP result"); err == nil {
|
||||
resultCodeChild, err := packetChild(response, 0)
|
||||
if err != nil {
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("invalid result code in packet"), Packet: packet}
|
||||
}
|
||||
|
||||
resultCode := uint16(response.Children[0].Value.(int64))
|
||||
if resultCode == 0 { // No error
|
||||
return nil
|
||||
}
|
||||
|
||||
if ber.Type(response.Children[1].Tag) == ber.Type(ber.TagOctetString) &&
|
||||
ber.Type(response.Children[2].Tag) == ber.Type(ber.TagOctetString) {
|
||||
if response.Children[1].Value == nil {
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("Invalid matchedDN in packet"), Packet: packet}
|
||||
if ber.Type(resultCodeChild.Tag) == ber.Type(ber.TagInteger) || ber.Type(resultCodeChild.Tag) == ber.Type(ber.TagEnumerated) {
|
||||
resultCode, err := packetResultCode(resultCodeChild)
|
||||
if err != nil {
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("invalid result code in packet"), Packet: packet}
|
||||
}
|
||||
return &Error{
|
||||
ResultCode: resultCode,
|
||||
MatchedDN: response.Children[1].Value.(string),
|
||||
Err: fmt.Errorf("%v", response.Children[2].Value),
|
||||
Packet: packet,
|
||||
|
||||
if resultCode == 0 { // No error
|
||||
return nil
|
||||
}
|
||||
|
||||
matchedDNChild, matchedDNErr := packetChild(response, 1)
|
||||
errorMessageChild, errorMessageErr := packetChild(response, 2)
|
||||
if matchedDNErr != nil || errorMessageErr != nil {
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("invalid packet format"), Packet: packet}
|
||||
}
|
||||
|
||||
if ber.Type(matchedDNChild.Tag) == ber.Type(ber.TagOctetString) &&
|
||||
ber.Type(errorMessageChild.Tag) == ber.Type(ber.TagOctetString) {
|
||||
matchedDN, err := packetString(matchedDNChild)
|
||||
if err != nil {
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("invalid matchedDN in packet"), Packet: packet}
|
||||
}
|
||||
return &Error{
|
||||
ResultCode: resultCode,
|
||||
MatchedDN: matchedDN,
|
||||
Err: fmt.Errorf("%v", errorMessageChild.Value),
|
||||
Packet: packet,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("Invalid packet format"), Packet: packet}
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("invalid packet format"), Packet: packet}
|
||||
}
|
||||
|
||||
// NewError creates an LDAP error with the given code and underlying error
|
||||
|
||||
+38
-12
@@ -32,7 +32,7 @@ func (er ExtendedRequest) appendTo(envelope *ber.Packet) error {
|
||||
pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationExtendedRequest, nil, "Extended Request")
|
||||
pkt.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, ber.TagEOC, er.Name, "Extended Request Name"))
|
||||
if er.Value != nil {
|
||||
pkt.AppendChild(er.Value)
|
||||
pkt.AppendChild(encodeExtendedRequestValue(er.Value))
|
||||
}
|
||||
envelope.AppendChild(pkt)
|
||||
if len(er.Controls) > 0 {
|
||||
@@ -41,6 +41,16 @@ func (er ExtendedRequest) appendTo(envelope *ber.Packet) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// encodeExtendedRequestValue wraps the caller payload as RFC 4511 requestValue
|
||||
// [1] OCTET STRING. Callers that already built that field (context class, tag 1)
|
||||
// are left unchanged so Password Modify-style packets are not double-wrapped.
|
||||
func encodeExtendedRequestValue(value *ber.Packet) *ber.Packet {
|
||||
if value.ClassType == ber.ClassContext && value.Tag == 1 {
|
||||
return value
|
||||
}
|
||||
return ber.NewString(ber.ClassContext, ber.TypePrimitive, 1, string(value.Bytes()), "Extended Request Value")
|
||||
}
|
||||
|
||||
// ExtendedResponse represents the response from the directory server
|
||||
// after sending an extended request
|
||||
// See: https://www.rfc-editor.org/rfc/rfc4511#section-4.12
|
||||
@@ -72,16 +82,24 @@ func (l *Conn) Extended(er *ExtendedRequest) (*ExtendedResponse, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = GetLDAPError(packet); err != nil {
|
||||
|
||||
return decodeExtendedResponse(packet)
|
||||
}
|
||||
|
||||
// decodeExtendedResponse decodes an extended response envelope, including any
|
||||
// response controls. It is separated from the network loop so the full
|
||||
// response decoder can be fuzzed directly.
|
||||
func decodeExtendedResponse(packet *ber.Packet) (*ExtendedResponse, error) {
|
||||
if err := GetLDAPError(packet); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
extResp := packet.Children[1]
|
||||
if len(extResp.Children) < 3 {
|
||||
return nil, fmt.Errorf(
|
||||
"ldap: malformed extended response: expected at least 3 children, got %d",
|
||||
len(packet.Children),
|
||||
)
|
||||
extResp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := packetChildCount(extResp, 3, -1, "extended response"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
response := &ExtendedResponse{
|
||||
@@ -99,17 +117,25 @@ func (l *Conn) Extended(er *ExtendedRequest) (*ExtendedResponse, error) {
|
||||
}
|
||||
switch child.Tag {
|
||||
case ber.TagEnumerated:
|
||||
response.Name = child.Data.String()
|
||||
name, err := packetData(child)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response.Name = string(name)
|
||||
case ber.TagEmbeddedPDV:
|
||||
response.Value = child
|
||||
}
|
||||
}
|
||||
|
||||
if len(packet.Children) == 3 {
|
||||
for _, child := range packet.Children[2].Children {
|
||||
controlsChild, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ok {
|
||||
for _, child := range controlsChild.Children {
|
||||
decodedChild, decodeErr := DecodeControl(child)
|
||||
if decodeErr != nil {
|
||||
return nil, fmt.Errorf("failed to decode child control: %s", decodeErr)
|
||||
return nil, fmt.Errorf("failed to decode child control: %w", decodeErr)
|
||||
}
|
||||
response.Controls = append(response.Controls, decodedChild)
|
||||
}
|
||||
|
||||
+18
-3
@@ -208,9 +208,12 @@ func compileFilterSet(filter string, pos int, parent *ber.Packet) (int, error) {
|
||||
pos = newPos
|
||||
parent.AppendChild(child)
|
||||
}
|
||||
if pos == len(filter) {
|
||||
if pos >= len(filter) {
|
||||
return pos, NewError(ErrorFilterCompile, errors.New("ldap: unexpected end of filter"))
|
||||
}
|
||||
if filter[pos] != ')' {
|
||||
return pos, NewError(ErrorFilterCompile, fmt.Errorf("ldap: expected ')' at position %d", pos))
|
||||
}
|
||||
|
||||
return pos + 1, nil
|
||||
}
|
||||
@@ -235,8 +238,17 @@ func compileFilter(filter string, pos int) (*ber.Packet, int, error) {
|
||||
return nil, 0, NewError(ErrorFilterCompile, fmt.Errorf("ldap: error reading rune at position %d", newPos))
|
||||
case '(':
|
||||
packet, newPos, err = compileFilter(filter, pos+currentWidth)
|
||||
if err != nil {
|
||||
return nil, newPos, err
|
||||
}
|
||||
if newPos >= len(filter) {
|
||||
return nil, newPos, NewError(ErrorFilterCompile, errors.New("ldap: unexpected end of filter"))
|
||||
}
|
||||
if filter[newPos] != ')' {
|
||||
return nil, newPos, NewError(ErrorFilterCompile, fmt.Errorf("ldap: expected ')' at position %d", newPos))
|
||||
}
|
||||
newPos++
|
||||
return packet, newPos, err
|
||||
return packet, newPos, nil
|
||||
case '&':
|
||||
packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterAnd, nil, FilterMap[FilterAnd])
|
||||
newPos, err = compileFilterSet(filter, pos+currentWidth, packet)
|
||||
@@ -249,8 +261,11 @@ func compileFilter(filter string, pos int) (*ber.Packet, int, error) {
|
||||
packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterNot, nil, FilterMap[FilterNot])
|
||||
var child *ber.Packet
|
||||
child, newPos, err = compileFilter(filter, pos+currentWidth)
|
||||
if err != nil {
|
||||
return nil, newPos, err
|
||||
}
|
||||
packet.AppendChild(child)
|
||||
return packet, newPos, err
|
||||
return packet, newPos, nil
|
||||
default:
|
||||
const (
|
||||
stateReadingAttr = 0
|
||||
|
||||
+198
-68
@@ -2,7 +2,6 @@ package ldap
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -101,10 +100,18 @@ func addLDAPDescriptions(packet *ber.Packet) (err error) {
|
||||
}
|
||||
}()
|
||||
packet.Description = "LDAP Response"
|
||||
packet.Children[0].Description = "Message ID"
|
||||
messageID, err := packetChild(packet, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
messageID.Description = "Message ID"
|
||||
|
||||
application := uint8(packet.Children[1].Tag)
|
||||
packet.Children[1].Description = ApplicationMap[application]
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
application := uint8(protocolOp.Tag)
|
||||
protocolOp.Description = ApplicationMap[application]
|
||||
|
||||
switch application {
|
||||
case ApplicationBindRequest:
|
||||
@@ -116,18 +123,46 @@ func addLDAPDescriptions(packet *ber.Packet) (err error) {
|
||||
case ApplicationSearchRequest:
|
||||
err = addRequestDescriptions(packet)
|
||||
case ApplicationSearchResultEntry:
|
||||
packet.Children[1].Children[0].Description = "Object Name"
|
||||
packet.Children[1].Children[1].Description = "Attributes"
|
||||
for _, child := range packet.Children[1].Children[1].Children {
|
||||
objectName, err := packetChild(protocolOp, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
objectName.Description = "Object Name"
|
||||
attrs, err := packetChild(protocolOp, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
attrs.Description = "Attributes"
|
||||
for _, child := range attrs.Children {
|
||||
if child == nil {
|
||||
continue
|
||||
}
|
||||
child.Description = "Attribute"
|
||||
child.Children[0].Description = "Attribute Name"
|
||||
child.Children[1].Description = "Attribute Values"
|
||||
for _, grandchild := range child.Children[1].Children {
|
||||
nameChild, err := packetChild(child, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
nameChild.Description = "Attribute Name"
|
||||
valuesChild, err := packetChild(child, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
valuesChild.Description = "Attribute Values"
|
||||
for _, grandchild := range valuesChild.Children {
|
||||
if grandchild == nil {
|
||||
continue
|
||||
}
|
||||
grandchild.Description = "Attribute Value"
|
||||
}
|
||||
}
|
||||
if len(packet.Children) == 3 {
|
||||
err = addControlDescriptions(packet.Children[2])
|
||||
controls, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok {
|
||||
if err = addControlDescriptions(controls); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case ApplicationSearchResultDone:
|
||||
err = addDefaultLDAPResponseDescriptions(packet)
|
||||
@@ -160,42 +195,55 @@ func addLDAPDescriptions(packet *ber.Packet) (err error) {
|
||||
func addControlDescriptions(packet *ber.Packet) error {
|
||||
packet.Description = "Controls"
|
||||
for _, child := range packet.Children {
|
||||
if child == nil {
|
||||
return fmt.Errorf("nil control packet found")
|
||||
}
|
||||
var value *ber.Packet
|
||||
controlType := ""
|
||||
child.Description = "Control"
|
||||
switch len(child.Children) {
|
||||
case 0:
|
||||
// at least one child is required for control type
|
||||
return fmt.Errorf("at least one child is required for control type")
|
||||
|
||||
case 1:
|
||||
// just type, no criticality or value
|
||||
controlType = child.Children[0].Value.(string)
|
||||
child.Children[0].Description = "Control Type (" + ControlTypeMap[controlType] + ")"
|
||||
controlChildren, err := packetChildCount(child, 1, 3, "control packet")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
typeChild, err := packetChild(child, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
controlType, err = packetString(typeChild)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
typeChild.Description = "Control Type (" + ControlTypeMap[controlType] + ")"
|
||||
|
||||
switch len(controlChildren) {
|
||||
case 2:
|
||||
controlType = child.Children[0].Value.(string)
|
||||
child.Children[0].Description = "Control Type (" + ControlTypeMap[controlType] + ")"
|
||||
// Children[1] could be criticality or value (both are optional)
|
||||
// duck-type on whether this is a boolean
|
||||
if _, ok := child.Children[1].Value.(bool); ok {
|
||||
child.Children[1].Description = "Criticality"
|
||||
second, err := packetChild(child, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Children[1] is criticality or value; identify it by its ASN.1 tag.
|
||||
if second.ClassType == ber.ClassUniversal && second.Tag == ber.TagBoolean {
|
||||
second.Description = "Criticality"
|
||||
} else {
|
||||
child.Children[1].Description = "Control Value"
|
||||
value = child.Children[1]
|
||||
second.Description = "Control Value"
|
||||
value = second
|
||||
}
|
||||
|
||||
case 3:
|
||||
// criticality and value present
|
||||
controlType = child.Children[0].Value.(string)
|
||||
child.Children[0].Description = "Control Type (" + ControlTypeMap[controlType] + ")"
|
||||
child.Children[1].Description = "Criticality"
|
||||
child.Children[2].Description = "Control Value"
|
||||
value = child.Children[2]
|
||||
|
||||
default:
|
||||
// more than 3 children is invalid
|
||||
return fmt.Errorf("more than 3 children for control packet found")
|
||||
criticality, err := packetChild(child, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
criticality.Description = "Criticality"
|
||||
valueChild, err := packetChild(child, 2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
valueChild.Description = "Control Value"
|
||||
value = valueChild
|
||||
}
|
||||
|
||||
if value == nil {
|
||||
@@ -205,53 +253,99 @@ func addControlDescriptions(packet *ber.Packet) error {
|
||||
case ControlTypePaging:
|
||||
value.Description += " (Paging)"
|
||||
if value.Value != nil {
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
data, err := packetData(value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
return fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
value.Data.Truncate(0)
|
||||
value.Value = nil
|
||||
valueChildren.Children[1].Value = valueChildren.Children[1].Data.Bytes()
|
||||
cookieChild, err := packetChild(valueChildren, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cookie, err := packetData(cookieChild)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cookieChild.Value = cookie
|
||||
value.AppendChild(valueChildren)
|
||||
}
|
||||
value.Children[0].Description = "Real Search Control Value"
|
||||
value.Children[0].Children[0].Description = "Paging Size"
|
||||
value.Children[0].Children[1].Description = "Cookie"
|
||||
real, err := packetChild(value, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
real.Description = "Real Search Control Value"
|
||||
sizeChild, err := packetChild(real, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cookieChild, err := packetChild(real, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sizeChild.Description = "Paging Size"
|
||||
cookieChild.Description = "Cookie"
|
||||
|
||||
case ControlTypeBeheraPasswordPolicy:
|
||||
value.Description += " (Password Policy - Behera Draft)"
|
||||
if value.Value != nil {
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
data, err := packetData(value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
return fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
value.Data.Truncate(0)
|
||||
value.Value = nil
|
||||
value.AppendChild(valueChildren)
|
||||
}
|
||||
sequence := value.Children[0]
|
||||
sequence, err := packetChild(value, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, child := range sequence.Children {
|
||||
if child.Tag == 0 {
|
||||
if child == nil {
|
||||
continue
|
||||
}
|
||||
switch child.Tag {
|
||||
case 0:
|
||||
// Warning
|
||||
warningPacket := child.Children[0]
|
||||
val, err := ber.ParseInt64(warningPacket.Data.Bytes())
|
||||
warningPacket, err := packetChild(child, 0)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
return err
|
||||
}
|
||||
if warningPacket.Tag == 0 {
|
||||
data, err := packetData(warningPacket)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
val, err := ber.ParseInt64(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
switch warningPacket.Tag {
|
||||
case 0:
|
||||
// timeBeforeExpiration
|
||||
value.Description += " (TimeBeforeExpiration)"
|
||||
warningPacket.Value = val
|
||||
} else if warningPacket.Tag == 1 {
|
||||
case 1:
|
||||
// graceAuthNsRemaining
|
||||
value.Description += " (GraceAuthNsRemaining)"
|
||||
warningPacket.Value = val
|
||||
}
|
||||
} else if child.Tag == 1 {
|
||||
case 1:
|
||||
// Error
|
||||
bs := child.Data.Bytes()
|
||||
bs, err := packetData(child)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(bs) != 1 || bs[0] > 8 {
|
||||
return fmt.Errorf("failed to decode data bytes: %s", "invalid PasswordPolicyResponse enum value")
|
||||
return malformedf("invalid PasswordPolicyResponse enum value")
|
||||
}
|
||||
val := int8(bs[0])
|
||||
child.Description = "Error"
|
||||
@@ -265,10 +359,22 @@ func addControlDescriptions(packet *ber.Packet) error {
|
||||
|
||||
func addRequestDescriptions(packet *ber.Packet) error {
|
||||
packet.Description = "LDAP Request"
|
||||
packet.Children[0].Description = "Message ID"
|
||||
packet.Children[1].Description = ApplicationMap[uint8(packet.Children[1].Tag)]
|
||||
if len(packet.Children) == 3 {
|
||||
return addControlDescriptions(packet.Children[2])
|
||||
messageID, err := packetChild(packet, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
messageID.Description = "Message ID"
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
protocolOp.Description = ApplicationMap[uint8(protocolOp.Tag)]
|
||||
controls, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok {
|
||||
return addControlDescriptions(controls)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -283,28 +389,52 @@ func addDefaultLDAPResponseDescriptions(packet *ber.Packet) error {
|
||||
description = "Error Message"
|
||||
}
|
||||
|
||||
packet.Children[1].Children[0].Description = "Result Code (" + LDAPResultCodeMap[resultCode] + ")"
|
||||
packet.Children[1].Children[1].Description = "Matched DN (" + matchedDN + ")"
|
||||
packet.Children[1].Children[2].Description = description
|
||||
if len(packet.Children[1].Children) > 3 {
|
||||
packet.Children[1].Children[3].Description = "Referral"
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(packet.Children) == 3 {
|
||||
return addControlDescriptions(packet.Children[2])
|
||||
resultCodeChild, err := packetChild(protocolOp, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resultCodeChild.Description = "Result Code (" + LDAPResultCodeMap[resultCode] + ")"
|
||||
matchedDNChild, err := packetChild(protocolOp, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
matchedDNChild.Description = "Matched DN (" + matchedDN + ")"
|
||||
errorMessageChild, err := packetChild(protocolOp, 2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
errorMessageChild.Description = description
|
||||
referral, ok, err := packetChildIfPresent(protocolOp, 3)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok {
|
||||
referral.Description = "Referral"
|
||||
}
|
||||
controls, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok {
|
||||
return addControlDescriptions(controls)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DebugBinaryFile reads and prints packets from the given filename
|
||||
func DebugBinaryFile(fileName string) error {
|
||||
file, err := ioutil.ReadFile(fileName)
|
||||
file, err := os.ReadFile(fileName)
|
||||
if err != nil {
|
||||
return NewError(ErrorDebugging, err)
|
||||
}
|
||||
ber.PrintBytes(os.Stdout, file, "")
|
||||
packet, err := ber.DecodePacketErr(file)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode packet: %s", err)
|
||||
return fmt.Errorf("failed to decode packet: %w", err)
|
||||
}
|
||||
if err := addLDAPDescriptions(packet); err != nil {
|
||||
return err
|
||||
|
||||
+6
-6
@@ -89,16 +89,16 @@ func (l *Conn) ModifyDN(m *ModifyDNRequest) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(packet.Children) < 2 {
|
||||
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if packet.Children[1].Tag == ApplicationModifyDNResponse {
|
||||
err := GetLDAPError(packet)
|
||||
if err != nil {
|
||||
if protocolOp.Tag == ApplicationModifyDNResponse {
|
||||
if err := GetLDAPError(packet); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("ldap: unexpected response: %d", packet.Children[1].Tag)
|
||||
return fmt.Errorf("ldap: unexpected response: %d", protocolOp.Tag)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
+18
-13
@@ -121,16 +121,16 @@ func (l *Conn) Modify(modifyRequest *ModifyRequest) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(packet.Children) < 2 {
|
||||
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if packet.Children[1].Tag == ApplicationModifyResponse {
|
||||
err := GetLDAPError(packet)
|
||||
if err != nil {
|
||||
if protocolOp.Tag == ApplicationModifyResponse {
|
||||
if err := GetLDAPError(packet); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("ldap: unexpected response: %d", packet.Children[1].Tag)
|
||||
return fmt.Errorf("ldap: unexpected response: %d", protocolOp.Tag)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -162,19 +162,22 @@ func (l *Conn) ModifyWithResult(modifyRequest *ModifyRequest) (*ModifyResult, er
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(packet.Children) < 2 {
|
||||
return nil, fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch packet.Children[1].Tag {
|
||||
case ApplicationModifyResponse:
|
||||
if protocolOp.Tag == ApplicationModifyResponse {
|
||||
if err = GetLDAPError(packet); err != nil {
|
||||
result.Referral = getReferral(err, packet)
|
||||
|
||||
return result, err
|
||||
}
|
||||
if len(packet.Children) == 3 {
|
||||
for _, child := range packet.Children[2].Children {
|
||||
controls, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ok {
|
||||
for _, child := range controls.Children {
|
||||
decodedChild, err := DecodeControl(child)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to decode child control: " + err.Error())
|
||||
@@ -182,6 +185,8 @@ func (l *Conn) ModifyWithResult(modifyRequest *ModifyRequest) (*ModifyResult, er
|
||||
result.Controls = append(result.Controls, decodedChild)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return nil, fmt.Errorf("ldap: unexpected response: %d", protocolOp.Tag)
|
||||
}
|
||||
l.Debug.Printf("%d: returning", msgCtx.id)
|
||||
return result, nil
|
||||
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
package ldap
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
ber "github.com/go-asn1-ber/asn1-ber"
|
||||
)
|
||||
|
||||
// ErrMalformedPacket is the sentinel wrapped by the structural decoding
|
||||
// failures reported by the helpers in this file, so callers can distinguish a
|
||||
// malformed packet with errors.Is. It is nested inside the LDAP-style *Error
|
||||
// (ResultCode ErrorMalformedPacket) built by malformedf; wrapping that error
|
||||
// with %s instead of %w drops the sentinel from the chain.
|
||||
var ErrMalformedPacket = errors.New("ldap: malformed packet")
|
||||
|
||||
// malformedf builds an LDAP-style error (NewError with ErrorMalformedPacket)
|
||||
// wrapping ErrMalformedPacket. Callers must wrap its result with %w, not %s,
|
||||
// to keep both the *Error and the sentinel matchable with errors.As/errors.Is.
|
||||
func malformedf(format string, args ...any) error {
|
||||
return NewError(ErrorMalformedPacket, fmt.Errorf("%w: %s", ErrMalformedPacket, fmt.Sprintf(format, args...)))
|
||||
}
|
||||
|
||||
// packetChildCount asserts that p has between min and max direct children
|
||||
// (inclusive) and returns them. A negative min disables the lower bound and a
|
||||
// negative max disables the upper bound. It centralizes the repeated
|
||||
// children-count validation so every decode path rejects malformed packets
|
||||
// with a consistent, descriptive error instead of a bespoke length check.
|
||||
//
|
||||
// min == max means an exact count is required.
|
||||
func packetChildCount(p *ber.Packet, min, max int, what string) ([]*ber.Packet, error) {
|
||||
if p == nil {
|
||||
return nil, malformedf("%s is missing", what)
|
||||
}
|
||||
n := len(p.Children)
|
||||
switch {
|
||||
case min >= 0 && max >= 0 && min == max && n != min:
|
||||
return nil, malformedf("%s: expected %d children, got %d", what, min, n)
|
||||
case min >= 0 && n < min:
|
||||
return nil, malformedf("%s: expected %d or more children, got %d", what, min, n)
|
||||
case max >= 0 && n > max:
|
||||
return nil, malformedf("%s: expected at most %d children, got %d", what, max, n)
|
||||
}
|
||||
return p.Children, nil
|
||||
}
|
||||
|
||||
// packetChild returns the i-th child of p. It is the primary accessor for
|
||||
// inbound packets: a field's position in its ASN.1 SEQUENCE is fixed by the
|
||||
// relevant RFC, so callers must address packets by order rather than by
|
||||
// inspecting the Go type of a child's Value.
|
||||
func packetChild(p *ber.Packet, i int) (*ber.Packet, error) {
|
||||
if p == nil {
|
||||
return nil, malformedf("nil packet")
|
||||
}
|
||||
if i < 0 || i >= len(p.Children) {
|
||||
return nil, malformedf("child index %d out of range, packet has %d children", i, len(p.Children))
|
||||
}
|
||||
child := p.Children[i]
|
||||
if child == nil {
|
||||
return nil, malformedf("child index %d is nil", i)
|
||||
}
|
||||
return child, nil
|
||||
}
|
||||
|
||||
// packetChildIfPresent is packetChild for OPTIONAL members: when the packet
|
||||
// has no child at index i it reports ok == false instead of an error. A nil
|
||||
// packet or a nil placeholder child is still an error, because those are
|
||||
// invalid rather than simply absent.
|
||||
func packetChildIfPresent(p *ber.Packet, i int) (child *ber.Packet, ok bool, err error) {
|
||||
if p == nil {
|
||||
return nil, false, malformedf("nil packet")
|
||||
}
|
||||
if i < 0 || i >= len(p.Children) {
|
||||
return nil, false, nil
|
||||
}
|
||||
child = p.Children[i]
|
||||
if child == nil {
|
||||
return nil, false, malformedf("child index %d is nil", i)
|
||||
}
|
||||
return child, true, nil
|
||||
}
|
||||
|
||||
// packetString returns the string value of p. The field's position or tag is
|
||||
// expected to have already fixed it as a string by the schema; this is the
|
||||
// single guarded leaf conversion, never a way to discover what a field is.
|
||||
func packetString(p *ber.Packet) (string, error) {
|
||||
if p == nil {
|
||||
return "", malformedf("missing string value")
|
||||
}
|
||||
s, ok := p.Value.(string)
|
||||
if !ok {
|
||||
return "", malformedf("expected string value, got %T", p.Value)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// packetInt64 returns the int64 value of p, whose schema position fixed it as
|
||||
// an INTEGER or ENUMERATED.
|
||||
func packetInt64(p *ber.Packet) (int64, error) {
|
||||
if p == nil {
|
||||
return 0, malformedf("missing integer value")
|
||||
}
|
||||
i, ok := p.Value.(int64)
|
||||
if !ok {
|
||||
return 0, malformedf("expected integer value, got %T", p.Value)
|
||||
}
|
||||
return i, nil
|
||||
}
|
||||
|
||||
// packetResultCode returns the LDAPResult resultCode held by p. RFC 4511
|
||||
// declares resultCode an ENUMERATED and the codes it assigns all fit the uint16
|
||||
// this package exposes, so a value outside that range is malformed rather than
|
||||
// merely unknown. Narrowing it instead would alias it onto an unrelated code,
|
||||
// and any multiple of 2^16 onto success(0).
|
||||
func packetResultCode(p *ber.Packet) (uint16, error) {
|
||||
code, err := packetInt64(p)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if code < 0 || code > math.MaxUint16 {
|
||||
return 0, malformedf("result code %d out of range", code)
|
||||
}
|
||||
return uint16(code), nil
|
||||
}
|
||||
|
||||
// packetBool returns the bool value of p, whose schema position or BOOLEAN tag
|
||||
// fixed it as a boolean.
|
||||
func packetBool(p *ber.Packet) (bool, error) {
|
||||
if p == nil {
|
||||
return false, malformedf("missing boolean value")
|
||||
}
|
||||
b, ok := p.Value.(bool)
|
||||
if !ok {
|
||||
return false, malformedf("expected boolean value, got %T", p.Value)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// packetData returns the raw BER contents of p. Unlike p.Data.Bytes() it is
|
||||
// nil-safe, so a packet that carries no data buffer yields an error rather
|
||||
// than a nil-pointer panic.
|
||||
func packetData(p *ber.Packet) ([]byte, error) {
|
||||
if p == nil {
|
||||
return nil, malformedf("missing packet data")
|
||||
}
|
||||
if p.Data == nil {
|
||||
return nil, malformedf("packet has no data buffer")
|
||||
}
|
||||
return p.Data.Bytes(), nil
|
||||
}
|
||||
|
||||
// packetStringAt returns the string value of the i-th child of p. It combines
|
||||
// ordered access with the guarded leaf conversion and is the common shape for
|
||||
// response fields such as a DN or a referral URI.
|
||||
func packetStringAt(p *ber.Packet, i int) (string, error) {
|
||||
child, err := packetChild(p, i)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return packetString(child)
|
||||
}
|
||||
|
||||
// packetInt64At returns the int64 value of the i-th child of p.
|
||||
func packetInt64At(p *ber.Packet, i int) (int64, error) {
|
||||
child, err := packetChild(p, i)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return packetInt64(child)
|
||||
}
|
||||
|
||||
// packetDataAt returns the raw BER contents of the i-th child of p.
|
||||
func packetDataAt(p *ber.Packet, i int) ([]byte, error) {
|
||||
child, err := packetChild(p, i)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return packetData(child)
|
||||
}
|
||||
+29
-10
@@ -93,29 +93,48 @@ func (l *Conn) PasswordModify(passwordModifyRequest *PasswordModifyRequest) (*Pa
|
||||
|
||||
result := &PasswordModifyResult{}
|
||||
|
||||
if len(packet.Children) < 2 {
|
||||
return nil, fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
extendedResponse, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if packet.Children[1].Tag == ApplicationExtendedResponse {
|
||||
if extendedResponse.Tag == ApplicationExtendedResponse {
|
||||
if err = GetLDAPError(packet); err != nil {
|
||||
result.Referral = getReferral(err, packet)
|
||||
|
||||
return result, err
|
||||
}
|
||||
} else {
|
||||
return nil, NewError(ErrorUnexpectedResponse, fmt.Errorf("unexpected Response: %d", packet.Children[1].Tag))
|
||||
return nil, NewError(ErrorUnexpectedResponse, fmt.Errorf("unexpected Response: %d", extendedResponse.Tag))
|
||||
}
|
||||
|
||||
extendedResponse := packet.Children[1]
|
||||
for _, child := range extendedResponse.Children {
|
||||
if child == nil {
|
||||
continue
|
||||
}
|
||||
if child.Tag == ber.TagEmbeddedPDV {
|
||||
passwordModifyResponseValue, err := ber.DecodePacketErr(child.Data.Bytes())
|
||||
data, err := packetData(child)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap: failed to decode PasswordModifyResponseValue: %s", err)
|
||||
return nil, fmt.Errorf("ldap: failed to decode PasswordModifyResponseValue: %w", err)
|
||||
}
|
||||
if len(passwordModifyResponseValue.Children) == 1 {
|
||||
if passwordModifyResponseValue.Children[0].Tag == ber.TagEOC {
|
||||
result.GeneratedPassword = ber.DecodeString(passwordModifyResponseValue.Children[0].Data.Bytes())
|
||||
passwordModifyResponseValue, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap: failed to decode PasswordModifyResponseValue: %w", err)
|
||||
}
|
||||
pwChildren, err := packetChildCount(passwordModifyResponseValue, 0, 1, "password modify response value")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(pwChildren) == 1 {
|
||||
generatedPasswordValue, err := packetChild(passwordModifyResponseValue, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if generatedPasswordValue.Tag == ber.TagEOC {
|
||||
pw, err := packetData(generatedPasswordValue)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result.GeneratedPassword = ber.DecodeString(pw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+13
-8
@@ -76,7 +76,8 @@ func getReferral(err error, packet *ber.Packet) (referral string) {
|
||||
return ""
|
||||
}
|
||||
|
||||
if len(packet.Children) < 2 {
|
||||
protocolOp, perr := packetChild(packet, 1)
|
||||
if perr != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -87,13 +88,17 @@ func getReferral(err error, packet *ber.Packet) (referral string) {
|
||||
//
|
||||
// Related Issues:
|
||||
// - https://github.com/authelia/authelia/issues/4199 (downstream)
|
||||
if len(packet.Children[1].Children) == 0 || (packet.Children[1].TagType != ber.TypeConstructed || packet.Children[1].ClassType != ber.ClassApplication) {
|
||||
if protocolOp.TagType != ber.TypeConstructed || protocolOp.ClassType != ber.ClassApplication {
|
||||
return ""
|
||||
}
|
||||
if _, err := packetChildCount(protocolOp, 1, -1, "referral"); err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
var ok bool
|
||||
|
||||
for _, child := range packet.Children[1].Children {
|
||||
for _, child := range protocolOp.Children {
|
||||
if child == nil {
|
||||
continue
|
||||
}
|
||||
// The referral URI itself should be contained within a child which has a Tag of ber.BitString or
|
||||
// ber.TagPrintableString, and the Type of ber.TypeConstructed and the Class of ClassContext. As soon as any of
|
||||
// these conditions is not true we can skip this child.
|
||||
@@ -105,11 +110,11 @@ func getReferral(err error, packet *ber.Packet) (referral string) {
|
||||
// malicious server can send an empty SEQUENCE. Skip it instead of indexing
|
||||
// child.Children[0], which would panic the goroutine that called Modify or
|
||||
// PasswordModify.
|
||||
if len(child.Children) == 0 {
|
||||
uriChild, err := packetChild(child, 0)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if referral, ok = child.Children[0].Value.(string); ok {
|
||||
if referral, err := packetString(uriChild); err == nil {
|
||||
return referral
|
||||
}
|
||||
}
|
||||
|
||||
+92
-33
@@ -140,60 +140,48 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
|
||||
ber.PrintPacket(packet)
|
||||
}
|
||||
|
||||
switch packet.Children[1].Tag {
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
|
||||
switch protocolOp.Tag {
|
||||
case ApplicationSearchResultEntry:
|
||||
result := &SearchSingleResult{
|
||||
Entry: &Entry{
|
||||
DN: packet.Children[1].Children[0].Value.(string),
|
||||
Attributes: unpackAttributes(packet.Children[1].Children[1].Children),
|
||||
},
|
||||
}
|
||||
if len(packet.Children) != 3 {
|
||||
if !r.send(ctx, result) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
decoded, err := DecodeControl(packet.Children[2].Children[0])
|
||||
result, err := decodeSearchResultEntry(packet)
|
||||
if err != nil {
|
||||
werr := fmt.Errorf("failed to decode search result entry: %w", err)
|
||||
result.Error = werr
|
||||
r.send(ctx, result)
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
result.Controls = append(result.Controls, decoded)
|
||||
if !r.send(ctx, result) {
|
||||
return
|
||||
}
|
||||
|
||||
case ApplicationSearchResultDone:
|
||||
if err := GetLDAPError(packet); err != nil {
|
||||
result, err := decodeSearchResultDone(packet)
|
||||
if err != nil {
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
if len(packet.Children) == 3 {
|
||||
result := &SearchSingleResult{}
|
||||
for _, child := range packet.Children[2].Children {
|
||||
decodedChild, err := DecodeControl(child)
|
||||
if err != nil {
|
||||
werr := fmt.Errorf("failed to decode child control: %w", err)
|
||||
r.send(ctx, &SearchSingleResult{Error: werr})
|
||||
return
|
||||
}
|
||||
result.Controls = append(result.Controls, decodedChild)
|
||||
if result != nil {
|
||||
if !r.send(ctx, result) {
|
||||
return
|
||||
}
|
||||
r.send(ctx, result)
|
||||
}
|
||||
foundSearchSingleResultDone = true
|
||||
|
||||
case ApplicationSearchResultReference:
|
||||
ref := packet.Children[1].Children[0].Value.(string)
|
||||
ref, err := packetStringAt(protocolOp, 0)
|
||||
if err != nil {
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
if !r.send(ctx, &SearchSingleResult{Referral: ref}) {
|
||||
return
|
||||
}
|
||||
|
||||
case ApplicationIntermediateResponse:
|
||||
decoded, err := DecodeControl(packet.Children[1])
|
||||
decoded, err := DecodeControl(protocolOp)
|
||||
if err != nil {
|
||||
werr := fmt.Errorf("failed to decode intermediate response: %w", err)
|
||||
r.send(ctx, &SearchSingleResult{Error: werr})
|
||||
@@ -206,7 +194,7 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
|
||||
}
|
||||
|
||||
default:
|
||||
err := fmt.Errorf("unknown tag: %d", packet.Children[1].Tag)
|
||||
err := fmt.Errorf("unknown tag: %d", protocolOp.Tag)
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
@@ -216,6 +204,77 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
|
||||
}()
|
||||
}
|
||||
|
||||
// decodeSearchResultEntry decodes a SearchResultEntry envelope, including any
|
||||
// response controls. It is kept out of the network loop so the full response
|
||||
// decoder can be exercised directly by the fuzz targets.
|
||||
func decodeSearchResultEntry(packet *ber.Packet) (*SearchSingleResult, error) {
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attributesChild, err := packetChild(protocolOp, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attributes, err := unpackAttributes(attributesChild.Children)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dn, err := packetStringAt(protocolOp, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &SearchSingleResult{
|
||||
Entry: &Entry{
|
||||
DN: dn,
|
||||
Attributes: attributes,
|
||||
},
|
||||
}
|
||||
controlsChild, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return result, nil
|
||||
}
|
||||
for _, controlChild := range controlsChild.Children {
|
||||
decoded, err := DecodeControl(controlChild)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode search result entry: %w", err)
|
||||
}
|
||||
result.Controls = append(result.Controls, decoded)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// decodeSearchResultDone decodes a SearchResultDone envelope. It returns a nil
|
||||
// result with a nil error when the response carries no controls, so the caller
|
||||
// does not enqueue an empty result.
|
||||
func decodeSearchResultDone(packet *ber.Packet) (*SearchSingleResult, error) {
|
||||
if err := GetLDAPError(packet); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
controlsChild, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
result := &SearchSingleResult{}
|
||||
for _, child := range controlsChild.Children {
|
||||
decodedChild, err := DecodeControl(child)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode child control: %w", err)
|
||||
}
|
||||
result.Controls = append(result.Controls, decodedChild)
|
||||
}
|
||||
if len(result.Controls) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func newSearchResponse(conn *Conn, bufferSize int) *searchResponse {
|
||||
var ch chan *SearchSingleResult
|
||||
if bufferSize > 0 {
|
||||
|
||||
+101
-25
@@ -245,7 +245,7 @@ func readTag(f reflect.StructField) (string, bool) {
|
||||
// if err := result.Unmarshal(&user); err != nil {
|
||||
// // ...
|
||||
// }
|
||||
func (e *Entry) Unmarshal(i interface{}) (err error) {
|
||||
func (e *Entry) Unmarshal(i any) (err error) {
|
||||
return e.UnmarshalFunc(i, func(entry *Entry, ft reflect.StructField, fv reflect.Value) error {
|
||||
// omitempty can be safely discarded, as it's not needed when unmarshalling
|
||||
fieldTag, _ := readTag(ft)
|
||||
@@ -307,10 +307,10 @@ func (e *Entry) Unmarshal(i interface{}) (err error) {
|
||||
|
||||
// UnmarshalFunc allows you to define a custom unmarshaler to parse an Entry values.
|
||||
// A custom unmarshaler can be found in the Unmarshal function or in the test files.
|
||||
func (e *Entry) UnmarshalFunc(i interface{},
|
||||
func (e *Entry) UnmarshalFunc(i any,
|
||||
fn func(entry *Entry, fieldType reflect.StructField, fieldValue reflect.Value) error) error {
|
||||
// Make sure it's a ptr
|
||||
if vo := reflect.ValueOf(i).Kind(); vo != reflect.Ptr {
|
||||
if vo := reflect.ValueOf(i).Kind(); vo != reflect.Pointer {
|
||||
return fmt.Errorf("ldap: cannot use %s, expected pointer to a struct", vo)
|
||||
}
|
||||
|
||||
@@ -377,6 +377,22 @@ type SearchResult struct {
|
||||
Referrals []string
|
||||
// Controls are the returned controls
|
||||
Controls []Control
|
||||
// ResultCode is the LDAP resultCode from SearchResultDone (0 = success).
|
||||
// Populated even on success so callers can inspect it alongside DiagnosticMessage.
|
||||
//
|
||||
// Note: for paged searches (SearchWithPaging), appendTo overwrites this field
|
||||
// on each page, so only the last page's ResultCode is preserved.
|
||||
// SearchAsync does not populate this field.
|
||||
ResultCode uint16
|
||||
// DiagnosticMessage is the server's free-text message from SearchResultDone.
|
||||
// Per RFC 4511, this may be set even when resultCode is 0 (success).
|
||||
// GetLDAPError returns nil on success and does not expose this field;
|
||||
// it is preserved here so callers can log or act on it.
|
||||
//
|
||||
// Note: for paged searches (SearchWithPaging), appendTo overwrites this field
|
||||
// on each page, so only the last page's DiagnosticMessage is preserved.
|
||||
// SearchAsync does not populate this field.
|
||||
DiagnosticMessage string
|
||||
}
|
||||
|
||||
// Print outputs a human-readable description
|
||||
@@ -398,6 +414,8 @@ func (s *SearchResult) appendTo(r *SearchResult) {
|
||||
r.Entries = append(r.Entries, s.Entries...)
|
||||
r.Referrals = append(r.Referrals, s.Referrals...)
|
||||
r.Controls = append(r.Controls, s.Controls...)
|
||||
r.ResultCode = s.ResultCode
|
||||
r.DiagnosticMessage = s.DiagnosticMessage
|
||||
}
|
||||
|
||||
// SearchSingleResult holds the server's single entry response to a search request
|
||||
@@ -583,7 +601,12 @@ func (l *Conn) Search(searchRequest *SearchRequest) (*SearchResult, error) {
|
||||
return result, err
|
||||
}
|
||||
|
||||
switch packet.Children[1].Tag {
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
switch protocolOp.Tag {
|
||||
case 4:
|
||||
if searchRequest.EnforceSizeLimit &&
|
||||
searchRequest.SizeLimit > 0 &&
|
||||
@@ -591,32 +614,59 @@ func (l *Conn) Search(searchRequest *SearchRequest) (*SearchResult, error) {
|
||||
return result, ErrSizeLimitExceeded
|
||||
}
|
||||
|
||||
attr := make([]*ber.Packet, 0)
|
||||
if len(packet.Children[1].Children) > 1 {
|
||||
attr = packet.Children[1].Children[1].Children
|
||||
// RFC 4511 declares SearchResultEntry ::= [APPLICATION 4] SEQUENCE {
|
||||
// objectName LDAPDN, attributes PartialAttributeList }, and
|
||||
// PartialAttributeList is a SEQUENCE OF, so the attributes element
|
||||
// must be present even when it is empty. Both search paths treat a
|
||||
// missing element as malformed.
|
||||
attributesChild, err := packetChild(protocolOp, 1)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
attributes, err := unpackAttributes(attributesChild.Children)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
dn, err := packetStringAt(protocolOp, 0)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
entry := &Entry{
|
||||
DN: packet.Children[1].Children[0].Value.(string),
|
||||
Attributes: unpackAttributes(attr),
|
||||
DN: dn,
|
||||
Attributes: attributes,
|
||||
}
|
||||
result.Entries = append(result.Entries, entry)
|
||||
case 5:
|
||||
rc, _, diag, parseErr := parseLDAPResult(packet)
|
||||
if parseErr != nil {
|
||||
return result, NewError(ErrorNetwork, fmt.Errorf("malformed SearchResultDone: %w", parseErr))
|
||||
}
|
||||
result.ResultCode = rc
|
||||
result.DiagnosticMessage = diag
|
||||
err := GetLDAPError(packet)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
if len(packet.Children) == 3 {
|
||||
for _, child := range packet.Children[2].Children {
|
||||
controlsChild, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
if ok {
|
||||
for _, child := range controlsChild.Children {
|
||||
decodedChild, err := DecodeControl(child)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("failed to decode child control: %s", err)
|
||||
return result, fmt.Errorf("failed to decode child control: %w", err)
|
||||
}
|
||||
result.Controls = append(result.Controls, decodedChild)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
case 19:
|
||||
result.Referrals = append(result.Referrals, packet.Children[1].Children[0].Value.(string))
|
||||
ref, err := packetStringAt(protocolOp, 0)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.Referrals = append(result.Referrals, ref)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -653,26 +703,52 @@ func (l *Conn) Syncrepl(
|
||||
|
||||
// unpackAttributes will extract all given LDAP attributes and it's values
|
||||
// from the ber.Packet
|
||||
func unpackAttributes(children []*ber.Packet) []*EntryAttribute {
|
||||
entries := make([]*EntryAttribute, len(children))
|
||||
for i, child := range children {
|
||||
length := len(child.Children[1].Children)
|
||||
func unpackAttributes(children []*ber.Packet) ([]*EntryAttribute, error) {
|
||||
entries := make([]*EntryAttribute, 0, len(children))
|
||||
for _, child := range children {
|
||||
// A conforming PartialAttribute is SEQUENCE { type, vals SET OF value }.
|
||||
// A non-conforming or malicious server can omit the vals element or send
|
||||
// a non-string type/value; return an error instead of panicking the
|
||||
// search goroutine, so the caller can handle it.
|
||||
if child == nil {
|
||||
return nil, malformedf("malformed attribute: nil attribute")
|
||||
}
|
||||
nameChild, err := packetChild(child, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap: malformed attribute: %w", err)
|
||||
}
|
||||
valuesChild, err := packetChild(child, 1)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap: malformed attribute: %w", err)
|
||||
}
|
||||
name, err := packetString(nameChild)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap: malformed attribute: type is not a string: %T: %w", nameChild.Value, err)
|
||||
}
|
||||
values := valuesChild.Children
|
||||
entry := &EntryAttribute{
|
||||
Name: child.Children[0].Value.(string),
|
||||
Name: name,
|
||||
// pre-allocate the slice since we can determine
|
||||
// the number of attributes at this point
|
||||
Values: make([]string, length),
|
||||
ByteValues: make([][]byte, length),
|
||||
Values: make([]string, len(values)),
|
||||
ByteValues: make([][]byte, len(values)),
|
||||
}
|
||||
|
||||
for i, value := range child.Children[1].Children {
|
||||
for i, value := range values {
|
||||
if value == nil {
|
||||
return nil, malformedf("malformed attribute %q: value is nil", name)
|
||||
}
|
||||
v, err := packetString(value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap: malformed attribute %q: value is not a string: %T: %w", name, value.Value, err)
|
||||
}
|
||||
entry.ByteValues[i] = value.ByteValue
|
||||
entry.Values[i] = value.Value.(string)
|
||||
entry.Values[i] = v
|
||||
}
|
||||
entries[i] = entry
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
|
||||
return entries
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
// DirSync does a Search with dirSync Control.
|
||||
@@ -717,7 +793,7 @@ func (l *Conn) DirSync(
|
||||
return searchResult, nil
|
||||
}
|
||||
|
||||
// DirSyncDirSyncAsync performs a search request and returns all search results
|
||||
// DirSyncAsync performs a search request and returns all search results
|
||||
// asynchronously. This is efficient when the server returns lots of entries.
|
||||
func (l *Conn) DirSyncAsync(
|
||||
ctx context.Context, searchRequest *SearchRequest, bufferSize int,
|
||||
|
||||
+30
-5
@@ -95,6 +95,11 @@ type advancedState struct {
|
||||
index int
|
||||
hashMatch [maxMatchLength + minMatchLength]uint32
|
||||
|
||||
// litBits[i] is the number of bits needed to encode window[index:i]
|
||||
// as literals, where index is the window index at the start of the
|
||||
// current deflateLazy call. Only allocated when d.chain > 100 (level 9).
|
||||
litBits []int32
|
||||
|
||||
// Input hash chains
|
||||
// hashHead[hashValue] contains the largest inputIndex with the specified hash value
|
||||
// If hashHead[hashValue] is within the current window, then
|
||||
@@ -284,7 +289,9 @@ func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, of
|
||||
minIndex := max(pos-windowSize, 0)
|
||||
offset = 0
|
||||
|
||||
if d.chain < 100 {
|
||||
// The gain estimate below needs the tables that deflateLazy only
|
||||
// generates when d.chain > 100, so the conditions must match.
|
||||
if d.chain <= 100 {
|
||||
for i := prevHead; tries > 0; tries-- {
|
||||
if wEnd == win[i+length] {
|
||||
n := matchLen(win[i:i+minMatchLook], wPos)
|
||||
@@ -312,21 +319,25 @@ func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, of
|
||||
}
|
||||
|
||||
// Minimum gain to accept a match.
|
||||
cGain := 4
|
||||
cGain := int32(4)
|
||||
|
||||
// Some like it higher (CSV), some like it lower (JSON)
|
||||
const baseCost = 3
|
||||
// Base is 4 bytes at with an additional cost.
|
||||
// Matches must be better than this.
|
||||
|
||||
s := d.state
|
||||
hashPrev := &s.hashPrev
|
||||
hashOffset := s.hashOffset
|
||||
litBits := s.litBits[pos : pos+minMatchLook+1]
|
||||
|
||||
for i := prevHead; tries > 0; tries-- {
|
||||
if wEnd == win[i+length] {
|
||||
n := matchLen(win[i:i+minMatchLook], wPos)
|
||||
if n > length {
|
||||
// Calculate gain. Estimate
|
||||
newGain := d.h.bitLengthRaw(wPos[:n]) - int(offsetExtraBits[offsetCode(uint32(pos-i))]) - baseCost - int(lengthExtraBits[lengthCodes[(n-3)&255]])
|
||||
newGain := litBits[n] - litBits[0] - int32(offsetExtraBits[offsetCode(uint32(pos-i))]) - baseCost - int32(lengthExtraBits[lengthCodes[(n-3)&255]])
|
||||
|
||||
//fmt.Println("gain:", newGain, "prev:", cGain, "raw:", d.h.bitLengthRaw(wPos[:n]), "this-len:", n, "prev-len:", length)
|
||||
if newGain > cGain {
|
||||
length = n
|
||||
offset = pos - i
|
||||
@@ -344,7 +355,7 @@ func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, of
|
||||
// hashPrev[i & windowMask] has already been overwritten, so stop now.
|
||||
break
|
||||
}
|
||||
i = int(d.state.hashPrev[i&windowMask]) - d.state.hashOffset
|
||||
i = int(hashPrev[i&windowMask]) - hashOffset
|
||||
if i < minIndex {
|
||||
break
|
||||
}
|
||||
@@ -428,6 +439,20 @@ func (d *compressor) deflateLazy() {
|
||||
tmp[v]++
|
||||
}
|
||||
d.h.generate(tmp[:], 15)
|
||||
|
||||
// Compute the cumulative cost of encoding the window as literals,
|
||||
// so findMatch can look up the cost of any range in constant time.
|
||||
if s.litBits == nil {
|
||||
s.litBits = make([]int32, 2*windowSize+1)
|
||||
}
|
||||
codes := d.h.codes[:256]
|
||||
litBits := s.litBits[s.index : d.windowEnd+1]
|
||||
total := int32(0)
|
||||
litBits[0] = 0
|
||||
for i, v := range d.window[s.index:d.windowEnd] {
|
||||
total += int32(codes[v].len())
|
||||
litBits[i+1] = total
|
||||
}
|
||||
}
|
||||
|
||||
s.maxInsertIndex = d.windowEnd - (minMatchLength - 1)
|
||||
|
||||
+94
-128
@@ -32,14 +32,12 @@ const (
|
||||
|
||||
// bufferFlushSize indicates the buffer size
|
||||
// after which bytes are flushed to the writer.
|
||||
// Should preferably be a multiple of 6, since
|
||||
// we accumulate 6 bytes between writes to the buffer.
|
||||
// Between checks, at most 7 bytes are added to the buffer,
|
||||
// and writes are done as unconditional 8-byte stores, so the
|
||||
// buffer must have at least bufferFlushSize+7+8 bytes.
|
||||
bufferFlushSize = 246
|
||||
)
|
||||
|
||||
// Minimum length code that emits bits.
|
||||
const lengthExtraBitsMinCode = 8
|
||||
|
||||
// The number of extra bits needed by length code X - LENGTH_CODES_START.
|
||||
var lengthExtraBits = [32]uint8{
|
||||
/* 257 */ 0, 0, 0,
|
||||
@@ -55,9 +53,6 @@ var lengthBase = [32]uint8{
|
||||
64, 80, 96, 112, 128, 160, 192, 224, 255,
|
||||
}
|
||||
|
||||
// Minimum offset code that emits bits.
|
||||
const offsetExtraBitsMinCode = 4
|
||||
|
||||
// offset code word extra bits.
|
||||
var offsetExtraBits = [32]int8{
|
||||
0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
|
||||
@@ -67,8 +62,24 @@ var offsetExtraBits = [32]int8{
|
||||
14, 14,
|
||||
}
|
||||
|
||||
// offsetCombined combines the number of extra bits and the base offset
|
||||
// of each offset code in a single table: extra bits in the low 8 bits,
|
||||
// and the base offset (already reduced by baseMatchOffset) in the upper bits.
|
||||
// Entries for the extended window codes 30 and 31 are unused.
|
||||
var offsetCombined = [32]uint32{}
|
||||
|
||||
// lengthCombined combines, for each match length (reduced by
|
||||
// baseMatchLength), the length code (relative to lengthCodesStart) in
|
||||
// bits 0-4, the number of extra bits in bits 5-7 and the value of the
|
||||
// extra bits in bits 8-12.
|
||||
var lengthCombined = func() (t [256]uint32) {
|
||||
for i := range t {
|
||||
code := lengthCodes[i]
|
||||
t[i] = uint32(code) | uint32(lengthExtraBits[code])<<5 | uint32(uint8(i)-lengthBase[code])<<8
|
||||
}
|
||||
return t
|
||||
}()
|
||||
|
||||
func init() {
|
||||
var offsetBase = [32]uint32{
|
||||
/* normal deflate */
|
||||
@@ -85,7 +96,7 @@ func init() {
|
||||
|
||||
for i := range offsetCombined[:] {
|
||||
// Don't use extended window values...
|
||||
if offsetExtraBits[i] == 0 || offsetBase[i] > 0x006000 {
|
||||
if offsetBase[i] > 0x006000 {
|
||||
continue
|
||||
}
|
||||
offsetCombined[i] = uint32(offsetExtraBits[i]) | (offsetBase[i] << 8)
|
||||
@@ -115,10 +126,14 @@ type huffmanBitWriter struct {
|
||||
lastHeader int
|
||||
// Set between 0 (reused block can be up to 2x the size)
|
||||
logNewTablePenalty uint
|
||||
bytes [256 + 8]byte
|
||||
literalFreq [lengthCodesStart + 32]uint16
|
||||
offsetFreq [32]uint16
|
||||
codegenFreq [codegenCodeCount]uint16
|
||||
|
||||
// bytes must hold at least bufferFlushSize+7+8 bytes (see bufferFlushSize).
|
||||
// Its size is rounded up to a multiple of 8 to keep the following
|
||||
// fields aligned, which is measurably faster in writeBlockHuff.
|
||||
bytes [(bufferFlushSize + 7 + 8 + 7) &^ 7]byte
|
||||
literalFreq [lengthCodesStart + 32]uint16
|
||||
offsetFreq [32]uint16
|
||||
codegenFreq [codegenCodeCount]uint16
|
||||
|
||||
// codegen must have an extra space for the final symbol.
|
||||
codegen [literalCount + offsetCodeCount + 1]uint8
|
||||
@@ -842,124 +857,75 @@ func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode)
|
||||
lengths := leCodes[lengthCodesStart:]
|
||||
lengths = lengths[:32]
|
||||
|
||||
// Go 1.16 LOVES having these on stack.
|
||||
// Keeping these on the stack instead of in w is significantly faster.
|
||||
bits, nbits, nbytes := w.bits, w.nbits, w.nbytes
|
||||
|
||||
for _, t := range tokens {
|
||||
// Flush whole bytes, so that nbits <= 7 when entering the loop below.
|
||||
le.Store64(w.bytes[:], nbytes, bits)
|
||||
nbytes += nbits >> 3
|
||||
bits >>= nbits & 56
|
||||
nbits &= 7
|
||||
if nbytes >= bufferFlushSize {
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
if w.err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// The loop below flushes whole bytes at the end of every iteration,
|
||||
// so that nbits <= 7 at the top of every iteration.
|
||||
// A literal adds at most 15 bits and a match at most
|
||||
// 15+5+15+13 = 48 bits, so up to three literals or a single match
|
||||
// can be added to the 64-bit accumulator without an intermediate flush.
|
||||
// Unconditionally storing 8 bytes and advancing by the number of
|
||||
// whole bytes avoids a poorly predicted branch per token.
|
||||
for i := 0; i < len(tokens); i++ {
|
||||
t := tokens[i]
|
||||
if t < 256 {
|
||||
//w.writeCode(lits[t.literal()])
|
||||
c := lits[t]
|
||||
bits |= c.code64() << (nbits & 63)
|
||||
nbits += c.len()
|
||||
if nbits >= 48 {
|
||||
le.Store64(w.bytes[:], nbytes, bits)
|
||||
bits >>= 48
|
||||
nbits -= 48
|
||||
nbytes += 6
|
||||
if nbytes >= bufferFlushSize {
|
||||
if w.err != nil {
|
||||
nbytes = 0
|
||||
return
|
||||
}
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
// Add up to two more literals before flushing.
|
||||
if i+1 < len(tokens) && tokens[i+1] < 256 {
|
||||
i++
|
||||
c := lits[tokens[i]]
|
||||
bits |= c.code64() << (nbits & 63)
|
||||
nbits += c.len()
|
||||
if i+1 < len(tokens) && tokens[i+1] < 256 {
|
||||
i++
|
||||
c := lits[tokens[i]]
|
||||
bits |= c.code64() << (nbits & 63)
|
||||
nbits += c.len()
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Write the length
|
||||
length := t.length()
|
||||
lengthCode := lengthCode(length) & 31
|
||||
if false {
|
||||
w.writeCode(lengths[lengthCode])
|
||||
} else {
|
||||
// inlined
|
||||
c := lengths[lengthCode]
|
||||
bits |= c.code64() << (nbits & 63)
|
||||
nbits += c.len()
|
||||
if nbits >= 48 {
|
||||
le.Store64(w.bytes[:], nbytes, bits)
|
||||
bits >>= 48
|
||||
nbits -= 48
|
||||
nbytes += 6
|
||||
if nbytes >= bufferFlushSize {
|
||||
if w.err != nil {
|
||||
nbytes = 0
|
||||
return
|
||||
}
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
// Write the length code and its extra bits as one unit.
|
||||
lc := lengthCombined[t.length()]
|
||||
c := lengths[lc&31]
|
||||
bits |= (c.code64() | uint64(lc>>8)<<(c.len()&63)) << (nbits & 63)
|
||||
nbits += c.len() + uint8(lc>>5)&7
|
||||
|
||||
if lengthCode >= lengthExtraBitsMinCode {
|
||||
extraLengthBits := lengthExtraBits[lengthCode]
|
||||
//w.writeBits(extraLength, extraLengthBits)
|
||||
extraLength := int32(length - lengthBase[lengthCode])
|
||||
bits |= uint64(extraLength) << (nbits & 63)
|
||||
nbits += extraLengthBits
|
||||
if nbits >= 48 {
|
||||
le.Store64(w.bytes[:], nbytes, bits)
|
||||
bits >>= 48
|
||||
nbits -= 48
|
||||
nbytes += 6
|
||||
if nbytes >= bufferFlushSize {
|
||||
if w.err != nil {
|
||||
nbytes = 0
|
||||
return
|
||||
}
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
}
|
||||
}
|
||||
// Write the offset code and its extra bits as one unit.
|
||||
offset := t.offset()
|
||||
offCode := (offset >> 16) & 31
|
||||
c = offs[offCode]
|
||||
offComb := offsetCombined[offCode]
|
||||
extra := (offset - (offComb >> 8)) & matchOffsetOnlyMask
|
||||
bits |= (c.code64() | uint64(extra)<<(c.len()&63)) << (nbits & 63)
|
||||
nbits += c.len() + uint8(offComb)
|
||||
}
|
||||
// Write the offset
|
||||
offset := t.offset()
|
||||
offsetCode := (offset >> 16) & 31
|
||||
if false {
|
||||
w.writeCode(offs[offsetCode])
|
||||
} else {
|
||||
// inlined
|
||||
c := offs[offsetCode]
|
||||
bits |= c.code64() << (nbits & 63)
|
||||
nbits += c.len()
|
||||
if nbits >= 48 {
|
||||
le.Store64(w.bytes[:], nbytes, bits)
|
||||
bits >>= 48
|
||||
nbits -= 48
|
||||
nbytes += 6
|
||||
if nbytes >= bufferFlushSize {
|
||||
if w.err != nil {
|
||||
nbytes = 0
|
||||
return
|
||||
}
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if offsetCode >= offsetExtraBitsMinCode {
|
||||
offsetComb := offsetCombined[offsetCode]
|
||||
//w.writeBits(extraOffset, extraOffsetBits)
|
||||
bits |= uint64((offset-(offsetComb>>8))&matchOffsetOnlyMask) << (nbits & 63)
|
||||
nbits += uint8(offsetComb)
|
||||
if nbits >= 48 {
|
||||
le.Store64(w.bytes[:], nbytes, bits)
|
||||
bits >>= 48
|
||||
nbits -= 48
|
||||
nbytes += 6
|
||||
if nbytes >= bufferFlushSize {
|
||||
if w.err != nil {
|
||||
nbytes = 0
|
||||
return
|
||||
}
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
}
|
||||
le.Store64(w.bytes[:], nbytes, bits)
|
||||
nbytes += nbits >> 3
|
||||
bits >>= nbits & 56
|
||||
nbits &= 7
|
||||
if nbytes >= bufferFlushSize {
|
||||
if w.err != nil {
|
||||
nbytes = 0
|
||||
return
|
||||
}
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
}
|
||||
}
|
||||
// Restore...
|
||||
@@ -1094,8 +1060,8 @@ func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) {
|
||||
if debugDeflate {
|
||||
count -= int(nbytes)*8 + int(nbits)
|
||||
}
|
||||
// Unroll, write 3 codes/loop.
|
||||
// Fastest number of unrolls.
|
||||
// Write 3 codes per iteration. The three codes are combined first,
|
||||
// independently of the accumulator, and merged with a single shift.
|
||||
for len(input) > 3 {
|
||||
// We must have at least 48 bits free.
|
||||
if nbits >= 8 {
|
||||
@@ -1116,13 +1082,13 @@ func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) {
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
}
|
||||
a, b := encoding[input[0]], encoding[input[1]]
|
||||
bits |= a.code64() << (nbits & 63)
|
||||
bits |= b.code64() << ((nbits + a.len()) & 63)
|
||||
c := encoding[input[2]]
|
||||
nbits += b.len() + a.len()
|
||||
bits |= c.code64() << (nbits & 63)
|
||||
nbits += c.len()
|
||||
a, b, c := encoding[input[0]], encoding[input[1]], encoding[input[2]]
|
||||
v := a.code64() | b.code64()<<(a.len()&63)
|
||||
n := a.len() + b.len()
|
||||
v |= c.code64() << (n & 63)
|
||||
n += c.len()
|
||||
bits |= v << (nbits & 63)
|
||||
nbits += n
|
||||
input = input[3:]
|
||||
}
|
||||
|
||||
|
||||
+102
-36
@@ -38,6 +38,9 @@ type huffmanEncoder struct {
|
||||
// Possible lengths are codegenCodeCount, offsetCodeCount and literalCount.
|
||||
// The largest of these is literalCount, so we allocate for that case.
|
||||
freqcache [literalCount + 1]literalNode
|
||||
|
||||
// sortcache is scratch space for sortByFreq.
|
||||
sortcache [literalCount + 1]literalNode
|
||||
}
|
||||
|
||||
type literalNode struct {
|
||||
@@ -139,14 +142,6 @@ func (h *huffmanEncoder) bitLength(freq []uint16) int {
|
||||
return total
|
||||
}
|
||||
|
||||
func (h *huffmanEncoder) bitLengthRaw(b []byte) int {
|
||||
var total int
|
||||
for _, f := range b {
|
||||
total += int(h.codes[f].len())
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// canReuseBits returns the number of bits or math.MaxInt32 if the encoder cannot be reused.
|
||||
func (h *huffmanEncoder) canReuseBits(freq []uint16) int {
|
||||
var total int
|
||||
@@ -309,27 +304,93 @@ func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32 {
|
||||
}
|
||||
|
||||
// Look at the leaves and assign them a bit count and an encoding as specified
|
||||
// in RFC 1951 3.2.2
|
||||
func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalNode) {
|
||||
code := uint16(0)
|
||||
// in RFC 1951 3.2.2.
|
||||
// list must be sorted by increasing frequency and codes must have
|
||||
// all entries for literals not in list set to zero.
|
||||
func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalNode, codes []hcode) {
|
||||
// The literals list[len(list)-bits] .. list[len(list)-1]
|
||||
// are encoded using "bits" bits. Record the length of each literal
|
||||
// temporarily in codes.
|
||||
for n, bits := range bitCount {
|
||||
code <<= 1
|
||||
if n == 0 || bits == 0 {
|
||||
continue
|
||||
}
|
||||
// The literals list[len(list)-bits] .. list[len(list)-bits]
|
||||
// are encoded using "bits" bits, and get the values
|
||||
// code, code + 1, .... The code values are
|
||||
// assigned in literal order (not frequency order).
|
||||
chunk := list[len(list)-int(bits):]
|
||||
|
||||
sortByLiteral(chunk)
|
||||
for _, node := range chunk {
|
||||
h.codes[node.literal] = newhcode(reverseBits(code, uint8(n)), uint8(n))
|
||||
code++
|
||||
for _, node := range list[len(list)-int(bits):] {
|
||||
codes[node.literal] = hcode(n)
|
||||
}
|
||||
list = list[0 : len(list)-int(bits)]
|
||||
}
|
||||
|
||||
// Code values are assigned in literal order (not frequency order)
|
||||
// within each code length, starting from the first code of each length.
|
||||
var nextCode [maxBitsLimit]uint16
|
||||
code := uint16(0)
|
||||
for n := 1; n < len(bitCount); n++ {
|
||||
code = (code + uint16(bitCount[n-1])) << 1
|
||||
nextCode[n] = code
|
||||
}
|
||||
for i, c := range codes {
|
||||
if c == 0 {
|
||||
continue
|
||||
}
|
||||
// n is at most maxBitsLimit-1; the mask only elides bounds checks.
|
||||
n := uint8(c)
|
||||
codes[i] = newhcode(reverseBits(nextCode[n&15], n), n)
|
||||
nextCode[n&15]++
|
||||
}
|
||||
}
|
||||
|
||||
// sortByFreq sorts list by increasing frequency.
|
||||
// The sort is stable, so nodes with equal frequencies keep their order.
|
||||
func (h *huffmanEncoder) sortByFreq(list []literalNode) {
|
||||
if len(list) <= 32 {
|
||||
// Insertion sort is faster for small lists.
|
||||
for i := 1; i < len(list); i++ {
|
||||
n := list[i]
|
||||
j := i
|
||||
for ; j > 0 && list[j-1].freq > n.freq; j-- {
|
||||
list[j] = list[j-1]
|
||||
}
|
||||
list[j] = n
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Counting sort on the low byte and then on the high byte
|
||||
// of the frequency. Both passes are stable.
|
||||
tmp := h.sortcache[:len(list)]
|
||||
var count [256]uint16
|
||||
var maxFreq uint16
|
||||
for _, n := range list {
|
||||
count[n.freq&0xff]++
|
||||
maxFreq |= n.freq
|
||||
}
|
||||
var pos uint16
|
||||
for i, c := range count {
|
||||
count[i] = pos
|
||||
pos += c
|
||||
}
|
||||
for _, n := range list {
|
||||
tmp[count[n.freq&0xff]] = n
|
||||
count[n.freq&0xff]++
|
||||
}
|
||||
if maxFreq < 256 {
|
||||
copy(list, tmp)
|
||||
return
|
||||
}
|
||||
count = [256]uint16{}
|
||||
for _, n := range tmp {
|
||||
count[n.freq>>8]++
|
||||
}
|
||||
pos = 0
|
||||
for i, c := range count {
|
||||
count[i] = pos
|
||||
pos += c
|
||||
}
|
||||
for _, n := range tmp {
|
||||
list[count[n.freq>>8]] = n
|
||||
count[n.freq>>8]++
|
||||
}
|
||||
}
|
||||
|
||||
// Update this Huffman Code object to be the minimum code for the specified frequency count.
|
||||
@@ -362,12 +423,14 @@ func (h *huffmanEncoder) generate(freq []uint16, maxBits int32) {
|
||||
}
|
||||
return
|
||||
}
|
||||
sortByFreq(list)
|
||||
// list is in order of increasing literal value, so a stable sort
|
||||
// by frequency orders it by (frequency, literal).
|
||||
h.sortByFreq(list)
|
||||
|
||||
// Get the number of literals for each bit count
|
||||
bitCount := h.bitCounts(list, maxBits)
|
||||
// And do the assignment
|
||||
h.assignEncodingAndSize(bitCount, list)
|
||||
h.assignEncodingAndSize(bitCount, list, codes)
|
||||
}
|
||||
|
||||
// atLeastOne clamps the result between 1 and 15.
|
||||
@@ -394,24 +457,27 @@ func histogram(b []byte, h []uint16) {
|
||||
}
|
||||
|
||||
func histogramSplit(b []byte, h []uint16) {
|
||||
// Tested, and slightly faster than 2-way.
|
||||
// Writing to separate arrays and combining is also slightly slower.
|
||||
h = h[:256]
|
||||
// Walk four quarters in parallel, each into its own table.
|
||||
// Tested to be faster than walking halves. Using separate tables
|
||||
// avoids the load/store dependencies that arise when two of the
|
||||
// streams hit the same byte value, which is common for text.
|
||||
var h0, h1, h2, h3 [256]uint16
|
||||
// Make size divisible by 4
|
||||
for len(b)&3 != 0 {
|
||||
h[b[0]]++
|
||||
h0[b[0]]++
|
||||
b = b[1:]
|
||||
}
|
||||
n := len(b) / 4
|
||||
x, y, z, w := b[:n], b[n:], b[n+n:], b[n+n+n:]
|
||||
y, z, w = y[:len(x)], z[:len(x)], w[:len(x)]
|
||||
for i, t := range x {
|
||||
v0 := &h[t]
|
||||
v1 := &h[y[i]]
|
||||
v2 := &h[z[i]]
|
||||
v3 := &h[w[i]]
|
||||
*v0++
|
||||
*v1++
|
||||
*v2++
|
||||
*v3++
|
||||
h0[t]++
|
||||
h1[y[i]]++
|
||||
h2[z[i]]++
|
||||
h3[w[i]]++
|
||||
}
|
||||
h = h[:256]
|
||||
for i := range h {
|
||||
h[i] += h0[i] + h1[i] + h2[i] + h3[i]
|
||||
}
|
||||
}
|
||||
+15
-15
@@ -120,7 +120,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits n>0:", err)
|
||||
}
|
||||
f.err = err
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -148,7 +148,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<5:", err)
|
||||
}
|
||||
f.err = err
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -216,7 +216,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<nb:", err)
|
||||
}
|
||||
f.err = err
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -371,7 +371,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits n>0:", err)
|
||||
}
|
||||
f.err = err
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -399,7 +399,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<5:", err)
|
||||
}
|
||||
f.err = err
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -467,7 +467,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<nb:", err)
|
||||
}
|
||||
f.err = err
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -638,7 +638,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits n>0:", err)
|
||||
}
|
||||
f.err = err
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -674,7 +674,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<5:", err)
|
||||
}
|
||||
f.err = err
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -757,7 +757,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<nb:", err)
|
||||
}
|
||||
f.err = err
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -918,7 +918,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits n>0:", err)
|
||||
}
|
||||
f.err = err
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -946,7 +946,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<5:", err)
|
||||
}
|
||||
f.err = err
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -1014,7 +1014,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<nb:", err)
|
||||
}
|
||||
f.err = err
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -1169,7 +1169,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits n>0:", err)
|
||||
}
|
||||
f.err = err
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -1197,7 +1197,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<5:", err)
|
||||
}
|
||||
f.err = err
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -1265,7 +1265,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<nb:", err)
|
||||
}
|
||||
f.err = err
|
||||
f.err = noEOF(err)
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
|
||||
+6
-7
@@ -12,18 +12,17 @@ import (
|
||||
// matchLen returns the maximum common prefix length of a and b.
|
||||
// a must be the shortest of the two.
|
||||
func matchLen(a, b []byte) (n int) {
|
||||
left := len(a)
|
||||
for left >= 8 {
|
||||
diff := le.Load64(a, n) ^ le.Load64(b, n)
|
||||
// Keeping a and b the same length and reslicing them as we go
|
||||
// lets the compiler prove that no bounds checks are needed.
|
||||
b = b[:len(a)]
|
||||
for len(a) >= 8 {
|
||||
diff := le.Load64(a, 0) ^ le.Load64(b, 0)
|
||||
if diff != 0 {
|
||||
return n + bits.TrailingZeros64(diff)>>3
|
||||
}
|
||||
a, b = a[8:], b[8:]
|
||||
n += 8
|
||||
left -= 8
|
||||
}
|
||||
|
||||
a = a[n:]
|
||||
b = b[n:]
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
break
|
||||
|
||||
+11
-7
@@ -215,7 +215,11 @@ func mFastLog2(val float32) float32 {
|
||||
ux &= -0x7f800001
|
||||
ux += 127 << 23
|
||||
uval := math.Float32frombits(uint32(ux))
|
||||
log2 += ((-0.34484843)*uval+2.02466578)*uval - 0.67487759
|
||||
|
||||
p := float32(-0.34484843*uval) + 2.02466578
|
||||
q := float32(p*uval) - 0.67487759
|
||||
log2 += q
|
||||
|
||||
return log2
|
||||
}
|
||||
|
||||
@@ -232,7 +236,8 @@ func (t *tokens) EstimatedBits() int {
|
||||
for _, v := range t.litHist[:] {
|
||||
if v > 0 {
|
||||
n := float32(v)
|
||||
shannon += atLeastOne(-mFastLog2(n*invTotal)) * n
|
||||
w := float32(atLeastOne(-mFastLog2(n*invTotal)) * n)
|
||||
shannon += w
|
||||
}
|
||||
}
|
||||
// Just add 15 for EOB
|
||||
@@ -240,7 +245,8 @@ func (t *tokens) EstimatedBits() int {
|
||||
for i, v := range t.extraHist[1 : literalCount-256] {
|
||||
if v > 0 {
|
||||
n := float32(v)
|
||||
shannon += atLeastOne(-mFastLog2(n*invTotal)) * n
|
||||
w := float32(atLeastOne(-mFastLog2(n*invTotal)) * n)
|
||||
shannon += w
|
||||
bits += int(lengthExtraBits[i&31]) * int(v)
|
||||
nMatches += int(v)
|
||||
}
|
||||
@@ -251,7 +257,8 @@ func (t *tokens) EstimatedBits() int {
|
||||
for i, v := range t.offHist[:offsetCodeCount] {
|
||||
if v > 0 {
|
||||
n := float32(v)
|
||||
shannon += atLeastOne(-mFastLog2(n*invTotal)) * n
|
||||
w := float32(atLeastOne(-mFastLog2(n*invTotal)) * n)
|
||||
shannon += w
|
||||
bits += int(offsetExtraBits[i&31]) * int(v)
|
||||
}
|
||||
}
|
||||
@@ -358,9 +365,6 @@ func (t token) offset() uint32 { return uint32(t) & offsetMask }
|
||||
|
||||
func (t token) length() uint8 { return uint8(t >> lengthShift) }
|
||||
|
||||
// Convert length to code.
|
||||
func lengthCode(len uint8) uint8 { return lengthCodes[len] }
|
||||
|
||||
// Returns the offset code corresponding to a specific offset
|
||||
func offsetCode(off uint32) uint32 {
|
||||
if false {
|
||||
|
||||
+63
@@ -9,6 +9,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/bits"
|
||||
|
||||
"github.com/klauspost/compress/internal/le"
|
||||
)
|
||||
@@ -210,6 +211,68 @@ func (b *bitReaderShifted) remaining() uint {
|
||||
return b.off*8 + uint(64-b.bitsRead)
|
||||
}
|
||||
|
||||
// canUseAsm reports whether the reader has a full 8-byte window ahead of
|
||||
// its read pointer, which the Decompress4X asm loops need to take over.
|
||||
func (b *bitReaderShifted) canUseAsm() bool {
|
||||
return b.off >= 8
|
||||
}
|
||||
|
||||
// prepareForAsm establishes the invariant the Decompress4X asm loops rely
|
||||
// on: value == load64(in[off:off+8]) << bitsRead with bitsRead <= 7, so
|
||||
// that a full group of symbols can never shift their sentinel bit out of
|
||||
// the container. init leaves bitsRead == 8 when the final byte of the
|
||||
// stream is exactly 0x01; that whole byte is consumed, so the same position
|
||||
// is the window one byte lower with nothing consumed. Requires canUseAsm.
|
||||
func (b *bitReaderShifted) prepareForAsm() {
|
||||
if b.bitsRead >= 8 {
|
||||
b.off--
|
||||
b.value = le.Load64(b.in, b.off)
|
||||
b.bitsRead -= 8
|
||||
}
|
||||
}
|
||||
|
||||
// restoreFromAsm converts the state left behind by the Decompress4X asm
|
||||
// loops back to the invariant the Go code relies on: value holds the 8
|
||||
// bytes at in[off:off+8] shifted left by bitsRead, with the low bitsRead
|
||||
// bits zero.
|
||||
//
|
||||
// The asm keeps a sentinel bit in value just below the unread bits, so its
|
||||
// trailing zero count is the number of consumed bits. The sentinel is ORed
|
||||
// over the lowest bit of the window, which the loop never consumes before
|
||||
// re-reading memory, so the window is re-read here too rather than taken
|
||||
// from value. The asm reports off as the signed distance from the start of
|
||||
// the stream, and it can be negative: a reload always reads a whole 8-byte
|
||||
// window, so a stream that is nearly drained ends with up to 7 bytes of the
|
||||
// previous stream (or the jump table) below its start inside the window.
|
||||
// Those bytes sit below the stream's own bits and count as consumed.
|
||||
// Anything further below, or more bits consumed than the stream holds, is
|
||||
// corruption.
|
||||
func (b *bitReaderShifted) restoreFromAsm() error {
|
||||
off := int(b.off)
|
||||
consumed := uint(bits.TrailingZeros64(b.value))
|
||||
if off < 0 {
|
||||
if off < -7 {
|
||||
return errors.New("corruption detected: stream underrun")
|
||||
}
|
||||
consumed += uint(-off) * 8
|
||||
if consumed > 64 {
|
||||
return errors.New("corruption detected: stream underrun")
|
||||
}
|
||||
off = 0
|
||||
}
|
||||
if off+8 > len(b.in) {
|
||||
return errors.New("corruption detected: stream overrun")
|
||||
}
|
||||
b.off = uint(off)
|
||||
b.bitsRead = uint8(consumed)
|
||||
if consumed >= 64 {
|
||||
b.value = 0
|
||||
} else {
|
||||
b.value = le.Load64(b.in, b.off) << consumed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// close the bitstream and returns an error if out-of-buffer reads occurred.
|
||||
func (b *bitReaderShifted) close() error {
|
||||
// Release reference.
|
||||
|
||||
+87
-8
@@ -8,36 +8,99 @@ import (
|
||||
)
|
||||
|
||||
// decompress4x_main_loop_amd64 is an x86 assembler implementation
|
||||
// of Decompress4X when tablelog > 8.
|
||||
// of Decompress4X when tablelog > 8, decoding fastSymbols symbols per
|
||||
// stream between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_main_loop_amd64(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_8b_main_loop_amd64 is an x86 assembler implementation
|
||||
// of Decompress4X when tablelog <= 8 which decodes 4 entries
|
||||
// per loop.
|
||||
// of Decompress4X when tablelog <= 8, decoding fast8bSymbols symbols
|
||||
// per stream between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_8b_main_loop_amd64(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_4b_main_loop_amd64 is an x86 assembler implementation
|
||||
// of Decompress4X when tablelog <= 4, decoding fast4bSymbols symbols
|
||||
// per stream between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_4b_main_loop_amd64(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_4b_main_loop_bmi2 is the BMI2 twin of decompress4x_4b_main_loop_amd64.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_4b_main_loop_bmi2(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_main_loop_bmi2 is the BMI2 twin of decompress4x_main_loop_amd64.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_main_loop_bmi2(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_8b_main_loop_bmi2 is the BMI2 twin of decompress4x_8b_main_loop_amd64.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_8b_main_loop_bmi2(ctx *decompress4xContext)
|
||||
|
||||
// decompress1x_main_loop_amd64 is an x86 assembler implementation
|
||||
// of Decompress1X when tablelog > 8.
|
||||
// of Decompress1X when tablelog > 8, decoding fastSymbols symbols
|
||||
// between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_main_loop_amd64(ctx *decompress1xContext)
|
||||
|
||||
// decompress1x_main_loop_bmi2 is an x86 with BMI2 assembler implementation
|
||||
// of Decompress1X when tablelog > 8.
|
||||
// decompress1x_8b_main_loop_amd64 is an x86 assembler implementation
|
||||
// of Decompress1X when tablelog <= 8, decoding fast8bSymbols symbols
|
||||
// between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_8b_main_loop_amd64(ctx *decompress1xContext)
|
||||
|
||||
// decompress1x_4b_main_loop_amd64 is an x86 assembler implementation
|
||||
// of Decompress1X when tablelog <= 4, decoding fast4bSymbols symbols
|
||||
// between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_4b_main_loop_amd64(ctx *decompress1xContext)
|
||||
|
||||
// decompress1x_main_loop_bmi2 is the BMI2 twin of decompress1x_main_loop_amd64.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_main_loop_bmi2(ctx *decompress1xContext)
|
||||
|
||||
// decompress1x_8b_main_loop_bmi2 is the BMI2 twin of decompress1x_8b_main_loop_amd64.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_8b_main_loop_bmi2(ctx *decompress1xContext)
|
||||
|
||||
// decompress1x_4b_main_loop_bmi2 is the BMI2 twin of decompress1x_4b_main_loop_amd64.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_4b_main_loop_bmi2(ctx *decompress1xContext)
|
||||
|
||||
func decompress4x_main_loop_asm(ctx *decompress4xContext) {
|
||||
decompress4x_main_loop_amd64(ctx)
|
||||
if cpuinfo.HasBMI2() {
|
||||
decompress4x_main_loop_bmi2(ctx)
|
||||
} else {
|
||||
decompress4x_main_loop_amd64(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func decompress4x_8b_main_loop_asm(ctx *decompress4xContext) {
|
||||
decompress4x_8b_main_loop_amd64(ctx)
|
||||
if cpuinfo.HasBMI2() {
|
||||
decompress4x_8b_main_loop_bmi2(ctx)
|
||||
} else {
|
||||
decompress4x_8b_main_loop_amd64(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func decompress4x_4b_main_loop_asm(ctx *decompress4xContext) {
|
||||
if cpuinfo.HasBMI2() {
|
||||
decompress4x_4b_main_loop_bmi2(ctx)
|
||||
} else {
|
||||
decompress4x_4b_main_loop_amd64(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func decompress1x_main_loop_asm(ctx *decompress1xContext) {
|
||||
@@ -47,3 +110,19 @@ func decompress1x_main_loop_asm(ctx *decompress1xContext) {
|
||||
decompress1x_main_loop_amd64(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func decompress1x_8b_main_loop_asm(ctx *decompress1xContext) {
|
||||
if cpuinfo.HasBMI2() {
|
||||
decompress1x_8b_main_loop_bmi2(ctx)
|
||||
} else {
|
||||
decompress1x_8b_main_loop_amd64(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func decompress1x_4b_main_loop_asm(ctx *decompress1xContext) {
|
||||
if cpuinfo.HasBMI2() {
|
||||
decompress1x_4b_main_loop_bmi2(ctx)
|
||||
} else {
|
||||
decompress1x_4b_main_loop_amd64(ctx)
|
||||
}
|
||||
}
|
||||
+3329
-773
File diff suppressed because it is too large.
Load diff
+39
-4
@@ -6,24 +6,47 @@
|
||||
package huff0
|
||||
|
||||
// decompress4x_main_loop_arm64 is an arm64 assembler implementation
|
||||
// of Decompress4X when tablelog > 8.
|
||||
// of Decompress4X when tablelog > 8, decoding fastSymbols symbols per
|
||||
// stream between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_main_loop_arm64(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_8b_main_loop_arm64 is an arm64 assembler implementation
|
||||
// of Decompress4X when tablelog <= 8 which decodes 4 entries
|
||||
// per loop.
|
||||
// of Decompress4X when tablelog <= 8, decoding fast8bSymbols symbols
|
||||
// per stream between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_8b_main_loop_arm64(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_4b_main_loop_arm64 is an arm64 assembler implementation
|
||||
// of Decompress4X when tablelog <= 4, decoding fast4bSymbols symbols
|
||||
// per stream between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_4b_main_loop_arm64(ctx *decompress4xContext)
|
||||
|
||||
// decompress1x_main_loop_arm64 is an arm64 assembler implementation
|
||||
// of Decompress1X when tablelog > 8.
|
||||
// of Decompress1X when tablelog > 8, decoding fastSymbols symbols
|
||||
// between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_main_loop_arm64(ctx *decompress1xContext)
|
||||
|
||||
// decompress1x_8b_main_loop_arm64 is an arm64 assembler implementation
|
||||
// of Decompress1X when tablelog <= 8, decoding fast8bSymbols symbols
|
||||
// between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_8b_main_loop_arm64(ctx *decompress1xContext)
|
||||
|
||||
// decompress1x_4b_main_loop_arm64 is an arm64 assembler implementation
|
||||
// of Decompress1X when tablelog <= 4, decoding fast4bSymbols symbols
|
||||
// between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_4b_main_loop_arm64(ctx *decompress1xContext)
|
||||
|
||||
func decompress4x_main_loop_asm(ctx *decompress4xContext) {
|
||||
decompress4x_main_loop_arm64(ctx)
|
||||
}
|
||||
@@ -32,6 +55,18 @@ func decompress4x_8b_main_loop_asm(ctx *decompress4xContext) {
|
||||
decompress4x_8b_main_loop_arm64(ctx)
|
||||
}
|
||||
|
||||
func decompress4x_4b_main_loop_asm(ctx *decompress4xContext) {
|
||||
decompress4x_4b_main_loop_arm64(ctx)
|
||||
}
|
||||
|
||||
func decompress1x_main_loop_asm(ctx *decompress1xContext) {
|
||||
decompress1x_main_loop_arm64(ctx)
|
||||
}
|
||||
|
||||
func decompress1x_8b_main_loop_asm(ctx *decompress1xContext) {
|
||||
decompress1x_8b_main_loop_arm64(ctx)
|
||||
}
|
||||
|
||||
func decompress1x_4b_main_loop_asm(ctx *decompress1xContext) {
|
||||
decompress1x_4b_main_loop_arm64(ctx)
|
||||
}
|
||||
+1630
-769
File diff suppressed because it is too large.
Load diff
+79
-19
@@ -14,6 +14,10 @@ import (
|
||||
// fallback8BitSize is the size where using Go version is faster.
|
||||
const fallback8BitSize = 800
|
||||
|
||||
// decompress4xContext is the argument block of the Decompress4X asm loops.
|
||||
// Go fills every field but decoded and inner; the asm advances ip, and on
|
||||
// return leaves each bit reader in the form bitReaderShifted.restoreFromAsm
|
||||
// expects.
|
||||
type decompress4xContext struct {
|
||||
pbr *[4]bitReaderShifted
|
||||
peekBits uint8
|
||||
@@ -21,9 +25,20 @@ type decompress4xContext struct {
|
||||
dstEvery int
|
||||
tbl *dEntrySingle
|
||||
decoded int
|
||||
limit *byte
|
||||
limit *byte // stream 0's output pointer must stay below this
|
||||
ilowest *byte // start of the input block; no read goes below it
|
||||
ip [4]*byte // each stream's 8-byte input window, advanced by the asm
|
||||
inner *byte // scratch for the asm: the current inner-loop limit
|
||||
}
|
||||
|
||||
// Symbols decoded per stream between reloads by the 4X asm loops; must
|
||||
// match the constants of the same names in _generate/gen.go.
|
||||
const (
|
||||
fastSymbols = 5 // tablelog 9..11
|
||||
fast8bSymbols = 7 // tablelog 5..8
|
||||
fast4bSymbols = 14 // tablelog <= 4
|
||||
)
|
||||
|
||||
// Decompress4X will decompress a 4X encoded stream.
|
||||
// The length of the supplied input must match the end of a block exactly.
|
||||
// The *capacity* of the dst slice must match the destination size of
|
||||
@@ -72,23 +87,55 @@ func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) {
|
||||
|
||||
var decoded int
|
||||
|
||||
if len(out) > 4*4 && !(br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4) {
|
||||
nSyms := fastSymbols
|
||||
if d.actualTableLog <= 4 {
|
||||
nSyms = fast4bSymbols
|
||||
} else if use8BitTables {
|
||||
nSyms = fast8bSymbols
|
||||
}
|
||||
// The asm writes nSyms bytes per stream per iteration and only re-checks
|
||||
// its bounds between batches of iterations (the batch size is derived
|
||||
// from limit in _generate/gen.go), so stream 0 must stop early enough
|
||||
// that stream 3 (which may be up to 3 bytes shorter than dstEvery)
|
||||
// never writes past the end of out. Every stream needs a full 8-byte
|
||||
// window ahead of its read pointer to enter the loop.
|
||||
if limit := dstEvery - nSyms - 2; limit > 0 && br[0].canUseAsm() && br[1].canUseAsm() && br[2].canUseAsm() && br[3].canUseAsm() {
|
||||
for i := range br {
|
||||
br[i].prepareForAsm()
|
||||
}
|
||||
ctx := decompress4xContext{
|
||||
pbr: &br,
|
||||
peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast()
|
||||
out: &out[0],
|
||||
dstEvery: dstEvery,
|
||||
tbl: &single[0],
|
||||
limit: &out[dstEvery-4], // Always stop decoding when first buffer gets here to avoid writing OOB on last.
|
||||
limit: &out[limit],
|
||||
// The 6-byte jump table sits below stream 0 inside src, so the
|
||||
// lowest window may reach into it; restoreFromAsm accounts for
|
||||
// bytes below a stream's start. Bounding by src rather than by
|
||||
// stream 0 keeps the asm running about six bytes longer, which
|
||||
// matters for streams with very short codes.
|
||||
ilowest: &src[0],
|
||||
}
|
||||
if use8BitTables {
|
||||
for i := range br {
|
||||
ctx.ip[i] = &br[i].in[br[i].off]
|
||||
}
|
||||
switch nSyms {
|
||||
case fast4bSymbols:
|
||||
decompress4x_4b_main_loop_asm(&ctx)
|
||||
case fast8bSymbols:
|
||||
decompress4x_8b_main_loop_asm(&ctx)
|
||||
} else {
|
||||
default:
|
||||
decompress4x_main_loop_asm(&ctx)
|
||||
}
|
||||
|
||||
decoded = ctx.decoded
|
||||
out = out[decoded/4:]
|
||||
for i := range br {
|
||||
if err := br[i].restoreFromAsm(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Decode remaining.
|
||||
@@ -128,18 +175,20 @@ func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) {
|
||||
return dst, nil
|
||||
}
|
||||
|
||||
// decompress1xContext is the argument block of the Decompress1X asm loops.
|
||||
// Go fills every field but decoded; the asm advances ip, and on return
|
||||
// leaves the bit reader in the form bitReaderShifted.restoreFromAsm expects.
|
||||
type decompress1xContext struct {
|
||||
pbr *bitReaderShifted
|
||||
peekBits uint8
|
||||
out *byte
|
||||
outCap int
|
||||
outCap int // no write reaches out[outCap]
|
||||
tbl *dEntrySingle
|
||||
decoded int
|
||||
ilowest *byte // start of the stream; no read goes below it
|
||||
ip *byte // the 8-byte input window, advanced by the asm
|
||||
}
|
||||
|
||||
// Error reported by asm implementations
|
||||
const error_max_decoded_size_exeeded = -1
|
||||
|
||||
// Decompress1X will decompress a 1X encoded stream.
|
||||
// The cap of the output buffer will be the maximum decompressed size.
|
||||
// The length of the supplied input must match the end of a block exactly.
|
||||
@@ -158,25 +207,36 @@ func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) {
|
||||
const tlSize = 1 << tableLogMax
|
||||
const tlMask = tlSize - 1
|
||||
|
||||
if maxDecodedSize >= 4 {
|
||||
// The asm decodes whole batches of symbols and only re-checks its
|
||||
// bounds between them, so it needs at least one batch of room (the
|
||||
// output bound rounds nSyms up to 16, see _generate/gen.go) and a full
|
||||
// 8-byte window ahead of the read pointer to enter the loop. It also
|
||||
// needs at most 7 bits consumed on entry so that a batch cannot run
|
||||
// the container dry, which prepareForAsm establishes.
|
||||
decoded := 0
|
||||
if maxDecodedSize >= 16 && br.canUseAsm() {
|
||||
br.prepareForAsm()
|
||||
ctx := decompress1xContext{
|
||||
pbr: &br,
|
||||
out: &dst[0],
|
||||
outCap: maxDecodedSize,
|
||||
peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast()
|
||||
tbl: &d.dt.single[0],
|
||||
ilowest: &src[0],
|
||||
ip: &br.in[br.off],
|
||||
}
|
||||
|
||||
decompress1x_main_loop_asm(&ctx)
|
||||
if ctx.decoded == error_max_decoded_size_exeeded {
|
||||
return nil, ErrMaxDecodedSizeExceeded
|
||||
if d.actualTableLog <= 4 {
|
||||
decompress1x_4b_main_loop_asm(&ctx)
|
||||
} else if d.actualTableLog <= 8 {
|
||||
decompress1x_8b_main_loop_asm(&ctx)
|
||||
} else {
|
||||
decompress1x_main_loop_asm(&ctx)
|
||||
}
|
||||
|
||||
dst = dst[:ctx.decoded]
|
||||
decoded = ctx.decoded
|
||||
}
|
||||
dst = dst[:decoded]
|
||||
|
||||
// br < 8, so uint8 is fine
|
||||
bitsLeft := uint8(br.off)*8 + 64 - br.bitsRead
|
||||
bitsLeft := br.remaining()
|
||||
for bitsLeft > 0 {
|
||||
br.fill()
|
||||
if len(dst) >= maxDecodedSize {
|
||||
@@ -186,7 +246,7 @@ func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) {
|
||||
v := d.dt.single[br.peekBitsFast(d.actualTableLog)&tlMask]
|
||||
nBits := uint8(v.entry)
|
||||
br.advance(nBits)
|
||||
bitsLeft -= nBits
|
||||
bitsLeft -= uint(nBits)
|
||||
dst = append(dst, uint8(v.entry>>8))
|
||||
}
|
||||
return dst, br.close()
|
||||
|
||||
+2
-2
@@ -151,7 +151,7 @@ func (i *Index) reduce() {
|
||||
i.estBlockUncomp += i.estBlockUncomp * int64(removeN)
|
||||
}
|
||||
|
||||
func (i *Index) appendTo(b []byte, uncompTotal, compTotal int64) []byte {
|
||||
func (i *Index) appendTo(b []byte, compTotal, uncompTotal int64) []byte {
|
||||
i.reduce()
|
||||
var tmp [binary.MaxVarintLen64]byte
|
||||
|
||||
@@ -425,7 +425,7 @@ func IndexStream(r io.Reader) ([]byte, error) {
|
||||
_, err := io.ReadFull(r, buf[:4])
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
return i.appendTo(nil, i.TotalUncompressed, i.TotalCompressed), nil
|
||||
return i.appendTo(nil, i.TotalCompressed, i.TotalUncompressed), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+1
-1
@@ -809,7 +809,7 @@ func (w *Writer) closeIndex(idx bool) ([]byte, error) {
|
||||
if w.pad <= 1 {
|
||||
compSize = w.written
|
||||
}
|
||||
index = w.index.appendTo(w.ibuf[:0], w.uncompWritten, compSize)
|
||||
index = w.index.appendTo(w.ibuf[:0], compSize, w.uncompWritten)
|
||||
// Count as written for padding.
|
||||
if w.appendIndex {
|
||||
w.written += int64(len(index))
|
||||
|
||||
+3
@@ -240,9 +240,11 @@ func (b *blockDec) decodeBuf(hist *history) error {
|
||||
b.dst[i] = v
|
||||
}
|
||||
hist.appendKeep(b.dst)
|
||||
hist.decoders.consumeSyncLen(len(b.dst))
|
||||
return nil
|
||||
case blockTypeRaw:
|
||||
hist.appendKeep(b.data)
|
||||
hist.decoders.consumeSyncLen(len(b.data))
|
||||
return nil
|
||||
case blockTypeCompressed:
|
||||
saved := b.dst
|
||||
@@ -487,6 +489,7 @@ func (b *blockDec) decodeCompressed(hist *history) error {
|
||||
}
|
||||
if hist.decoders.nSeqs == 0 {
|
||||
b.dst = append(b.dst, hist.decoders.literals...)
|
||||
hist.decoders.consumeSyncLen(len(hist.decoders.literals))
|
||||
return nil
|
||||
}
|
||||
before := len(hist.decoders.out)
|
||||
|
||||
+81
-44
@@ -7,8 +7,11 @@ package zstd
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"maps"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/klauspost/compress/zstd/internal/xxhash"
|
||||
)
|
||||
@@ -20,7 +23,8 @@ import (
|
||||
// A decoder can safely be re-used even if the previous stream failed.
|
||||
// To release the resources, you must call the Close() function on a decoder.
|
||||
type Decoder struct {
|
||||
o decoderOptions
|
||||
// publishedOptions contains the current immutable decoder options.
|
||||
publishedOptions atomic.Pointer[decoderOptions]
|
||||
|
||||
// Unreferenced decoders, ready for use.
|
||||
decoders chan *blockDec
|
||||
@@ -84,9 +88,10 @@ var (
|
||||
func NewReader(r io.Reader, opts ...DOption) (*Decoder, error) {
|
||||
initPredefined()
|
||||
var d Decoder
|
||||
d.o.setDefault()
|
||||
for _, o := range opts {
|
||||
err := o(&d.o)
|
||||
var o decoderOptions
|
||||
o.setDefault()
|
||||
for _, opt := range opts {
|
||||
err := opt(&o)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -99,17 +104,19 @@ func NewReader(r io.Reader, opts ...DOption) (*Decoder, error) {
|
||||
}
|
||||
|
||||
// Initialize dict map if needed.
|
||||
if d.o.dicts == nil {
|
||||
d.o.dicts = make(map[uint32]*dict)
|
||||
if o.dicts == nil {
|
||||
o.dicts = make(map[uint32]*dict)
|
||||
}
|
||||
|
||||
// Create decoders
|
||||
d.decoders = make(chan *blockDec, d.o.concurrent)
|
||||
for i := 0; i < d.o.concurrent; i++ {
|
||||
dec := newBlockDec(d.o.lowMem)
|
||||
dec.localFrame = newFrameDec(d.o)
|
||||
d.decoders = make(chan *blockDec, o.concurrent)
|
||||
for i := 0; i < o.concurrent; i++ {
|
||||
dec := newBlockDec(o.lowMem)
|
||||
dec.localFrame = newFrameDec(o)
|
||||
dec.localFrame.o.dicts = nil
|
||||
d.decoders <- dec
|
||||
}
|
||||
d.publishedOptions.Store(&o)
|
||||
|
||||
if r == nil {
|
||||
return &d, nil
|
||||
@@ -171,6 +178,9 @@ func (d *Decoder) Reset(r io.Reader) error {
|
||||
d.drainOutput()
|
||||
|
||||
d.syncStream.br.r = nil
|
||||
if d.frame != nil {
|
||||
d.frame.o.dicts = nil
|
||||
}
|
||||
if r == nil {
|
||||
d.current.err = ErrDecoderNilInput
|
||||
if len(d.current.b) > 0 {
|
||||
@@ -180,8 +190,10 @@ func (d *Decoder) Reset(r io.Reader) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
o := *d.publishedOptions.Load()
|
||||
|
||||
// If bytes buffer and < 5MB, do sync decoding anyway.
|
||||
if bb, ok := r.(byter); ok && bb.Len() < d.o.decodeBufsBelow && !d.o.limitToCap {
|
||||
if bb, ok := r.(byter); ok && bb.Len() < o.decodeBufsBelow && !o.limitToCap {
|
||||
bb2 := bb
|
||||
if debugDecoder {
|
||||
println("*bytes.Buffer detected, doing sync decode, len:", bb.Len())
|
||||
@@ -193,18 +205,30 @@ func (d *Decoder) Reset(r io.Reader) error {
|
||||
}
|
||||
|
||||
dst, err := d.DecodeAll(b, dst)
|
||||
if err == nil {
|
||||
err = io.EOF
|
||||
if !errors.Is(err, ErrDecoderSizeExceeded) {
|
||||
if err == nil {
|
||||
err = io.EOF
|
||||
}
|
||||
// Save output buffer
|
||||
d.syncStream.dstBuf = dst
|
||||
d.current.b = dst
|
||||
d.current.err = err
|
||||
d.current.flushed = true
|
||||
if debugDecoder {
|
||||
println("sync decode to", len(dst), "bytes, err:", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Save output buffer
|
||||
d.syncStream.dstBuf = dst
|
||||
d.current.b = dst
|
||||
d.current.err = err
|
||||
d.current.flushed = true
|
||||
// The output does not fit WithDecoderMaxMemory, which caps the total
|
||||
// decoded size when decoding in memory. A Reader follows the
|
||||
// streaming contract, where the option caps the window instead, so
|
||||
// decode this input as a stream after all; the shortcut has not
|
||||
// consumed the reader. Drop the oversized buffer rather than keep it
|
||||
// for reuse.
|
||||
if debugDecoder {
|
||||
println("sync decode to", len(dst), "bytes, err:", err)
|
||||
println("sync decode exceeded max memory after", len(dst), "bytes; streaming instead")
|
||||
}
|
||||
return nil
|
||||
d.syncStream.dstBuf = nil
|
||||
}
|
||||
// Remove current block.
|
||||
d.stashDecoder()
|
||||
@@ -217,14 +241,16 @@ func (d *Decoder) Reset(r io.Reader) error {
|
||||
// Ensure no-one else is still running...
|
||||
d.streamWg.Wait()
|
||||
if d.frame == nil {
|
||||
d.frame = newFrameDec(d.o)
|
||||
d.frame = newFrameDec(o)
|
||||
} else {
|
||||
d.frame.setOptions(o)
|
||||
}
|
||||
|
||||
if d.o.concurrent == 1 {
|
||||
if o.concurrent == 1 {
|
||||
return d.startSyncDecoder(r)
|
||||
}
|
||||
|
||||
d.current.output = make(chan decodeOutput, d.o.concurrent)
|
||||
d.current.output = make(chan decodeOutput, o.concurrent)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
d.current.cancel = cancel
|
||||
d.streamWg.Add(1)
|
||||
@@ -238,13 +264,21 @@ func (d *Decoder) Reset(r io.Reader) error {
|
||||
// Options are applied on top of the existing options.
|
||||
// Some options cannot be changed on reset and will return an error.
|
||||
func (d *Decoder) ResetWithOptions(r io.Reader, opts ...DOption) error {
|
||||
d.o.resetOpt = true
|
||||
defer func() { d.o.resetOpt = false }()
|
||||
if d.current.err == ErrDecoderClosed {
|
||||
return d.current.err
|
||||
}
|
||||
next := *d.publishedOptions.Load()
|
||||
next.dicts = maps.Clone(next.dicts)
|
||||
next.resetOpt = true
|
||||
for _, o := range opts {
|
||||
if err := o(&d.o); err != nil {
|
||||
if err := o(&next); err != nil {
|
||||
next.resetOpt = false
|
||||
d.publishedOptions.Store(&next)
|
||||
return err
|
||||
}
|
||||
}
|
||||
next.resetOpt = false
|
||||
d.publishedOptions.Store(&next)
|
||||
return d.Reset(r)
|
||||
}
|
||||
|
||||
@@ -324,6 +358,8 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) {
|
||||
// Grab a block decoder and frame decoder.
|
||||
block := <-d.decoders
|
||||
frame := block.localFrame
|
||||
o := *d.publishedOptions.Load()
|
||||
frame.setOptions(o)
|
||||
initialSize := len(dst)
|
||||
defer func() {
|
||||
if debugDecoder {
|
||||
@@ -335,6 +371,7 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) {
|
||||
frame.history.decoders.br.in = nil
|
||||
frame.history.decoders.br.cursor = 0
|
||||
}
|
||||
frame.o.dicts = nil
|
||||
d.decoders <- block
|
||||
}()
|
||||
frame.bBuf = input
|
||||
@@ -354,20 +391,20 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) {
|
||||
if err = d.setDict(frame); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if frame.WindowSize > d.o.maxWindowSize {
|
||||
if frame.WindowSize > frame.o.maxWindowSize {
|
||||
if debugDecoder {
|
||||
println("window size exceeded:", frame.WindowSize, ">", d.o.maxWindowSize)
|
||||
println("window size exceeded:", frame.WindowSize, ">", frame.o.maxWindowSize)
|
||||
}
|
||||
return dst, ErrWindowSizeExceeded
|
||||
}
|
||||
if frame.FrameContentSize != fcsUnknown {
|
||||
if frame.FrameContentSize > d.o.maxDecodedSize-uint64(len(dst)-initialSize) {
|
||||
if frame.FrameContentSize > frame.o.maxDecodedSize-uint64(len(dst)-initialSize) {
|
||||
if debugDecoder {
|
||||
println("decoder size exceeded; fcs:", frame.FrameContentSize, "> mcs:", d.o.maxDecodedSize-uint64(len(dst)-initialSize), "len:", len(dst))
|
||||
println("decoder size exceeded; fcs:", frame.FrameContentSize, "> mcs:", frame.o.maxDecodedSize-uint64(len(dst)-initialSize), "len:", len(dst))
|
||||
}
|
||||
return dst, ErrDecoderSizeExceeded
|
||||
}
|
||||
if d.o.limitToCap && frame.FrameContentSize > uint64(cap(dst)-len(dst)) {
|
||||
if frame.o.limitToCap && frame.FrameContentSize > uint64(cap(dst)-len(dst)) {
|
||||
if debugDecoder {
|
||||
println("decoder size exceeded; fcs:", frame.FrameContentSize, "> (cap-len)", cap(dst)-len(dst))
|
||||
}
|
||||
@@ -380,14 +417,14 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if cap(dst) == 0 && !d.o.limitToCap {
|
||||
if cap(dst) == 0 && !frame.o.limitToCap {
|
||||
// Allocate len(input) * 2 by default if nothing is provided
|
||||
// and we didn't get frame content size.
|
||||
size := min(
|
||||
// Cap to 1 MB.
|
||||
len(input)*2, 1<<20)
|
||||
if uint64(size) > d.o.maxDecodedSize {
|
||||
size = int(d.o.maxDecodedSize)
|
||||
if uint64(size) > frame.o.maxDecodedSize {
|
||||
size = int(frame.o.maxDecodedSize)
|
||||
}
|
||||
dst = make([]byte, 0, size)
|
||||
}
|
||||
@@ -396,7 +433,7 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) {
|
||||
if err != nil {
|
||||
return dst, err
|
||||
}
|
||||
if uint64(len(dst)-initialSize) > d.o.maxDecodedSize {
|
||||
if uint64(len(dst)-initialSize) > frame.o.maxDecodedSize {
|
||||
return dst, ErrDecoderSizeExceeded
|
||||
}
|
||||
if len(frame.bBuf) == 0 {
|
||||
@@ -459,7 +496,7 @@ func (d *Decoder) nextBlock(blocking bool) (ok bool) {
|
||||
println("got", len(d.current.b), "bytes, error:", d.current.err, "data crc:", tmp)
|
||||
}
|
||||
|
||||
if d.o.ignoreChecksum {
|
||||
if d.frame.o.ignoreChecksum {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -497,7 +534,7 @@ func (d *Decoder) nextBlockSync() (ok bool) {
|
||||
if d.current.err != nil {
|
||||
return false
|
||||
}
|
||||
if d.frame.WindowSize > d.o.maxDecodedSize || d.frame.WindowSize > d.o.maxWindowSize {
|
||||
if d.frame.WindowSize > d.frame.o.maxDecodedSize || d.frame.WindowSize > d.frame.o.maxWindowSize {
|
||||
d.current.err = ErrDecoderSizeExceeded
|
||||
return false
|
||||
}
|
||||
@@ -546,11 +583,11 @@ func (d *Decoder) nextBlockSync() (ok bool) {
|
||||
|
||||
// Update/Check CRC
|
||||
if d.frame.HasCheckSum {
|
||||
if !d.o.ignoreChecksum {
|
||||
if !d.frame.o.ignoreChecksum {
|
||||
d.frame.crc.Write(d.current.b)
|
||||
}
|
||||
if d.current.d.Last {
|
||||
if !d.o.ignoreChecksum {
|
||||
if !d.frame.o.ignoreChecksum {
|
||||
d.current.err = d.frame.checkCRC()
|
||||
} else {
|
||||
d.current.err = d.frame.consumeCRC()
|
||||
@@ -656,8 +693,8 @@ func (d *Decoder) startStreamDecoder(ctx context.Context, r io.Reader, output ch
|
||||
defer d.streamWg.Done()
|
||||
br := readerWrapper{r: r}
|
||||
|
||||
var seqDecode = make(chan *blockDec, d.o.concurrent)
|
||||
var seqExecute = make(chan *blockDec, d.o.concurrent)
|
||||
var seqDecode = make(chan *blockDec, d.frame.o.concurrent)
|
||||
var seqExecute = make(chan *blockDec, d.frame.o.concurrent)
|
||||
|
||||
// Async 1: Decode sequences...
|
||||
go func() {
|
||||
@@ -858,9 +895,9 @@ decodeStream:
|
||||
if err == nil {
|
||||
err = d.setDict(frame)
|
||||
}
|
||||
if err == nil && d.frame.WindowSize > d.o.maxWindowSize {
|
||||
if err == nil && d.frame.WindowSize > d.frame.o.maxWindowSize {
|
||||
if debugDecoder {
|
||||
println("decoder size exceeded, fws:", d.frame.WindowSize, "> mws:", d.o.maxWindowSize)
|
||||
println("decoder size exceeded, fws:", d.frame.WindowSize, "> mws:", d.frame.o.maxWindowSize)
|
||||
}
|
||||
|
||||
err = ErrDecoderSizeExceeded
|
||||
@@ -940,7 +977,7 @@ decodeStream:
|
||||
}
|
||||
|
||||
func (d *Decoder) setDict(frame *frameDec) (err error) {
|
||||
dict, ok := d.o.dicts[frame.DictionaryID]
|
||||
dict, ok := frame.o.dicts[frame.DictionaryID]
|
||||
if ok {
|
||||
if debugDecoder {
|
||||
println("setting dict", frame.DictionaryID)
|
||||
|
||||
+7
-4
@@ -49,13 +49,16 @@ const (
|
||||
)
|
||||
|
||||
func newFrameDec(o decoderOptions) *frameDec {
|
||||
d := frameDec{}
|
||||
d.setOptions(o)
|
||||
return &d
|
||||
}
|
||||
|
||||
func (d *frameDec) setOptions(o decoderOptions) {
|
||||
if o.maxWindowSize > o.maxDecodedSize {
|
||||
o.maxWindowSize = o.maxDecodedSize
|
||||
}
|
||||
d := frameDec{
|
||||
o: o,
|
||||
}
|
||||
return &d
|
||||
d.o = o
|
||||
}
|
||||
|
||||
// reset will read the frame header and prepare for block decoding.
|
||||
|
||||
+4
-6
@@ -47,12 +47,10 @@ init_main_loop_condition:
|
||||
|
||||
// Spread symbols
|
||||
// Calculate table step
|
||||
MOVD R0, R8
|
||||
LSR $0x01, R8, R8
|
||||
MOVD R0, R9
|
||||
LSR $0x03, R9, R9
|
||||
ADD R9, R8, R8
|
||||
ADD $3, R8, R8
|
||||
LSR $0x01, R0, R8
|
||||
LSR $0x03, R0, R9
|
||||
ADD R9, R8, R8
|
||||
ADD $3, R8, R8
|
||||
|
||||
// Fill add bits values
|
||||
SUB $1, R0, R9
|
||||
|
||||
+23
@@ -99,6 +99,29 @@ func (s *sequenceDecs) initialize(br *bitReader, hist *history, out []byte) erro
|
||||
return nil
|
||||
}
|
||||
|
||||
// consumeSyncLen accounts for n bytes of frame output produced outside
|
||||
// decodeSync. maxSyncLen bounds how much the frame may still produce and
|
||||
// decodeSyncSimple compares it with the output buffer's slack to decide
|
||||
// whether the extended 16-byte copies are safe. Blocks with sequences
|
||||
// subtracted their output; raw blocks, RLE blocks and compressed blocks
|
||||
// holding only literals did not, so a frame that opened with a raw block
|
||||
// overstated its remaining size for every block after it and ran the
|
||||
// bounds-exact copies for the rest of the frame.
|
||||
//
|
||||
// Zero means "no bound" and selects the conservative paths, so a block that
|
||||
// meets or exceeds the bound lands there; the frame-size checks in
|
||||
// runDecoder reject the excess afterwards.
|
||||
func (s *sequenceDecs) consumeSyncLen(n int) {
|
||||
if s.maxSyncLen == 0 {
|
||||
return
|
||||
}
|
||||
if uint64(n) >= s.maxSyncLen {
|
||||
s.maxSyncLen = 0
|
||||
return
|
||||
}
|
||||
s.maxSyncLen -= uint64(n)
|
||||
}
|
||||
|
||||
func (s *sequenceDecs) freeDecoders() {
|
||||
if f := s.litLengths.fse; f != nil && !f.preDefined {
|
||||
fseDecoderPool.Put(f)
|
||||
|
||||
+854
-815
File diff suppressed because it is too large.
Load diff
+513
-612
File diff suppressed because it is too large.
Load diff
+4
-3
@@ -83,9 +83,10 @@ const errorOverread = 6
|
||||
// When the output and literal buffers have compressedBlockOverAlloc (16)
|
||||
// bytes of slack past their logical use, the assembly may use extended
|
||||
// memory copies that read and write in 16-byte blocks, overrunning the end
|
||||
// of a literal run or match by up to 15 bytes. Otherwise it must use the
|
||||
// bounds-exact ("safe") copies. This mirrors the analogous, always-dynamic
|
||||
// selection in executeSimple below.
|
||||
// of a literal run or match by up to 15 bytes; an empty literal run still
|
||||
// copies one block, reading and writing the full 16 bytes of slack past
|
||||
// its position. Otherwise it must use the bounds-exact ("safe") copies.
|
||||
// This mirrors the analogous, always-dynamic selection in executeSimple below.
|
||||
//
|
||||
// The unsafe copies were disabled in #644 (2022) as a mitigation for a
|
||||
// crash, but that crash's root cause — an unguarded bitReader overread that
|
||||
|
||||
+4
-2
@@ -1110,11 +1110,13 @@ func lexConvenientNumber(lx *lexer) stateFn {
|
||||
return lexConvenientNumber
|
||||
}
|
||||
lx.backup()
|
||||
if isNL(r) || r == eof || r == mapEnd || r == optValTerm || r == mapValTerm || isWhitespace(r) || unicode.IsDigit(r) {
|
||||
if isNL(r) || r == eof || r == mapEnd || r == optValTerm || r == mapValTerm || isWhitespace(r) {
|
||||
lx.emit(itemInteger)
|
||||
return lx.pop()
|
||||
}
|
||||
// This is not a number, so treat it as a string.
|
||||
// Anything else following the suffix (including a digit, e.g. "0K1abc"
|
||||
// or "5e7bcd") means this isn't a convenient number after all, so treat
|
||||
// the whole token as a string.
|
||||
lx.stringStateFn = lexString
|
||||
return lexString
|
||||
}
|
||||
|
||||
+76
-26
@@ -1128,6 +1128,7 @@ func (a *Account) removeLeafNode(c *client) {
|
||||
for i, l := range a.lleafs {
|
||||
if l == c {
|
||||
a.lleafs[i] = a.lleafs[ll-1]
|
||||
a.lleafs[ll-1] = nil
|
||||
if ll == 1 {
|
||||
a.lleafs = nil
|
||||
} else {
|
||||
@@ -2530,14 +2531,16 @@ func (a *Account) newServiceReply(tracking bool) []byte {
|
||||
reply = append(reply, replyPre...)
|
||||
reply = append(reply, b[:]...)
|
||||
|
||||
if tracking && s.sys != nil {
|
||||
// Add in our tracking identifier. This allows the metrics to get back to only
|
||||
// this server without needless SUBS/UNSUBS.
|
||||
reply = append(reply, '.')
|
||||
reply = append(reply, s.sys.shash...)
|
||||
reply = append(reply, '.', 'T')
|
||||
}
|
||||
if tracking {
|
||||
if shash := s.Node(); shash != _EMPTY_ {
|
||||
// Add in our tracking identifier. This allows the metrics to get back to only
|
||||
// this server without needless SUBS/UNSUBS.
|
||||
reply = append(reply, '.')
|
||||
reply = append(reply, shash...)
|
||||
reply = append(reply, '.', 'T')
|
||||
|
||||
}
|
||||
}
|
||||
return reply
|
||||
}
|
||||
|
||||
@@ -2667,12 +2670,15 @@ func (a *Account) SetServiceExportAllowTrace(export string, allowTrace bool) err
|
||||
func (a *Account) addRespServiceImport(dest *Account, to string, osi *serviceImport, tracking bool, header http.Header, mt *msgTrace) *serviceImport {
|
||||
nrr := string(osi.acc.newServiceReply(tracking))
|
||||
|
||||
dest.mu.Lock()
|
||||
osiSe, osiLat, osiRT, osiShare := osi.se, osi.latency, osi.rt, osi.share
|
||||
dest.mu.Unlock()
|
||||
|
||||
a.mu.Lock()
|
||||
rt := osi.rt
|
||||
|
||||
// dest is the requestor's account. a is the service responder with the export.
|
||||
// Marked as internal here, that is how we distinguish.
|
||||
si := &serviceImport{dest, nil, osi.se, nil, nrr, to, nil, 0, rt, nil, nil, nil, mt, false, true, false, osi.share, false, false, false, nil}
|
||||
si := &serviceImport{dest, nil, osiSe, nil, nrr, to, nil, 0, osiRT, nil, nil, nil, mt, false, true, false, osiShare, false, false, false, nil}
|
||||
|
||||
if a.exports.responses == nil {
|
||||
a.exports.responses = make(map[string]*serviceImport)
|
||||
@@ -2681,12 +2687,12 @@ func (a *Account) addRespServiceImport(dest *Account, to string, osi *serviceImp
|
||||
|
||||
// Always grab time and make sure response threshold timer is running.
|
||||
si.ts = time.Now().UnixNano()
|
||||
if osi.se != nil {
|
||||
osi.se.setResponseThresholdTimer()
|
||||
if osiSe != nil {
|
||||
osiSe.setResponseThresholdTimer()
|
||||
}
|
||||
|
||||
if rt == Singleton && tracking {
|
||||
si.latency = osi.latency
|
||||
if osiRT == Singleton && tracking {
|
||||
si.latency = osiLat
|
||||
si.tracking = true
|
||||
si.trackingHdr = header
|
||||
}
|
||||
@@ -3418,21 +3424,14 @@ func (a *Account) hasExternalAuth() bool {
|
||||
return a.extAuth != nil
|
||||
}
|
||||
|
||||
// Deterimine if this is an external auth user.
|
||||
// Determine if this is an external auth user.
|
||||
func (a *Account) isExternalAuthUser(userID string) bool {
|
||||
if a == nil {
|
||||
return false
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if a.extAuth != nil {
|
||||
for _, u := range a.extAuth.AuthUsers {
|
||||
if userID == u {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
return a.extAuth != nil && slices.Contains(a.extAuth.AuthUsers, userID)
|
||||
}
|
||||
|
||||
// Return the external authorization xkey if external authorization is enabled and the xkey is set.
|
||||
@@ -3581,6 +3580,7 @@ func (s *Server) updateAccountClaimsWithRefresh(a *Account, ac *jwt.AccountClaim
|
||||
}
|
||||
a.mu.Unlock()
|
||||
|
||||
mappingFailed := false
|
||||
for sub, wm := range ac.Mappings {
|
||||
mappings := make([]*MapDest, len(wm))
|
||||
for i, m := range wm {
|
||||
@@ -3591,11 +3591,18 @@ func (s *Server) updateAccountClaimsWithRefresh(a *Account, ac *jwt.AccountClaim
|
||||
}
|
||||
}
|
||||
// This will overwrite existing entries
|
||||
a.AddWeightedMappings(string(sub), mappings...)
|
||||
if err := a.AddWeightedMappings(string(sub), mappings...); err != nil {
|
||||
// Do not remove existing mappings when a replacement fails to install;
|
||||
// otherwise a rejected dest can leave the account with no mapping.
|
||||
s.Errorf("Error adding subject mapping %q for account [%s]: %v", sub, tl, err)
|
||||
mappingFailed = true
|
||||
}
|
||||
}
|
||||
// remove mappings
|
||||
for _, rmMapping := range removeList {
|
||||
a.RemoveMapping(rmMapping)
|
||||
// remove mappings only after all replacements installed cleanly
|
||||
if !mappingFailed {
|
||||
for _, rmMapping := range removeList {
|
||||
a.RemoveMapping(rmMapping)
|
||||
}
|
||||
}
|
||||
|
||||
// Re-register system exports/imports.
|
||||
@@ -4451,6 +4458,49 @@ func claimValidate(claim *jwt.AccountClaims) error {
|
||||
if vr.IsBlocking(false) {
|
||||
return fmt.Errorf("validation errors: %v", vr.Errors())
|
||||
}
|
||||
// Align with Account.AddWeightedMappings so JWT pushes that would be
|
||||
// silently discarded at install time are rejected up front instead.
|
||||
if err := validateAccountClaimMappings(claim); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateAccountClaimMappings applies the same destination checks used by
|
||||
// Account.AddWeightedMappings (duplicates, weight totals, ValidateMapping,
|
||||
// NewSubjectTransform). jwt.Mapping.Validate is intentionally weaker.
|
||||
func validateAccountClaimMappings(claim *jwt.AccountClaims) error {
|
||||
if claim == nil {
|
||||
return nil
|
||||
}
|
||||
for src, wms := range claim.Mappings {
|
||||
if !IsValidSubject(string(src)) {
|
||||
return fmt.Errorf("mapping %q: %w", src, ErrBadSubject)
|
||||
}
|
||||
seen := make(map[string]struct{})
|
||||
tw := make(map[string]uint8)
|
||||
for _, m := range wms {
|
||||
dest := string(m.Subject)
|
||||
if _, ok := seen[dest]; ok {
|
||||
return fmt.Errorf("mapping %q: duplicate entry for %q", src, dest)
|
||||
}
|
||||
seen[dest] = struct{}{}
|
||||
weight := m.GetWeight()
|
||||
if weight > 100 {
|
||||
return fmt.Errorf("mapping %q: individual weights need to be <= 100", src)
|
||||
}
|
||||
tw[m.Cluster] += weight
|
||||
if tw[m.Cluster] > 100 {
|
||||
return fmt.Errorf("mapping %q: total weight needs to be <= 100", src)
|
||||
}
|
||||
if err := ValidateMapping(string(src), dest); err != nil {
|
||||
return fmt.Errorf("mapping %q -> %q: %v", src, dest, err)
|
||||
}
|
||||
if _, err := NewSubjectTransform(string(src), dest); err != nil {
|
||||
return fmt.Errorf("mapping %q -> %q: %v", src, dest, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+30
-13
@@ -352,8 +352,8 @@ func (s *Server) configureAuthorization() {
|
||||
}
|
||||
for _, u := range opts.AuthCallout.AuthUsers {
|
||||
// Check for user in users and nkeys since this is server config.
|
||||
var found bool
|
||||
if len(s.users) > 0 {
|
||||
found := u != _EMPTY_ && (u == opts.Username || u == opts.Websocket.Username || u == opts.MQTT.Username)
|
||||
if !found && len(s.users) > 0 {
|
||||
_, found = s.users[u]
|
||||
}
|
||||
if !found && len(s.nkeys) > 0 {
|
||||
@@ -661,6 +661,11 @@ func (s *Server) processClientOrLeafAuthentication(c *client, opts *Options) (au
|
||||
ok bool
|
||||
err error
|
||||
ao bool // auth override
|
||||
// Set if account registration failed, the connection is already closed.
|
||||
regErr error
|
||||
|
||||
username string
|
||||
token string
|
||||
)
|
||||
|
||||
// Little helper that will log the error as a debug statement, set the auth error in
|
||||
@@ -682,6 +687,10 @@ func (s *Server) processClientOrLeafAuthentication(c *client, opts *Options) (au
|
||||
var proxyRequired bool
|
||||
// Check if we have auth callouts enabled at the server level or in the bound account.
|
||||
defer func() {
|
||||
// Not an auth failure, skip the auth error event and auth callout.
|
||||
if regErr != nil {
|
||||
return
|
||||
}
|
||||
authErr := c.getAuthError()
|
||||
if authErr == nil {
|
||||
authErr = ErrAuthentication
|
||||
@@ -731,16 +740,20 @@ func (s *Server) processClientOrLeafAuthentication(c *client, opts *Options) (au
|
||||
// We have auth callout set here.
|
||||
var skip bool
|
||||
// Check if we are on the list of auth_users.
|
||||
userID := c.getRawAuthUser()
|
||||
if juc != nil {
|
||||
skip = acc.isExternalAuthUser(userID)
|
||||
skip = acc.isExternalAuthUser(juc.Subject)
|
||||
} else {
|
||||
for _, u := range opts.AuthCallout.AuthUsers {
|
||||
if userID == u {
|
||||
skip = true
|
||||
break
|
||||
}
|
||||
var userID string
|
||||
switch {
|
||||
case nkey != nil:
|
||||
userID = nkey.Nkey
|
||||
case user != nil:
|
||||
userID = user.Username
|
||||
case token == _EMPTY_ && username != _EMPTY_ && c.opts.Username == username:
|
||||
// Single user, or websocket/MQTT auth override.
|
||||
userID = username
|
||||
}
|
||||
skip = userID != _EMPTY_ && slices.Contains(opts.AuthCallout.AuthUsers, userID)
|
||||
}
|
||||
|
||||
// If we are here we have an auth callout defined and we have failed auth so far
|
||||
@@ -795,9 +808,7 @@ func (s *Server) processClientOrLeafAuthentication(c *client, opts *Options) (au
|
||||
return true
|
||||
}
|
||||
var (
|
||||
username string
|
||||
password string
|
||||
token string
|
||||
noAuthUser string
|
||||
pinnedAcounts map[string]struct{}
|
||||
)
|
||||
@@ -1042,6 +1053,10 @@ func (s *Server) processClientOrLeafAuthentication(c *client, opts *Options) (au
|
||||
c.Debugf("User JWT generated invalid permissions")
|
||||
return false
|
||||
}
|
||||
// The scoped template may have introduced a proxy requirement.
|
||||
if proxyRequired = juc.ProxyRequired; proxyRequired && !trustedProxy {
|
||||
return setProxyAuthError(ErrAuthProxyRequired)
|
||||
}
|
||||
}
|
||||
if acc.IsExpired() {
|
||||
c.Debugf("Account JWT has expired")
|
||||
@@ -1202,7 +1217,7 @@ func (s *Server) processClientOrLeafAuthentication(c *client, opts *Options) (au
|
||||
return false
|
||||
}
|
||||
}
|
||||
if err := c.RegisterNkeyUser(nkey); err != nil {
|
||||
if regErr = c.RegisterNkeyUser(nkey); regErr != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -1222,7 +1237,9 @@ func (s *Server) processClientOrLeafAuthentication(c *client, opts *Options) (au
|
||||
// If we are authorized, register the user which will properly setup any permissions
|
||||
// for pub/sub authorizations.
|
||||
if ok {
|
||||
c.RegisterUser(user)
|
||||
if regErr = c.registerUser(user); regErr != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
+29
-14
@@ -42,7 +42,7 @@ func titleCase(m string) string {
|
||||
|
||||
// Process a callout on this client's behalf.
|
||||
func (s *Server) processClientOrLeafCallout(c *client, opts *Options, proxyRequired, trustedProxy bool, ujwt string) (authorized bool, errStr string) {
|
||||
isOperatorMode := len(opts.TrustedKeys) > 0
|
||||
isOperatorMode := s.trustedKeys != nil
|
||||
|
||||
// this is the account the user connected in, or the one running the callout
|
||||
var acc *Account
|
||||
@@ -132,24 +132,30 @@ func (s *Server) processClientOrLeafCallout(c *client, opts *Options, proxyRequi
|
||||
return nil, errors.New("auth callout violation: auth callout response is not for server")
|
||||
}
|
||||
|
||||
// if response is encrypted none of this is needed
|
||||
if !encrypted {
|
||||
if isOperatorMode {
|
||||
// The asserted issuer account, if any, must be the callout account.
|
||||
if cr.IssuerAccount != _EMPTY_ && cr.IssuerAccount != account {
|
||||
return nil, fmt.Errorf("auth callout response issuer account %q is not the callout account", cr.IssuerAccount)
|
||||
}
|
||||
// The actual signer must be the callout account or one of its signing keys.
|
||||
if cr.Issuer != account {
|
||||
if _, ok := acc.hasIssuer(cr.Issuer); !ok {
|
||||
return nil, errors.New("auth callout signing key is unknown")
|
||||
}
|
||||
}
|
||||
} else if opts.AuthCallout == nil || cr.Issuer != opts.AuthCallout.Issuer {
|
||||
// The signer must be the configured issuer.
|
||||
return nil, errors.New("auth callout signing key is unknown")
|
||||
}
|
||||
}
|
||||
|
||||
// check if had an error message from the auth account
|
||||
if cr.Error != _EMPTY_ {
|
||||
return nil, fmt.Errorf("auth callout service returned an error: %v", cr.Error)
|
||||
}
|
||||
|
||||
// if response is encrypted none of this is needed
|
||||
if isOperatorMode && !encrypted {
|
||||
pkStr := cr.Issuer
|
||||
if cr.IssuerAccount != _EMPTY_ {
|
||||
pkStr = cr.IssuerAccount
|
||||
}
|
||||
if pkStr != account {
|
||||
if _, ok := acc.hasIssuer(pkStr); !ok {
|
||||
return nil, errors.New("auth callout signing key is unknown")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return jwt.DecodeUserClaims(cr.Jwt)
|
||||
}
|
||||
|
||||
@@ -291,6 +297,15 @@ func (s *Server) processClientOrLeafCallout(c *client, opts *Options, proxyRequi
|
||||
return
|
||||
}
|
||||
|
||||
// The scoped template may have introduced a proxy requirement.
|
||||
if arc.ProxyRequired && !trustedProxy {
|
||||
err = ErrAuthProxyRequired
|
||||
c.setAuthError(err)
|
||||
c.authViolation()
|
||||
respCh <- titleCase(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
// the JWT is cleared, because if in operator mode it may hold the JWT
|
||||
// for the bearer token that connected to the callout if in operator mode
|
||||
// the permissions are already set on the client, this prevents a decode
|
||||
|
||||
+85
-11
@@ -79,6 +79,75 @@ func (ss *SequenceSet) Exists(seq uint64) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// SpanEnd returns the last sequence in the consecutive span starting at seq.
|
||||
// If seq is not in the set, it returns 0, false.
|
||||
func (ss *SequenceSet) SpanEnd(seq uint64) (end uint64, found bool) {
|
||||
if ss == nil {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// Keep only ancestors that are successors of the node being searched for.
|
||||
var path [32]*node
|
||||
parents := path[:0]
|
||||
n := ss.root
|
||||
for n != nil {
|
||||
if seq < n.base {
|
||||
parents = append(parents, n)
|
||||
n = n.l
|
||||
} else if seq-n.base >= numEntries {
|
||||
n = n.r
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
if n == nil || !n.exists(seq) {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
offset := seq - n.base
|
||||
bucket, bit := offset/bitsPerBucket, offset%bitsPerBucket
|
||||
for {
|
||||
for ; bucket < numBuckets; bucket++ {
|
||||
// Ignore bits before seq and find the first missing sequence.
|
||||
if missing := ^n.bits[bucket] & (^uint64(0) << bit); missing != 0 {
|
||||
delta := uint64(bits.TrailingZeros64(missing)) - bit
|
||||
if delta > ^uint64(0)-seq {
|
||||
return ^uint64(0), true
|
||||
}
|
||||
return seq + delta - 1, true
|
||||
}
|
||||
// A full word can be skipped, unless it reaches the sequence limit.
|
||||
step := uint64(bitsPerBucket) - bit
|
||||
if step > ^uint64(0)-seq {
|
||||
return ^uint64(0), true
|
||||
}
|
||||
seq += step
|
||||
bit = 0
|
||||
}
|
||||
|
||||
// Advance to the next node in tree order without searching from the root.
|
||||
if n.r != nil {
|
||||
n = n.r
|
||||
for n.l != nil {
|
||||
parents = append(parents, n)
|
||||
n = n.l
|
||||
}
|
||||
} else if len(parents) > 0 {
|
||||
n = parents[len(parents)-1]
|
||||
parents = parents[:len(parents)-1]
|
||||
} else {
|
||||
return seq - 1, true
|
||||
}
|
||||
// A gap in node coverage ends the span. SetInitialMin can leave an
|
||||
// unaligned node overlapping its successor, so resume at seq's offset.
|
||||
if n.base > seq || seq-n.base >= numEntries {
|
||||
return seq - 1, true
|
||||
}
|
||||
offset = seq - n.base
|
||||
bucket, bit = offset/bitsPerBucket, offset%bitsPerBucket
|
||||
}
|
||||
}
|
||||
|
||||
// SetInitialMin should be used to set the initial minimum sequence when known.
|
||||
// This will more effectively utilize space versus self selecting.
|
||||
// The set should be empty.
|
||||
@@ -279,10 +348,6 @@ func (ss SequenceSet) Encode(buf []byte) []byte {
|
||||
buf = buf[:encLen]
|
||||
}
|
||||
|
||||
// TODO(dlc) - Go 1.19 introduced Append to not have to keep track.
|
||||
// Once 1.20 is out we could change this over.
|
||||
// Also binary.Write() is way slower, do not use.
|
||||
|
||||
var le = binary.LittleEndian
|
||||
buf[0], buf[1] = magic, version
|
||||
i := hdrLen
|
||||
@@ -290,14 +355,15 @@ func (ss SequenceSet) Encode(buf []byte) []byte {
|
||||
le.PutUint32(buf[i+4:], uint32(ss.size))
|
||||
i += 8
|
||||
ss.root.nodeIter(func(n *node) {
|
||||
le.PutUint64(buf[i:], n.base)
|
||||
i += 8
|
||||
for _, b := range n.bits {
|
||||
le.PutUint64(buf[i:], b)
|
||||
i += 8
|
||||
// Bound the whole record once, and read buckets without copying the array.
|
||||
const nodeLen = (numBuckets+1)*8 + 2
|
||||
record := buf[i : i+nodeLen]
|
||||
le.PutUint64(record, n.base)
|
||||
for j := range n.bits {
|
||||
le.PutUint64(record[8+j*8:], n.bits[j])
|
||||
}
|
||||
le.PutUint16(buf[i:], uint16(n.h))
|
||||
i += 2
|
||||
le.PutUint16(record[nodeLen-2:], uint16(n.h))
|
||||
i += nodeLen
|
||||
})
|
||||
return buf[:i]
|
||||
}
|
||||
@@ -566,6 +632,9 @@ func (n *node) clear(seq uint64, deleted *bool) bool {
|
||||
}
|
||||
n.bits[i] &^= mask
|
||||
*deleted = true
|
||||
if n.bits[i] != 0 {
|
||||
return false
|
||||
}
|
||||
for _, b := range n.bits {
|
||||
if b != 0 {
|
||||
return false
|
||||
@@ -578,6 +647,7 @@ func (n *node) delete(seq uint64, deleted *bool, nodes *int) *node {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
nn := *nodes
|
||||
|
||||
if seq < n.base {
|
||||
n.l = n.l.delete(seq, deleted, nodes)
|
||||
@@ -596,6 +666,10 @@ func (n *node) delete(seq uint64, deleted *bool, nodes *int) *node {
|
||||
}
|
||||
}
|
||||
|
||||
// Clearing a bit without removing a node leaves heights and balance unchanged.
|
||||
if *nodes == nn {
|
||||
return n
|
||||
}
|
||||
if n != nil {
|
||||
n.h = maxH(n) + 1
|
||||
}
|
||||
|
||||
+153
-52
@@ -852,6 +852,10 @@ func (c *client) RemoteAddress() net.Addr {
|
||||
// Helper function to report errors.
|
||||
func (c *client) reportErrRegisterAccount(acc *Account, err error) {
|
||||
if err == ErrTooManyAccountConnections {
|
||||
// Record the reason so that processConnect() can tell a real account
|
||||
// connection limit apart from an authentication failure, instead of
|
||||
// having to guess from the account the client is bound to.
|
||||
c.setAuthError(err)
|
||||
c.maxAccountConnExceeded()
|
||||
return
|
||||
}
|
||||
@@ -1006,11 +1010,15 @@ func (c *client) applyAccountLimits() {
|
||||
// with the authenticated user. This is used to map
|
||||
// any permissions into the client and setup accounts.
|
||||
func (c *client) RegisterUser(user *User) {
|
||||
c.registerUser(user)
|
||||
}
|
||||
|
||||
func (c *client) registerUser(user *User) error {
|
||||
// Register with proper account and sublist.
|
||||
if user.Account != nil {
|
||||
if err := c.registerWithAccount(user.Account); err != nil {
|
||||
c.reportErrRegisterAccount(user.Account, err)
|
||||
return
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1038,6 +1046,7 @@ func (c *client) RegisterUser(user *User) {
|
||||
}
|
||||
|
||||
c.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// RegisterNkeyUser allows auth to call back into a new nkey
|
||||
@@ -1078,13 +1087,35 @@ func (c *client) updateDefaultPermissions(perms *Permissions) bool {
|
||||
c.perms = nil
|
||||
c.mperms = nil
|
||||
c.darray = nil
|
||||
c.replies = nil
|
||||
return true
|
||||
}
|
||||
var responsePermissionsUnchanged bool
|
||||
if c.user.Permissions != nil {
|
||||
responsePermissionsUnchanged = sameResponsePermissions(c.user.Permissions.Response, perms.Response)
|
||||
}
|
||||
replies := c.replies
|
||||
c.user.Permissions = perms.clone()
|
||||
c.setPermissions(c.user.Permissions)
|
||||
if responsePermissionsUnchanged {
|
||||
c.replies = replies
|
||||
} else if c.user.Permissions.Response == nil {
|
||||
c.replies = nil
|
||||
}
|
||||
for _, sub := range c.subs {
|
||||
if len(sub.queue) > 0 {
|
||||
c.canSubscribe(string(sub.subject), string(sub.queue))
|
||||
} else {
|
||||
c.canSubscribe(string(sub.subject))
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func sameResponsePermissions(current, updated *ResponsePermission) bool {
|
||||
return current != nil && updated != nil && *current == *updated
|
||||
}
|
||||
|
||||
func splitSubjectQueue(sq string) ([]byte, []byte, error) {
|
||||
vals := strings.Fields(strings.TrimSpace(sq))
|
||||
if len(vals) == 0 {
|
||||
@@ -1591,8 +1622,9 @@ func (c *client) readLoop(pre []byte) {
|
||||
// assigned messages and their "fsp" incremented, and need now to be
|
||||
// decremented and their writeLoop signaled.
|
||||
c.flushClients(0)
|
||||
// handled inline
|
||||
if err != ErrMaxPayload && err != ErrAuthentication {
|
||||
// Handled inline, or the connection was already closed
|
||||
// (e.g. account registration failure in processConnect).
|
||||
if err != ErrMaxPayload && err != ErrAuthentication && err != ErrConnectionClosed {
|
||||
c.Error(err)
|
||||
c.closeConnection(ProtocolViolation)
|
||||
}
|
||||
@@ -1620,7 +1652,9 @@ func (c *client) readLoop(pre []byte) {
|
||||
atomic.AddInt64(&c.inMsgs, inMsgs)
|
||||
atomic.AddInt64(&c.inBytes, inBytes)
|
||||
|
||||
if acc != nil {
|
||||
// A per-account route has its account set, but routed messages were
|
||||
// already added to the account's stats in processInboundRoutedMsg.
|
||||
if acc != nil && c.kind != ROUTER {
|
||||
acc.stats.Lock()
|
||||
acc.stats.inMsgs += inMsgs
|
||||
acc.stats.inBytes += inBytes
|
||||
@@ -1780,7 +1814,12 @@ func (c *client) flushOutbound() bool {
|
||||
// Check for compression
|
||||
cw := c.out.cw
|
||||
if cw != nil {
|
||||
// We will have to adjust once we have compressed, so remove for now.
|
||||
// Replace only the bytes being compressed. Pending bytes also include
|
||||
// already-compressed data left in wnb after a partial write.
|
||||
attempted = 0
|
||||
for _, buf := range collapsed {
|
||||
attempted += int64(len(buf))
|
||||
}
|
||||
c.out.pb -= attempted
|
||||
if c.isWebsocket() {
|
||||
c.ws.fs -= attempted
|
||||
@@ -2362,7 +2401,6 @@ func (c *client) processConnect(arg []byte) error {
|
||||
if srv != nil && srv.trustedKeys == nil {
|
||||
c.opts.JWT = _EMPTY_
|
||||
}
|
||||
ujwt := c.opts.JWT
|
||||
|
||||
// For headers both client and server need to support.
|
||||
c.headers = supportsHeaders && c.opts.Headers
|
||||
@@ -2383,24 +2421,29 @@ func (c *client) processConnect(arg []byte) error {
|
||||
// A second CONNECT may move the client into a different account via
|
||||
// checkAuthentication. Drop any previously-registered subscriptions
|
||||
// from the current account first so they don't leak in that account's
|
||||
// sublist after the client switches.
|
||||
// sublist after the client switches. Also, clear any cached sublist
|
||||
// results before switching accounts.
|
||||
if !firstConnect {
|
||||
c.in.genid = 0
|
||||
c.in.results = nil
|
||||
c.clearAccountSubs(false)
|
||||
}
|
||||
|
||||
// Check for Auth
|
||||
if ok := srv.checkAuthentication(c); !ok {
|
||||
// We may fail here because we reached max limits on an account.
|
||||
if ujwt != _EMPTY_ {
|
||||
c.mu.Lock()
|
||||
acc := c.acc
|
||||
c.mu.Unlock()
|
||||
srv.mu.Lock()
|
||||
tooManyAccCons := acc != nil && acc != srv.gacc
|
||||
srv.mu.Unlock()
|
||||
if tooManyAccCons {
|
||||
return ErrTooManyAccountConnections
|
||||
}
|
||||
// We may fail here because we reached the account connection limit.
|
||||
// In that case registerWithAccount() already recorded the reason,
|
||||
// notified the client and closed the connection, so report the
|
||||
// limit instead of an authentication violation.
|
||||
if c.getAuthError() == ErrTooManyAccountConnections {
|
||||
return ErrTooManyAccountConnections
|
||||
}
|
||||
// Account registration failures already sent the error and closed the connection.
|
||||
c.mu.Lock()
|
||||
closed := c.isClosed()
|
||||
c.mu.Unlock()
|
||||
if closed {
|
||||
return ErrConnectionClosed
|
||||
}
|
||||
c.authViolation()
|
||||
return ErrAuthentication
|
||||
@@ -3318,6 +3361,9 @@ func (c *client) addShadowSub(sub *subscription, ime *ime) (*subscription, error
|
||||
|
||||
im := ime.im
|
||||
nsub.im = im
|
||||
// A leafnode subscription's origin cluster only applies to its own account. The shadow is interest in another
|
||||
// account, which that cluster's leaf links never saw, so it must not carry the origin to leafnodes or routes.
|
||||
nsub.origin = nil
|
||||
|
||||
if !im.usePub && ime.dyn && im.tr != nil {
|
||||
if im.rtr == nil {
|
||||
@@ -3601,8 +3647,26 @@ func (c *client) checkDenySub(subject, queue string) bool {
|
||||
return denied
|
||||
}
|
||||
|
||||
// importTargetSubject returns the subject that will actually be delivered to
|
||||
// this subscription. For a shadow subscription created by a stream import, the
|
||||
// delivered subject is the import's local (post-transform) form, which can
|
||||
// differ from the subject the message was published on in the exporting
|
||||
// account. For any other subscription the subject is returned unchanged.
|
||||
func (s *subscription) importTargetSubject(subj []byte) []byte {
|
||||
if s == nil || s.im == nil {
|
||||
return subj
|
||||
}
|
||||
if s.im.tr != nil {
|
||||
return []byte(s.im.tr.TransformSubject(bytesToString(subj)))
|
||||
}
|
||||
if !s.im.usePub {
|
||||
return []byte(s.im.to)
|
||||
}
|
||||
return subj
|
||||
}
|
||||
|
||||
// Create a message header for routes or leafnodes. Header and origin cluster aware.
|
||||
func (c *client) msgHeaderForRouteOrLeaf(subj, reply []byte, rt *routeTarget, acc *Account) []byte {
|
||||
func (c *client) msgHeaderForRouteOrLeaf(subj, reply []byte, rt *routeTarget, acc *Account, noOrigin bool) []byte {
|
||||
hasHeader := c.pa.hdr > 0
|
||||
subclient := rt.sub.client
|
||||
canReceiveHeader := subclient.headers
|
||||
@@ -3615,7 +3679,7 @@ func (c *client) msgHeaderForRouteOrLeaf(subj, reply []byte, rt *routeTarget, ac
|
||||
// If we are coming from a leaf with an origin cluster we need to handle differently
|
||||
// if we can. We will send a route based LMSG which has origin cluster and headers
|
||||
// by default.
|
||||
if c.kind == LEAF && c.remoteCluster() != _EMPTY_ {
|
||||
if c.kind == LEAF && !noOrigin && c.remoteCluster() != _EMPTY_ {
|
||||
subclient.mu.Lock()
|
||||
lnoc = subclient.route.lnoc
|
||||
subclient.mu.Unlock()
|
||||
@@ -3636,14 +3700,7 @@ func (c *client) msgHeaderForRouteOrLeaf(subj, reply []byte, rt *routeTarget, ac
|
||||
// Leaf nodes are LMSG
|
||||
mh[0] = 'L'
|
||||
// Remap subject if its a shadow subscription, treat like a normal client.
|
||||
if rt.sub.im != nil {
|
||||
if rt.sub.im.tr != nil {
|
||||
to := rt.sub.im.tr.TransformSubject(bytesToString(subj))
|
||||
subj = []byte(to)
|
||||
} else if !rt.sub.im.usePub {
|
||||
subj = []byte(rt.sub.im.to)
|
||||
}
|
||||
}
|
||||
subj = rt.sub.importTargetSubject(subj)
|
||||
}
|
||||
mh = append(mh, subj...)
|
||||
mh = append(mh, ' ')
|
||||
@@ -3809,7 +3866,17 @@ func (c *client) deliverMsg(prodIsMQTT bool, sub *subscription, acc *Account, su
|
||||
|
||||
// Check if we are a leafnode and have perms to check.
|
||||
if client.kind == LEAF && client.perms != nil {
|
||||
subjectToCheck, _ := getGWRoutedSubjectOrSelf(subject)
|
||||
// For a shadow subscription created by a stream import, the subject that
|
||||
// goes on the wire is the import's local (post-transform) form, see
|
||||
// msgHeaderForRouteOrLeaf() above. Check the permissions against that
|
||||
// form: the exporting account's subject is never sent to the leafnode,
|
||||
// and requiring a permission for it would grant the leafnode an
|
||||
// unrelated capability in its own account.
|
||||
// The import transform is applied first and an internal gateway reply
|
||||
// prefix is stripped from its result, because the header path transforms
|
||||
// the complete subject as well. Stripping first could authorize a
|
||||
// subject that differs from the one placed on the wire.
|
||||
subjectToCheck, _ := getGWRoutedSubjectOrSelf(sub.importTargetSubject(subject))
|
||||
if !client.pubAllowedFullCheck(string(subjectToCheck), true, true) {
|
||||
mt.addEgressEvent(client, sub, errMsgTracePubViolation)
|
||||
client.mu.Unlock()
|
||||
@@ -3985,7 +4052,7 @@ func (c *client) deliverMsg(prodIsMQTT bool, sub *subscription, acc *Account, su
|
||||
// Also this check captures if the original reply (c.pa.reply) is a GW routed
|
||||
// reply (since it is known to be > minReplyLen). If that is the case, we need to
|
||||
// track the binding between the routed reply and the reply set in the message
|
||||
// header (which is c.pa.reply without the GNR routing prefix).
|
||||
// header (which is c.pa.reply without the _GR_ routing prefix).
|
||||
if client.kind == CLIENT && len(c.pa.reply) > minReplyLen {
|
||||
if gwrply {
|
||||
// Note that we keep track of the GW routed reply in the destination
|
||||
@@ -4324,10 +4391,8 @@ func isReservedReply(reply []byte) bool {
|
||||
// Faster to check with string([:]) than byte-by-byte
|
||||
if isJSAckSubject(reply) {
|
||||
return true
|
||||
} else if len(reply) > gwReplyPrefixLen && bytesToString(reply[:gwReplyPrefixLen]) == gwReplyPrefix {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return hasGWRoutedReplyPrefix(reply)
|
||||
}
|
||||
|
||||
// This will decide to call the client code or router code.
|
||||
@@ -4367,7 +4432,7 @@ func (c *client) processInboundClientMsg(msg []byte) (bool, bool) {
|
||||
c.in.msgs++
|
||||
c.in.bytes += int32(len(msg) - LEN_CR_LF)
|
||||
|
||||
// Check that client (could be here with SYSTEM) is not publishing on reserved "$GNR" prefix.
|
||||
// Check that client (could be here with SYSTEM) is not publishing on reserved "_GR_" or legacy "$GR" prefix.
|
||||
if c.kind == CLIENT && hasGWRoutedReplyPrefix(c.pa.subject) {
|
||||
c.pubPermissionViolation(c.pa.subject)
|
||||
return false, true
|
||||
@@ -4574,9 +4639,9 @@ func (c *client) handleGWReplyMap(msg []byte) bool {
|
||||
}
|
||||
|
||||
// Used to setup the response map for a service import request that has a reply subject.
|
||||
func (c *client) setupResponseServiceImport(acc *Account, si *serviceImport, tracking bool, header http.Header) *serviceImport {
|
||||
func (c *client) setupResponseServiceImport(acc *Account, si *serviceImport, hasLatency, tracking bool, header http.Header) *serviceImport {
|
||||
rsi := si.acc.addRespServiceImport(acc, string(c.pa.reply), si, tracking, header, nil)
|
||||
if si.latency != nil {
|
||||
if hasLatency {
|
||||
if c.rtt == 0 {
|
||||
// We have a service import that we are tracking but have not established RTT.
|
||||
c.sendRTTPing()
|
||||
@@ -4863,16 +4928,17 @@ func (c *client) processServiceImport(si *serviceImport, acc *Account, msg []byt
|
||||
if (c.kind == GATEWAY || c.kind == ROUTER) && !isResponse {
|
||||
return false
|
||||
}
|
||||
// We need to protect `si` fields with account's read lock.
|
||||
acc.mu.RLock()
|
||||
// Detect cycles and ignore (return) when we detect one.
|
||||
if len(c.pa.psi) > 0 {
|
||||
for i := len(c.pa.psi) - 1; i >= 0; i-- {
|
||||
if psi := c.pa.psi[i]; psi.se == si.se {
|
||||
acc.mu.RUnlock()
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
acc.mu.RLock()
|
||||
var checkJS bool
|
||||
shouldReturn := si.invalid || acc.sl == nil
|
||||
if !shouldReturn && !isResponse && si.to == jsAllAPI {
|
||||
@@ -4883,15 +4949,27 @@ func (c *client) processServiceImport(si *serviceImport, acc *Account, msg []byt
|
||||
siAcc := si.acc
|
||||
allowTrace := si.atrc
|
||||
isMsgTraceResp := isResponse && si.mt != nil
|
||||
siSe := si.se
|
||||
siLat := si.latency
|
||||
acc.mu.RUnlock()
|
||||
|
||||
// We have a special case where JetStream pulls in all service imports through one export.
|
||||
// However the GetNext for consumers and DirectGet for streams are a no-op and causes buildups of service imports,
|
||||
// response service imports and rrMap entries which all will need to simply expire.
|
||||
// TODO(dlc) - Come up with something better.
|
||||
if shouldReturn || (checkJS && si.se != nil && si.se.acc == c.srv.SystemAccount()) {
|
||||
if shouldReturn {
|
||||
return false
|
||||
}
|
||||
if checkJS && siSe != nil {
|
||||
// siSe.acc is updated by configureAccounts() under the exporting
|
||||
// account's lock (siAcc), so read it under that lock.
|
||||
siAcc.mu.RLock()
|
||||
viaSysAcc := siSe.acc == c.srv.SystemAccount()
|
||||
siAcc.mu.RUnlock()
|
||||
if viaSysAcc {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
mt, traceOnly := c.isMsgTraceEnabled()
|
||||
|
||||
@@ -4899,13 +4977,13 @@ func (c *client) processServiceImport(si *serviceImport, acc *Account, msg []byt
|
||||
var rsi *serviceImport
|
||||
|
||||
// Check if there is a reply present and set up a response.
|
||||
tracking, headers := shouldSample(si.latency, c)
|
||||
tracking, headers := shouldSample(siLat, c)
|
||||
if len(c.pa.reply) > 0 {
|
||||
// Special case for now, need to formalize.
|
||||
// TODO(dlc) - Formalize as a service import option for reply rewrite.
|
||||
// For now we can't do $JS.ACK since that breaks pull consumers across accounts.
|
||||
if !bytes.HasPrefix(c.pa.reply, []byte(jsAckPre)) {
|
||||
if rsi = c.setupResponseServiceImport(acc, si, tracking, headers); rsi != nil {
|
||||
if rsi = c.setupResponseServiceImport(acc, si, siLat != nil, tracking, headers); rsi != nil {
|
||||
nrr = []byte(rsi.from)
|
||||
}
|
||||
} else {
|
||||
@@ -4913,7 +4991,7 @@ func (c *client) processServiceImport(si *serviceImport, acc *Account, msg []byt
|
||||
// Normally this code is not called.
|
||||
nrr = c.pa.reply
|
||||
}
|
||||
} else if !isResponse && si.latency != nil && tracking {
|
||||
} else if !isResponse && siLat != nil && tracking {
|
||||
// Check to see if this was a bad request with no reply and we were supposed to be tracking.
|
||||
siAcc.sendBadRequestTrackingLatency(si, c, headers)
|
||||
}
|
||||
@@ -5162,6 +5240,26 @@ func (c *client) processServiceImport(si *serviceImport, acc *Account, msg []byt
|
||||
return didDeliver
|
||||
}
|
||||
|
||||
// isLeafEcho reports whether delivering to sub would send a message back where it came from.
|
||||
func (c *client) isLeafEcho(sub *subscription, leafOrigin string, importedFromService bool) bool {
|
||||
return (leafOrigin != _EMPTY_ || importedFromService || sub.im != nil) && c.checkLeafEcho(sub, leafOrigin, importedFromService)
|
||||
}
|
||||
|
||||
// Imported messages may go back to their origin leafnode cluster, which never saw them in this account.
|
||||
func (c *client) checkLeafEcho(sub *subscription, leafOrigin string, importedFromService bool) bool {
|
||||
dc := sub.client
|
||||
if sub.im == nil && !importedFromService {
|
||||
return leafOrigin != _EMPTY_ && leafOrigin == dc.remoteCluster()
|
||||
}
|
||||
// Returning it to the hub it came from lets imports on both sides loop it.
|
||||
if !c.isSpokeLeafNode() || !dc.isSpokeLeafNode() {
|
||||
return false
|
||||
}
|
||||
// Unnamed hubs advertise an empty cluster name even when clustered, so treat that as possibly the same hub.
|
||||
rc, drc := c.remoteCluster(), dc.remoteCluster()
|
||||
return rc == _EMPTY_ || drc == _EMPTY_ || rc == drc
|
||||
}
|
||||
|
||||
func (c *client) addSubToRouteTargets(sub *subscription) {
|
||||
if c.in.rts == nil {
|
||||
c.in.rts = make([]routeTarget, 0, routeTargetInit)
|
||||
@@ -5343,6 +5441,7 @@ func (c *client) processMsgResults(acc *Account, r *SublistResult, msg, deliver,
|
||||
}
|
||||
|
||||
mt, traceOnly := c.isMsgTraceEnabled()
|
||||
importedFromService := flags&pmrMsgImportedFromService != 0
|
||||
|
||||
// Loop over all normal subscriptions that match.
|
||||
for _, sub := range r.psubs {
|
||||
@@ -5380,7 +5479,7 @@ func (c *client) processMsgResults(acc *Account, r *SublistResult, msg, deliver,
|
||||
// Check for stream import mapped subs (shadow subs). These apply to local subs only.
|
||||
if sub.im != nil {
|
||||
// If this message was a service import do not re-export to an exported stream.
|
||||
if flags&pmrMsgImportedFromService != 0 {
|
||||
if importedFromService {
|
||||
continue
|
||||
}
|
||||
if sub.im.tr != nil {
|
||||
@@ -5467,6 +5566,10 @@ func (c *client) processMsgResults(acc *Account, r *SublistResult, msg, deliver,
|
||||
case LEAF:
|
||||
leafOrigin = c.remoteCluster()
|
||||
}
|
||||
// The leafnode cluster never published a service-imported message in this account.
|
||||
if importedFromService {
|
||||
leafOrigin = _EMPTY_
|
||||
}
|
||||
|
||||
// For all routes/leaf/gateway connections, we may still want to send messages to
|
||||
// leaf nodes or routes even if there are no queue filters since we collect
|
||||
@@ -5510,7 +5613,7 @@ func (c *client) processMsgResults(acc *Account, r *SublistResult, msg, deliver,
|
||||
// If the destination is a LEAF, we first need to make sure
|
||||
// that we would not pick one that was the origin of this
|
||||
// message.
|
||||
if dst == LEAF && leafOrigin != _EMPTY_ && leafOrigin == sub.client.remoteCluster() {
|
||||
if dst == LEAF && c.isLeafEcho(sub, leafOrigin, importedFromService) {
|
||||
continue
|
||||
}
|
||||
// If we have assigned a ROUTER rsub already, replace if
|
||||
@@ -5563,7 +5666,7 @@ func (c *client) processMsgResults(acc *Account, r *SublistResult, msg, deliver,
|
||||
if (src == LEAF || src == CLIENT) && dst == LEAF {
|
||||
// If we come from a LEAF and are about to pick a LEAF connection,
|
||||
// make sure this is not the same leaf cluster.
|
||||
if src == LEAF && leafOrigin != _EMPTY_ && leafOrigin == sub.client.remoteCluster() {
|
||||
if src == LEAF && c.isLeafEcho(sub, leafOrigin, importedFromService) {
|
||||
continue
|
||||
}
|
||||
// Remember that leaf in case we don't find any other candidate.
|
||||
@@ -5606,7 +5709,7 @@ func (c *client) processMsgResults(acc *Account, r *SublistResult, msg, deliver,
|
||||
// Check for stream import mapped subs. These apply to local subs only.
|
||||
if sub.im != nil {
|
||||
// If this message was a service import do not re-export to an exported stream.
|
||||
if flags&pmrMsgImportedFromService != 0 {
|
||||
if importedFromService {
|
||||
continue
|
||||
}
|
||||
if sub.im.tr != nil {
|
||||
@@ -5649,7 +5752,7 @@ func (c *client) processMsgResults(acc *Account, r *SublistResult, msg, deliver,
|
||||
var delivered bool
|
||||
if !skipDelivery {
|
||||
mh := c.msgHeader(dsubj, creply, sub)
|
||||
delivered = c.deliverMsg(prodIsMQTT, sub, acc, subject, creply, mh, msg, rplyHasGWPrefix)
|
||||
delivered = c.deliverMsg(prodIsMQTT, sub, acc, dsubj, creply, mh, msg, rplyHasGWPrefix)
|
||||
if restorePaTrace {
|
||||
c.pa.trace = mt
|
||||
}
|
||||
@@ -5722,10 +5825,8 @@ sendToRoutesOrLeafs:
|
||||
// If so make sure we do not send it back to the same cluster for a different
|
||||
// leafnode. Cluster wide no echo.
|
||||
if dc.kind == LEAF {
|
||||
// Check two scenarios. One is inbound from a route (c.pa.origin),
|
||||
// and the other is leaf to leaf. In both case, leafOrigin is the one
|
||||
// to use for the comparison.
|
||||
if leafOrigin != _EMPTY_ && leafOrigin == dc.remoteCluster() {
|
||||
// leafOrigin covers both inbound from a route (c.pa.origin) and leaf to leaf.
|
||||
if c.isLeafEcho(rt.sub, leafOrigin, importedFromService) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -5745,7 +5846,7 @@ sendToRoutesOrLeafs:
|
||||
hset = true
|
||||
}
|
||||
|
||||
mh := c.msgHeaderForRouteOrLeaf(subject, reply, rt, acc)
|
||||
mh := c.msgHeaderForRouteOrLeaf(subject, reply, rt, acc, importedFromService)
|
||||
if c.deliverMsg(prodIsMQTT, rt.sub, acc, subject, reply, mh, dmsg, false) {
|
||||
if flags&pmrCollectQueueNames != 0 {
|
||||
for _, qsub := range rt.qsubs {
|
||||
|
||||
+1
-1
@@ -66,7 +66,7 @@ func init() {
|
||||
|
||||
const (
|
||||
// VERSION is the current version for the server.
|
||||
VERSION = "2.15.0"
|
||||
VERSION = "2.15.1"
|
||||
|
||||
// PROTO is the currently supported protocol.
|
||||
// 0 was the original
|
||||
|
||||
+13
-8
@@ -2130,8 +2130,11 @@ func (o *consumer) createdTime() time.Time {
|
||||
// Internal to allow creation time to be restored.
|
||||
func (o *consumer) setCreatedTime(created time.Time) {
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
o.created = created
|
||||
o.mu.Unlock()
|
||||
if fs, ok := o.store.(*consumerFileStore); ok {
|
||||
fs.setCreatedTime(created)
|
||||
}
|
||||
}
|
||||
|
||||
// This will check for extended interest in a subject. If we have local interest we just return
|
||||
@@ -2431,9 +2434,7 @@ func (o *consumer) hasMaxDeliveries(seq uint64) bool {
|
||||
if dc := o.deliveryCount(seq); dc >= o.maxdc {
|
||||
// We have hit our max deliveries for this sequence.
|
||||
// Only send the advisory once.
|
||||
if dc == o.maxdc {
|
||||
o.notifyDeliveryExceeded(seq, dc)
|
||||
}
|
||||
o.notifyDeliveryExceeded(seq, o.rdc[seq]+1)
|
||||
// Determine if we signal to start flow of messages again.
|
||||
if o.maxp > 0 && len(o.pending) >= o.maxp {
|
||||
o.signalNewMessages()
|
||||
@@ -4977,10 +4978,8 @@ func (o *consumer) getNextMsg() (*jsPubMsg, uint64, error) {
|
||||
for seq = o.getNextToRedeliver(); seq > 0; seq = o.getNextToRedeliver() {
|
||||
dc = o.incDeliveryCount(seq)
|
||||
if o.maxdc > 0 && dc > o.maxdc {
|
||||
// Only send once
|
||||
if dc == o.maxdc+1 {
|
||||
o.notifyDeliveryExceeded(seq, dc-1)
|
||||
}
|
||||
// Only send the advisory once.
|
||||
o.notifyDeliveryExceeded(seq, dc-1)
|
||||
// Make sure to remove from pending.
|
||||
if p, ok := o.pending[seq]; ok && p != nil {
|
||||
delete(o.pending, seq)
|
||||
@@ -6992,6 +6991,12 @@ func (o *consumer) switchToEphemeral() {
|
||||
// Setup dthresh.
|
||||
o.updateInactiveThreshold(&o.cfg)
|
||||
o.updatePauseState(&o.cfg)
|
||||
// Pull consumers always run the delete timer, push consumers are
|
||||
// handled by updateDeliveryInterest below.
|
||||
if o.isLeader() && o.dthresh > 0 && o.isPullMode() {
|
||||
stopAndClearTimer(&o.dtmr)
|
||||
o.dtmr = time.AfterFunc(o.dthresh, o.deleteNotActive)
|
||||
}
|
||||
cfg := o.cfg
|
||||
o.mu.Unlock()
|
||||
|
||||
|
||||
+10
@@ -2258,5 +2258,15 @@
|
||||
"help": "",
|
||||
"url": "",
|
||||
"deprecates": ""
|
||||
},
|
||||
{
|
||||
"constant": "JSSourceConsumerFlowControlStalledErr",
|
||||
"code": 500,
|
||||
"error_code": 10228,
|
||||
"description": "stream source consumer stalled on flow control",
|
||||
"comment": "",
|
||||
"help": "",
|
||||
"url": "",
|
||||
"deprecates": ""
|
||||
}
|
||||
]
|
||||
+2
-2
@@ -2935,8 +2935,8 @@ func (s *Server) remoteLatencyUpdate(sub *subscription, _ *client, _ *Account, s
|
||||
}
|
||||
// Now get the request id / reply. We need to see if we have a GW prefix and if so strip that off.
|
||||
reply := rl.ReqId
|
||||
if gwPrefix, old := isGWRoutedSubjectAndIsOldPrefix([]byte(reply)); gwPrefix {
|
||||
reply = string(getSubjectFromGWRoutedReply([]byte(reply), old))
|
||||
if isGWRoutedReply([]byte(reply)) {
|
||||
reply = string(getSubjectFromGWRoutedReply([]byte(reply)))
|
||||
}
|
||||
acc.mu.RLock()
|
||||
si := acc.exports.responses[reply]
|
||||
|
||||
+251
-109
@@ -4281,38 +4281,80 @@ func (fs *fileStore) NumPending(sseq uint64, filter string, lastPerSubject bool)
|
||||
return 0, validThrough, nil
|
||||
}
|
||||
|
||||
// If sseq is less then our first set to first.
|
||||
if sseq < fs.state.FirstSeq {
|
||||
sseq = fs.state.FirstSeq
|
||||
}
|
||||
// Track starting for both block for the sseq and staring block that matches any subject.
|
||||
var seqStart int
|
||||
// See if we need to figure out starting block per sseq.
|
||||
if sseq > fs.state.FirstSeq {
|
||||
// This should not, but can return -1, so make sure we check to avoid panic below.
|
||||
if seqStart, _ = fs.selectMsgBlockWithIndex(sseq); seqStart < 0 {
|
||||
seqStart = 0
|
||||
}
|
||||
}
|
||||
|
||||
isAll := filter == _EMPTY_ || filter == fwcs
|
||||
if isAll && filter == _EMPTY_ {
|
||||
filter = fwcs
|
||||
}
|
||||
wc := subjectHasWildcard(filter)
|
||||
|
||||
// Resolve exact filters once, including those with no retained messages.
|
||||
var info *psi
|
||||
if !isAll && !wc {
|
||||
var ok bool
|
||||
if info, ok = fs.psim.Find(stringToBytes(filter)); !ok {
|
||||
return 0, validThrough, nil
|
||||
}
|
||||
}
|
||||
|
||||
// When starting at the beginning, count directly from stream and subject state.
|
||||
// No message blocks need to be loaded, even if there are sequence gaps.
|
||||
if sseq <= fs.state.FirstSeq {
|
||||
if isAll {
|
||||
if lastPerSubject {
|
||||
return uint64(fs.psim.Size()), validThrough, nil
|
||||
}
|
||||
return fs.state.Msgs, validThrough, nil
|
||||
}
|
||||
if !wc {
|
||||
if lastPerSubject {
|
||||
return 1, validThrough, nil
|
||||
}
|
||||
return info.total, validThrough, nil
|
||||
}
|
||||
fs.psim.Match(stringToBytes(filter), func(_ []byte, info *psi) {
|
||||
if lastPerSubject {
|
||||
total++
|
||||
} else {
|
||||
total += info.total
|
||||
}
|
||||
})
|
||||
return total, validThrough, nil
|
||||
}
|
||||
|
||||
// See if filter was provided but its the only subject.
|
||||
if !isAll && !wc && fs.psim.Size() == 1 {
|
||||
_, isAll = fs.psim.Find(stringToBytes(filter))
|
||||
isAll = true
|
||||
}
|
||||
// If we are isAll and have no deleted we can do a simpler calculation.
|
||||
if !lastPerSubject && isAll && (fs.state.LastSeq-fs.state.FirstSeq+1) == fs.state.Msgs {
|
||||
if sseq == 0 {
|
||||
return fs.state.Msgs, validThrough, nil
|
||||
}
|
||||
return fs.state.LastSeq - sseq + 1, validThrough, nil
|
||||
}
|
||||
|
||||
// The remaining paths start after FirstSeq and need the starting block.
|
||||
seqStart, _ := fs.selectMsgBlockWithIndex(sseq)
|
||||
// This should not, but can return -1, so make sure we check to avoid panic below.
|
||||
if seqStart < 0 {
|
||||
seqStart = 0
|
||||
}
|
||||
|
||||
// Block indexes can have gaps, and fblk can lag after deletions. Search the
|
||||
// retained blocks for the subject's conservative bounds rather than requiring
|
||||
// the indexed blocks to still exist.
|
||||
blkStart, blkEnd := 0, len(fs.blks)
|
||||
if info != nil {
|
||||
blkStart = sort.Search(len(fs.blks), func(i int) bool { return fs.blks[i].index >= info.fblk })
|
||||
blkEnd = sort.Search(len(fs.blks), func(i int) bool { return fs.blks[i].index > info.lblk })
|
||||
if seqStart >= blkEnd {
|
||||
return 0, validThrough, nil
|
||||
}
|
||||
if seqStart < blkStart {
|
||||
if lastPerSubject {
|
||||
return 1, validThrough, nil
|
||||
}
|
||||
return info.total, validThrough, nil
|
||||
}
|
||||
}
|
||||
|
||||
_tsa, _fsa := [32]string{}, [32]string{}
|
||||
tsa, fsa := _tsa[:0], _fsa[:0]
|
||||
if wc {
|
||||
@@ -4337,10 +4379,6 @@ func (fs *fileStore) NumPending(sseq uint64, filter string, lastPerSubject bool)
|
||||
// For the last block, we need to track the subjects that we know are in that block, and track seen
|
||||
// while in the block itself, but complexity there worth it.
|
||||
if lastPerSubject || fs.cfg.MaxMsgsPer == 1 {
|
||||
// If we want all and our start sequence is equal or less than first return number of subjects.
|
||||
if isAll && sseq <= fs.state.FirstSeq {
|
||||
return uint64(fs.psim.Size()), validThrough, nil
|
||||
}
|
||||
// If we are here we need to scan. We are going to scan the PSIM looking for lblks that are >= seqStart.
|
||||
// This will build up a list of all subjects from the selected block onward.
|
||||
lbm := make(map[string]bool)
|
||||
@@ -4360,6 +4398,11 @@ func (fs *fileStore) NumPending(sseq uint64, filter string, lastPerSubject bool)
|
||||
}
|
||||
})
|
||||
|
||||
// Subjects whose last block is later need no correction in this block.
|
||||
if len(lbm) == 0 {
|
||||
return total, validThrough, nil
|
||||
}
|
||||
|
||||
// Now check if we need to inspect the seqStart block.
|
||||
// Grab write lock in case we need to load in msgs.
|
||||
mb.mu.Lock()
|
||||
@@ -4380,9 +4423,13 @@ func (fs *fileStore) NumPending(sseq uint64, filter string, lastPerSubject bool)
|
||||
}
|
||||
var smv StoreMsg
|
||||
for seq, lseq := atomic.LoadUint64(&mb.first.seq), atomic.LoadUint64(&mb.last.seq); seq <= lseq; seq++ {
|
||||
if mb.dmap.Exists(seq) {
|
||||
// Optimisation to avoid calling cacheLookup which hits time.Now().
|
||||
if end, deleted := mb.dmap.SpanEnd(seq); deleted {
|
||||
// Skip the deleted span without calling cacheLookup, which hits time.Now().
|
||||
updateLLTS = true
|
||||
if end >= lseq {
|
||||
break
|
||||
}
|
||||
seq = end
|
||||
continue
|
||||
}
|
||||
sm, _ := mb.cacheLookupNoCopy(seq, &smv)
|
||||
@@ -4422,8 +4469,9 @@ func (fs *fileStore) NumPending(sseq uint64, filter string, lastPerSubject bool)
|
||||
// If we would need to scan more from the beginning, revert back to calculating directly here.
|
||||
// TODO(dlc) - Redo properly with sublists etc for subject-based filtering.
|
||||
if seqStart >= (len(fs.blks) / 2) {
|
||||
for i := seqStart; i < len(fs.blks); i++ {
|
||||
for i := max(seqStart, blkStart); i < blkEnd; i++ {
|
||||
var shouldExpire bool
|
||||
var updateLLTS bool
|
||||
mb := fs.blks[i]
|
||||
// Hold write lock in case we need to load cache.
|
||||
mb.mu.Lock()
|
||||
@@ -4491,8 +4539,17 @@ func (fs *fileStore) NumPending(sseq uint64, filter string, lastPerSubject bool)
|
||||
}
|
||||
var smv StoreMsg
|
||||
for seq, lseq := start, atomic.LoadUint64(&mb.last.seq); seq <= lseq; seq++ {
|
||||
if end, deleted := mb.dmap.SpanEnd(seq); deleted {
|
||||
updateLLTS = true
|
||||
if end >= lseq {
|
||||
break
|
||||
}
|
||||
seq = end
|
||||
continue
|
||||
}
|
||||
if sm, _ := mb.cacheLookupNoCopy(seq, &smv); sm != nil && isMatch(sm.subj) {
|
||||
t++
|
||||
updateLLTS = false // cacheLookup already updated it.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4502,6 +4559,9 @@ func (fs *fileStore) NumPending(sseq uint64, filter string, lastPerSubject bool)
|
||||
} else {
|
||||
mb.finishedWithCache()
|
||||
}
|
||||
if updateLLTS {
|
||||
mb.llts = ats.AccessTime()
|
||||
}
|
||||
mb.mu.Unlock()
|
||||
total += t
|
||||
}
|
||||
@@ -4511,16 +4571,16 @@ func (fs *fileStore) NumPending(sseq uint64, filter string, lastPerSubject bool)
|
||||
// If we are here it's better to calculate totals from psim and adjust downward by scanning less blocks.
|
||||
// TODO(dlc) - Eventually when sublist uses generics, make this sublist driven instead.
|
||||
start := uint32(math.MaxUint32)
|
||||
fs.psim.Match(stringToBytes(filter), func(_ []byte, psi *psi) {
|
||||
total += psi.total
|
||||
// Keep track of start index for this subject.
|
||||
if psi.fblk < start {
|
||||
start = psi.fblk
|
||||
}
|
||||
})
|
||||
// See if we were asked for all, if so we are done.
|
||||
if sseq <= fs.state.FirstSeq {
|
||||
return total, validThrough, nil
|
||||
if info != nil {
|
||||
total, start = info.total, info.fblk
|
||||
} else {
|
||||
fs.psim.Match(stringToBytes(filter), func(_ []byte, psi *psi) {
|
||||
total += psi.total
|
||||
// Keep track of start index for this subject.
|
||||
if psi.fblk < start {
|
||||
start = psi.fblk
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// If we are here we need to calculate partials for the first blocks.
|
||||
@@ -4533,7 +4593,7 @@ func (fs *fileStore) NumPending(sseq uint64, filter string, lastPerSubject bool)
|
||||
|
||||
// Track how many we need to adjust against the total.
|
||||
var adjust uint64
|
||||
for i := 0; i <= seqStart; i++ {
|
||||
for i := blkStart; i <= seqStart && i < blkEnd; i++ {
|
||||
mb := fs.blks[i]
|
||||
// We can skip blks if we know they are below the first one that has any subject matches.
|
||||
if !firstSubjBlkFound {
|
||||
@@ -4582,9 +4642,13 @@ func (fs *fileStore) NumPending(sseq uint64, filter string, lastPerSubject bool)
|
||||
// We need to walk all messages in this block
|
||||
var smv StoreMsg
|
||||
for seq := atomic.LoadUint64(&mb.first.seq); seq < last; seq++ {
|
||||
if mb.dmap.Exists(seq) {
|
||||
// Optimisation to avoid calling cacheLookup which hits time.Now().
|
||||
if end, deleted := mb.dmap.SpanEnd(seq); deleted {
|
||||
// Skip the deleted span without calling cacheLookup, which hits time.Now().
|
||||
updateLLTS = true
|
||||
if end >= last {
|
||||
break
|
||||
}
|
||||
seq = end
|
||||
continue
|
||||
}
|
||||
sm, _ := mb.cacheLookupNoCopy(seq, &smv)
|
||||
@@ -4633,22 +4697,28 @@ func (fs *fileStore) NumPendingMulti(sseq uint64, sl *gsl.SimpleSublist, lastPer
|
||||
return 0, validThrough, nil
|
||||
}
|
||||
|
||||
// If sseq is less then our first set to first.
|
||||
if sseq < fs.state.FirstSeq {
|
||||
sseq = fs.state.FirstSeq
|
||||
}
|
||||
// Track starting for both block for the sseq and staring block that matches any subject.
|
||||
var seqStart int
|
||||
// See if we need to figure out starting block per sseq.
|
||||
if sseq > fs.state.FirstSeq {
|
||||
// This should not, but can return -1, so make sure we check to avoid panic below.
|
||||
if seqStart, _ = fs.selectMsgBlockWithIndex(sseq); seqStart < 0 {
|
||||
seqStart = 0
|
||||
}
|
||||
}
|
||||
|
||||
isAll := sl == nil
|
||||
|
||||
// When starting at the beginning, count directly from stream and subject state.
|
||||
// No message blocks need to be loaded, even if there are sequence gaps.
|
||||
if sseq <= fs.state.FirstSeq {
|
||||
if isAll {
|
||||
if lastPerSubject {
|
||||
return uint64(fs.psim.Size()), validThrough, nil
|
||||
}
|
||||
return fs.state.Msgs, validThrough, nil
|
||||
}
|
||||
stree.IntersectGSL(fs.psim, sl, func(_ []byte, info *psi) bool {
|
||||
if lastPerSubject {
|
||||
total++
|
||||
} else {
|
||||
total += info.total
|
||||
}
|
||||
return true
|
||||
})
|
||||
return total, validThrough, nil
|
||||
}
|
||||
|
||||
// See if filter was provided but its the only subject.
|
||||
if !isAll && fs.psim.Size() == 1 {
|
||||
fs.psim.IterFast(func(subject []byte, _ *psi) bool {
|
||||
@@ -4658,11 +4728,55 @@ func (fs *fileStore) NumPendingMulti(sseq uint64, sl *gsl.SimpleSublist, lastPer
|
||||
}
|
||||
// If we are isAll and have no deleted we can do a simpler calculation.
|
||||
if !lastPerSubject && isAll && (fs.state.LastSeq-fs.state.FirstSeq+1) == fs.state.Msgs {
|
||||
if sseq == 0 {
|
||||
return fs.state.Msgs, validThrough, nil
|
||||
}
|
||||
return fs.state.LastSeq - sseq + 1, validThrough, nil
|
||||
}
|
||||
|
||||
// The remaining paths start after FirstSeq and need the starting block.
|
||||
seqStart, _ := fs.selectMsgBlockWithIndex(sseq)
|
||||
// This should not, but can return -1, so make sure we check to avoid panic below.
|
||||
if seqStart < 0 {
|
||||
seqStart = 0
|
||||
}
|
||||
|
||||
// Resolve the matching subjects' conservative block bounds once. Block
|
||||
// indexes can have gaps, and first-block tracking can lag after deletions.
|
||||
blkStart, blkEnd := 0, len(fs.blks)
|
||||
start, stop := uint32(math.MaxUint32), uint32(0)
|
||||
var matchedMsgs, matchedSubjects, pendingSubjects uint64
|
||||
var lbm map[string]bool
|
||||
if lastPerSubject || fs.cfg.MaxMsgsPer == 1 {
|
||||
lbm = make(map[string]bool)
|
||||
}
|
||||
if sl != nil {
|
||||
bi := fs.blks[seqStart].index
|
||||
stree.IntersectGSL(fs.psim, sl, func(subj []byte, info *psi) bool {
|
||||
matchedMsgs += info.total
|
||||
matchedSubjects++
|
||||
start, stop = min(start, info.fblk), max(stop, info.lblk)
|
||||
if lbm != nil && info.lblk >= bi {
|
||||
pendingSubjects++
|
||||
if info.lblk == bi {
|
||||
lbm[string(subj)] = true
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
if matchedSubjects == 0 {
|
||||
return 0, validThrough, nil
|
||||
}
|
||||
blkStart = sort.Search(len(fs.blks), func(i int) bool { return fs.blks[i].index >= start })
|
||||
blkEnd = sort.Search(len(fs.blks), func(i int) bool { return fs.blks[i].index > stop })
|
||||
if seqStart >= blkEnd {
|
||||
return 0, validThrough, nil
|
||||
}
|
||||
if seqStart < blkStart {
|
||||
if lastPerSubject {
|
||||
return matchedSubjects, validThrough, nil
|
||||
}
|
||||
return matchedMsgs, validThrough, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Setup the isMatch function.
|
||||
isMatch := func(subj string) bool {
|
||||
if isAll {
|
||||
@@ -4678,29 +4792,28 @@ func (fs *fileStore) NumPendingMulti(sseq uint64, sl *gsl.SimpleSublist, lastPer
|
||||
// For the last block, we need to track the subjects that we know are in that block, and track seen
|
||||
// while in the block itself, but complexity there worth it.
|
||||
if lastPerSubject || fs.cfg.MaxMsgsPer == 1 {
|
||||
// If we want all and our start sequence is equal or less than first return number of subjects.
|
||||
if isAll && sseq <= fs.state.FirstSeq {
|
||||
return uint64(fs.psim.Size()), validThrough, nil
|
||||
}
|
||||
// If we are here we need to scan. We are going to scan the PSIM looking for lblks that are >= seqStart.
|
||||
// This will build up a list of all subjects from the selected block onward.
|
||||
lbm := make(map[string]bool)
|
||||
mb := fs.blks[seqStart]
|
||||
bi := mb.index
|
||||
|
||||
stree.IntersectGSL(fs.psim, sl, func(subj []byte, psi *psi) bool {
|
||||
// If the select blk start is greater than entry's last blk skip.
|
||||
if bi > psi.lblk {
|
||||
if sl != nil {
|
||||
total = pendingSubjects
|
||||
} else {
|
||||
fs.psim.IterFast(func(subj []byte, info *psi) bool {
|
||||
if info.lblk >= bi {
|
||||
total++
|
||||
if info.lblk == bi {
|
||||
lbm[string(subj)] = true
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
total++
|
||||
// We will track the subjects that are an exact match to the last block.
|
||||
// This is needed for last block processing.
|
||||
if psi.lblk == bi {
|
||||
lbm[string(subj)] = true
|
||||
}
|
||||
return true
|
||||
})
|
||||
})
|
||||
}
|
||||
// Subjects whose last block is later need no correction in this block.
|
||||
if len(lbm) == 0 {
|
||||
return total, validThrough, nil
|
||||
}
|
||||
|
||||
// Now check if we need to inspect the seqStart block.
|
||||
// Grab write lock in case we need to load in msgs.
|
||||
@@ -4722,9 +4835,13 @@ func (fs *fileStore) NumPendingMulti(sseq uint64, sl *gsl.SimpleSublist, lastPer
|
||||
}
|
||||
var smv StoreMsg
|
||||
for seq, lseq := atomic.LoadUint64(&mb.first.seq), atomic.LoadUint64(&mb.last.seq); seq <= lseq; seq++ {
|
||||
if mb.dmap.Exists(seq) {
|
||||
// Optimisation to avoid calling cacheLookup which hits time.Now().
|
||||
if end, deleted := mb.dmap.SpanEnd(seq); deleted {
|
||||
// Skip the deleted span without calling cacheLookup, which hits time.Now().
|
||||
updateLLTS = true
|
||||
if end >= lseq {
|
||||
break
|
||||
}
|
||||
seq = end
|
||||
continue
|
||||
}
|
||||
sm, _ := mb.cacheLookupNoCopy(seq, &smv)
|
||||
@@ -4763,7 +4880,7 @@ func (fs *fileStore) NumPendingMulti(sseq uint64, sl *gsl.SimpleSublist, lastPer
|
||||
|
||||
// If we would need to scan more from the beginning, revert back to calculating directly here.
|
||||
if seqStart >= (len(fs.blks) / 2) {
|
||||
for i := seqStart; i < len(fs.blks); i++ {
|
||||
for i := max(seqStart, blkStart); i < blkEnd; i++ {
|
||||
var shouldExpire bool
|
||||
mb := fs.blks[i]
|
||||
// Hold write lock in case we need to load cache.
|
||||
@@ -4828,9 +4945,13 @@ func (fs *fileStore) NumPendingMulti(sseq uint64, sl *gsl.SimpleSublist, lastPer
|
||||
}
|
||||
var smv StoreMsg
|
||||
for seq, lseq := start, atomic.LoadUint64(&mb.last.seq); seq <= lseq; seq++ {
|
||||
if mb.dmap.Exists(seq) {
|
||||
// Optimisation to avoid calling cacheLookup which hits time.Now().
|
||||
if end, deleted := mb.dmap.SpanEnd(seq); deleted {
|
||||
// Skip the deleted span without calling cacheLookup, which hits time.Now().
|
||||
updateLLTS = true
|
||||
if end >= lseq {
|
||||
break
|
||||
}
|
||||
seq = end
|
||||
continue
|
||||
}
|
||||
if sm, _ := mb.cacheLookupNoCopy(seq, &smv); sm != nil && isMatch(sm.subj) {
|
||||
@@ -4855,19 +4976,10 @@ func (fs *fileStore) NumPendingMulti(sseq uint64, sl *gsl.SimpleSublist, lastPer
|
||||
}
|
||||
|
||||
// If we are here it's better to calculate totals from psim and adjust downward by scanning less blocks.
|
||||
start := uint32(math.MaxUint32)
|
||||
stree.IntersectGSL(fs.psim, sl, func(subj []byte, psi *psi) bool {
|
||||
total += psi.total
|
||||
// Keep track of start index for this subject.
|
||||
if psi.fblk < start {
|
||||
start = psi.fblk
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
// See if we were asked for all, if so we are done.
|
||||
if sseq <= fs.state.FirstSeq {
|
||||
return total, validThrough, nil
|
||||
if sl != nil {
|
||||
total = matchedMsgs
|
||||
} else {
|
||||
total, start = fs.state.Msgs, fs.blks[0].index
|
||||
}
|
||||
|
||||
// If we are here we need to calculate partials for the first blocks.
|
||||
@@ -4880,7 +4992,7 @@ func (fs *fileStore) NumPendingMulti(sseq uint64, sl *gsl.SimpleSublist, lastPer
|
||||
|
||||
// Track how many we need to adjust against the total.
|
||||
var adjust uint64
|
||||
for i := 0; i <= seqStart; i++ {
|
||||
for i := blkStart; i <= seqStart && i < blkEnd; i++ {
|
||||
mb := fs.blks[i]
|
||||
// We can skip blks if we know they are below the first one that has any subject matches.
|
||||
if !firstSubjBlkFound {
|
||||
@@ -4929,9 +5041,13 @@ func (fs *fileStore) NumPendingMulti(sseq uint64, sl *gsl.SimpleSublist, lastPer
|
||||
// We need to walk all messages in this block
|
||||
var smv StoreMsg
|
||||
for seq := atomic.LoadUint64(&mb.first.seq); seq < last; seq++ {
|
||||
if mb.dmap.Exists(seq) {
|
||||
// Optimisation to avoid calling cacheLookup which hits time.Now().
|
||||
if end, deleted := mb.dmap.SpanEnd(seq); deleted {
|
||||
// Skip the deleted span without calling cacheLookup, which hits time.Now().
|
||||
updateLLTS = true
|
||||
if end >= last {
|
||||
break
|
||||
}
|
||||
seq = end
|
||||
continue
|
||||
}
|
||||
sm, _ := mb.cacheLookupNoCopy(seq, &smv)
|
||||
@@ -6494,6 +6610,7 @@ func (mb *msgBlock) compactWithFloor(floor uint64, fsDmap *interiorDeletes) erro
|
||||
var le = binary.LittleEndian
|
||||
var firstSet bool
|
||||
var last uint64
|
||||
var lastTime int64
|
||||
var msgs uint64
|
||||
|
||||
fseq := atomic.LoadUint64(&mb.first.seq)
|
||||
@@ -6545,9 +6662,7 @@ func (mb *msgBlock) compactWithFloor(floor uint64, fsDmap *interiorDeletes) erro
|
||||
atomic.StoreUint64(&mb.first.seq, seq)
|
||||
}
|
||||
if seq >= last {
|
||||
last = seq
|
||||
atomic.StoreUint64(&mb.last.seq, last)
|
||||
mb.last.ts = ts
|
||||
last, lastTime = seq, ts
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6589,6 +6704,13 @@ func (mb *msgBlock) compactWithFloor(floor uint64, fsDmap *interiorDeletes) erro
|
||||
return err
|
||||
}
|
||||
|
||||
// Block selection reads last.seq without mb.mu, so publish it only
|
||||
// after the replacement file is installed.
|
||||
if msgs > 0 {
|
||||
atomic.StoreUint64(&mb.last.seq, last)
|
||||
mb.last.ts = lastTime
|
||||
}
|
||||
|
||||
// Make sure to sync if we have not done so yet
|
||||
mb.needSync = !sync
|
||||
|
||||
@@ -7363,7 +7485,17 @@ func (fs *fileStore) expireMsgs() {
|
||||
// Remove messages collected by THW.
|
||||
if !sdmEnabled {
|
||||
for _, rm := range rmSeqs {
|
||||
fs.removeMsg(rm.Seq, false, false, false)
|
||||
removed, err := fs.removeMsg(rm.Seq, false, false, false)
|
||||
// The message may already be gone, removed out of band by a purge, a rollup,
|
||||
// a compact or a truncate, none of which consult the THW. Drop the entry in
|
||||
// that case, otherwise it is collected again on every pass forever. A genuine
|
||||
// removal failure (write error, closed store) keeps the entry so it is retried.
|
||||
if !removed && (err == nil || err == ErrStoreMsgNotFound || err == ErrStoreEOF) {
|
||||
fs.ttls.Remove(rm.Seq, rm.Expires)
|
||||
// The removal that orphaned the entry may already have been flushed, so
|
||||
// mark the state dirty or the pruned wheel never reaches thw.db.
|
||||
fs.dirty++
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// THW is unordered, so must sort by sequence and must not be holding the lock.
|
||||
@@ -7386,6 +7518,7 @@ func (fs *fileStore) expireMsgs() {
|
||||
sm, _ = fs.msgForSeqLocked(rm.Seq, &smv, false)
|
||||
if sm == nil {
|
||||
fs.ttls.Remove(rm.Seq, rm.Expires)
|
||||
fs.dirty++
|
||||
fs.mu.Unlock()
|
||||
continue
|
||||
}
|
||||
@@ -11011,20 +11144,13 @@ func (fs *fileStore) compactLocked(seq uint64) (purged, bytes uint64, err error)
|
||||
}
|
||||
|
||||
// We will write to a new file and mv/rename it in case of failure.
|
||||
mfn := filepath.Join(smb.fs.fcfg.StoreDir, msgDir, fmt.Sprintf(newScan, smb.index))
|
||||
fs.dios.acquire()
|
||||
err = os.WriteFile(mfn, nbuf, defaultFilePerms)
|
||||
fs.dios.release()
|
||||
sync := fs.syncAlways.Load() || fs.syncOnFlush.Load()
|
||||
err = writeAtomically(fs.dios, smb.mfn, nbuf, defaultFilePerms, sync)
|
||||
if err != nil {
|
||||
_ = os.Remove(mfn)
|
||||
smb.mu.Unlock()
|
||||
return purged, bytes, err
|
||||
}
|
||||
if err = os.Rename(mfn, smb.mfn); err != nil {
|
||||
_ = os.Remove(mfn)
|
||||
smb.mu.Unlock()
|
||||
return purged, bytes, err
|
||||
}
|
||||
smb.needSync = !sync
|
||||
|
||||
// Make sure to remove fss state.
|
||||
smb.fss = nil
|
||||
@@ -13903,6 +14029,12 @@ func (o *consumerFileStore) GetConfig() *ConsumerConfig {
|
||||
return clone
|
||||
}
|
||||
|
||||
func (o *consumerFileStore) setCreatedTime(created time.Time) {
|
||||
o.mu.Lock()
|
||||
o.cfg.Created = created
|
||||
o.mu.Unlock()
|
||||
}
|
||||
|
||||
func (o *consumerFileStore) UpdateConfig(cfg *ConsumerConfig) error {
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
@@ -14022,8 +14154,13 @@ func (o *consumerFileStore) encryptState(buf []byte) ([]byte, error) {
|
||||
}
|
||||
|
||||
func (o *consumerFileStore) writeState(buf []byte) error {
|
||||
// Check if we have the index file open.
|
||||
o.mu.Lock()
|
||||
// Don't write after being stopped or deleted, otherwise we could recreate the state file.
|
||||
if o.closed {
|
||||
o.mu.Unlock()
|
||||
return ErrStoreClosed
|
||||
}
|
||||
// Check if we have the index file open.
|
||||
if o.writing || len(buf) == 0 {
|
||||
o.mu.Unlock()
|
||||
return nil
|
||||
@@ -14067,6 +14204,10 @@ func (o *consumerFileStore) updateConfig(cfg ConsumerConfig) error {
|
||||
// Write out the consumer meta data, i.e. state.
|
||||
// Lock should be held.
|
||||
func (cfs *consumerFileStore) writeConsumerMeta() error {
|
||||
// Don't write after being stopped or deleted, otherwise we'd write into the working directory.
|
||||
if cfs.closed {
|
||||
return ErrStoreClosed
|
||||
}
|
||||
meta := filepath.Join(cfs.odir, JetStreamMetaFile)
|
||||
if _, err := os.Stat(meta); err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
@@ -14415,8 +14556,9 @@ func (o *consumerFileStore) Stop() error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Wait for an in-progress flush, even if not dirty, so the state is on disk when we return.
|
||||
o.waitOnFlusher()
|
||||
if len(buf) > 0 {
|
||||
o.waitOnFlusher()
|
||||
err = o.fs.writeFileWithOptionalSync(ifn, buf, defaultFilePerms)
|
||||
}
|
||||
return err
|
||||
|
||||
+30
-95
@@ -16,7 +16,6 @@ package server
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -40,11 +39,14 @@ const (
|
||||
defaultGatewayRecentSubExpiration = 2 * time.Second
|
||||
defaultGatewayMaxRUnsubBeforeSwitch = 1000
|
||||
|
||||
// The legacy prefix "$GR.<4:cluster hash>." was used by servers prior
|
||||
// to v2.1.2 (which do not advertise GatewayNRP in their INFO). It is no
|
||||
// longer sent nor handled, but remains reserved on client ingress since
|
||||
// older peers would still strip it and deliver to their local subscribers.
|
||||
oldGWReplyPrefix = "$GR."
|
||||
oldGWReplyPrefixLen = len(oldGWReplyPrefix)
|
||||
oldGWReplyStart = oldGWReplyPrefixLen + 5 // len of prefix above + len of hash (4) + "."
|
||||
|
||||
// The new prefix is "_GR_.<cluster>.<server>." where <cluster> is 6 characters
|
||||
// The prefix is "_GR_.<cluster>.<server>." where <cluster> is 6 characters
|
||||
// hash of origin cluster name and <server> is 6 characters hash of origin server pub key.
|
||||
gwReplyPrefix = "_GR_."
|
||||
gwReplyPrefixLen = len(gwReplyPrefix)
|
||||
@@ -145,11 +147,7 @@ type srvGateway struct {
|
||||
info *Info // Gateway Info protocol
|
||||
infoJSON []byte // Marshal'ed Info protocol
|
||||
runknown bool // Rejects unknown (not configured) gateway connections
|
||||
replyPfx []byte // Will be "$GNR.<1:reserved>.<8:cluster hash>.<8:server hash>."
|
||||
|
||||
// For backward compatibility
|
||||
oldReplyPfx []byte
|
||||
oldHash []byte
|
||||
replyPfx []byte // Will be "_GR_.<6:cluster hash>.<6:server hash>."
|
||||
|
||||
// We maintain the interest of subjects and queues per account.
|
||||
// For a given account, entries in the map could be something like this:
|
||||
@@ -195,7 +193,6 @@ type gatewayCfg struct {
|
||||
sync.RWMutex
|
||||
*RemoteGatewayOpts
|
||||
hash []byte
|
||||
oldHash []byte
|
||||
urls map[string]*url.URL
|
||||
connAttempts int
|
||||
tlsName string
|
||||
@@ -215,8 +212,6 @@ type gateway struct {
|
||||
outbound bool
|
||||
// Set/check in readLoop without lock. This is to know that an inbound has sent the CONNECT protocol first
|
||||
connected bool
|
||||
// Set to true if outbound is to a server that only knows about $GR, not $GNR
|
||||
useOldPrefix bool
|
||||
// If true, it indicates that the inbound side will switch any account to
|
||||
// interest-only mode "immediately", so the outbound should disregard
|
||||
// the optimistic mode when checking for interest.
|
||||
@@ -336,13 +331,6 @@ func getGWHash(name string) []byte {
|
||||
return []byte(getHashSize(name, gwHashLen))
|
||||
}
|
||||
|
||||
func getOldHash(name string) []byte {
|
||||
sha := sha256.New()
|
||||
sha.Write([]byte(name))
|
||||
fullHash := []byte(fmt.Sprintf("%x", sha.Sum(nil)))
|
||||
return fullHash[:4]
|
||||
}
|
||||
|
||||
// Initialize the s.gateway structure. We do this even if the server
|
||||
// does not have a gateway configured. In some part of the code, the
|
||||
// server will check the number of outbound gateways, etc.. and so
|
||||
@@ -357,7 +345,6 @@ func (s *Server) newGateway(opts *Options) error {
|
||||
URLs: make(refCountedUrlSet),
|
||||
resolver: opts.Gateway.resolver,
|
||||
runknown: opts.Gateway.RejectUnknown,
|
||||
oldHash: getOldHash(opts.Gateway.Name),
|
||||
}
|
||||
gateway.Lock()
|
||||
defer gateway.Unlock()
|
||||
@@ -372,12 +359,6 @@ func (s *Server) newGateway(opts *Options) error {
|
||||
prefix = append(prefix, '.')
|
||||
gateway.replyPfx = prefix
|
||||
|
||||
prefix = make([]byte, 0, oldGWReplyStart)
|
||||
prefix = append(prefix, oldGWReplyPrefix...)
|
||||
prefix = append(prefix, gateway.oldHash...)
|
||||
prefix = append(prefix, '.')
|
||||
gateway.oldReplyPfx = prefix
|
||||
|
||||
gateway.pasi.m = make(map[string]map[string]*sitally)
|
||||
|
||||
if gateway.resolver == nil {
|
||||
@@ -394,7 +375,6 @@ func (s *Server) newGateway(opts *Options) error {
|
||||
cfg := &gatewayCfg{
|
||||
RemoteGatewayOpts: rgo.clone(),
|
||||
hash: getGWHash(rgo.Name),
|
||||
oldHash: getOldHash(rgo.Name),
|
||||
urls: make(map[string]*url.URL, len(rgo.URLs)),
|
||||
}
|
||||
if opts.Gateway.TLSConfig != nil && cfg.TLSConfig == nil {
|
||||
@@ -1136,7 +1116,6 @@ func (c *client) processGatewayInfo(info *Info) {
|
||||
c.Debugf("Gateway connect protocol sent to %q", gwName)
|
||||
// Send INFO too
|
||||
c.enqueueProto(infoJSON)
|
||||
c.gw.useOldPrefix = !info.GatewayNRP
|
||||
c.headers = supportsHeaders && info.Headers
|
||||
c.mu.Unlock()
|
||||
|
||||
@@ -1472,7 +1451,6 @@ func (s *Server) processImplicitGateway(info *Info) {
|
||||
cfg = &gatewayCfg{
|
||||
RemoteGatewayOpts: &RemoteGatewayOpts{Name: gwName},
|
||||
hash: getGWHash(gwName),
|
||||
oldHash: getOldHash(gwName),
|
||||
urls: make(map[string]*url.URL, len(info.GatewayURLs)),
|
||||
implicit: true,
|
||||
}
|
||||
@@ -2478,28 +2456,19 @@ func (s *Server) gatewayUpdateSubInterest(accName string, sub *subscription, cha
|
||||
}
|
||||
|
||||
// Returns true if the given subject is a GW routed reply subject,
|
||||
// that is, starts with $GNR and is long enough to contain cluster/server hash
|
||||
// that is, starts with _GR_ and is long enough to contain cluster/server hash
|
||||
// and subject.
|
||||
func isGWRoutedReply(subj []byte) bool {
|
||||
return len(subj) > gwSubjectOffset && bytesToString(subj[:gwReplyPrefixLen]) == gwReplyPrefix
|
||||
}
|
||||
|
||||
// Same than isGWRoutedReply but accepts the old prefix $GR and returns
|
||||
// a boolean indicating if this is the old prefix
|
||||
func isGWRoutedSubjectAndIsOldPrefix(subj []byte) (bool, bool) {
|
||||
if isGWRoutedReply(subj) {
|
||||
return true, false
|
||||
}
|
||||
if len(subj) > oldGWReplyStart && bytesToString(subj[:oldGWReplyPrefixLen]) == oldGWReplyPrefix {
|
||||
return true, true
|
||||
}
|
||||
return false, false
|
||||
}
|
||||
|
||||
// Returns true if subject starts with "$GNR.". This is to check that
|
||||
// clients can't publish on this subject.
|
||||
// Returns true if subject starts with "_GR_." or the legacy "$GR." prefix.
|
||||
// This is to check that clients can't publish on these subjects.
|
||||
func hasGWRoutedReplyPrefix(subj []byte) bool {
|
||||
return len(subj) > gwReplyPrefixLen && bytesToString(subj[:gwReplyPrefixLen]) == gwReplyPrefix
|
||||
if len(subj) > gwReplyPrefixLen && bytesToString(subj[:gwReplyPrefixLen]) == gwReplyPrefix {
|
||||
return true
|
||||
}
|
||||
return len(subj) > oldGWReplyPrefixLen && bytesToString(subj[:oldGWReplyPrefixLen]) == oldGWReplyPrefix
|
||||
}
|
||||
|
||||
// Evaluates if the given reply should be mapped or not.
|
||||
@@ -2554,7 +2523,6 @@ func (c *client) sendMsgToGateways(acc *Account, msg, subject, reply []byte, qgr
|
||||
gws = append(gws, gw.outo[i])
|
||||
}
|
||||
thisClusterReplyPrefix := gw.replyPfx
|
||||
thisClusterOldReplyPrefix := gw.oldReplyPfx
|
||||
gw.RUnlock()
|
||||
if len(gws) == 0 {
|
||||
return false
|
||||
@@ -2584,13 +2552,9 @@ func (c *client) sendMsgToGateways(acc *Account, msg, subject, reply []byte, qgr
|
||||
|
||||
// Check if the subject is on the reply prefix, if so, we
|
||||
// need to send that message directly to the origin cluster.
|
||||
directSend, old := isGWRoutedSubjectAndIsOldPrefix(subject)
|
||||
directSend := isGWRoutedReply(subject)
|
||||
if directSend {
|
||||
if old {
|
||||
dstHash = subject[oldGWReplyPrefixLen : oldGWReplyStart-1]
|
||||
} else {
|
||||
dstHash = subject[gwClusterOffset : gwClusterOffset+gwHashLen]
|
||||
}
|
||||
dstHash = subject[gwClusterOffset : gwClusterOffset+gwHashLen]
|
||||
}
|
||||
for i := 0; i < len(gws); i++ {
|
||||
gwc := gws[i]
|
||||
@@ -2598,11 +2562,7 @@ func (c *client) sendMsgToGateways(acc *Account, msg, subject, reply []byte, qgr
|
||||
gwc.mu.Lock()
|
||||
var ok bool
|
||||
if gwc.gw.cfg != nil {
|
||||
if old {
|
||||
ok = bytes.Equal(dstHash, gwc.gw.cfg.oldHash)
|
||||
} else {
|
||||
ok = bytes.Equal(dstHash, gwc.gw.cfg.hash)
|
||||
}
|
||||
ok = bytes.Equal(dstHash, gwc.gw.cfg.hash)
|
||||
}
|
||||
gwc.mu.Unlock()
|
||||
if !ok {
|
||||
@@ -2662,14 +2622,7 @@ func (c *client) sendMsgToGateways(acc *Account, msg, subject, reply []byte, qgr
|
||||
// Decide if we should map.
|
||||
if gw.shouldMapReplyForGatewaySend(acc, reply) {
|
||||
mreply = mreplya[:0]
|
||||
gwc.mu.Lock()
|
||||
useOldPrefix := gwc.gw.useOldPrefix
|
||||
gwc.mu.Unlock()
|
||||
if useOldPrefix {
|
||||
mreply = append(mreply, thisClusterOldReplyPrefix...)
|
||||
} else {
|
||||
mreply = append(mreply, thisClusterReplyPrefix...)
|
||||
}
|
||||
mreply = append(mreply, thisClusterReplyPrefix...)
|
||||
mreply = append(mreply, reply...)
|
||||
}
|
||||
}
|
||||
@@ -2935,10 +2888,7 @@ func (s *Server) getRouteByHash(hash, accName []byte) (*client, bool) {
|
||||
}
|
||||
|
||||
// Returns the subject from the routed reply
|
||||
func getSubjectFromGWRoutedReply(reply []byte, isOldPrefix bool) []byte {
|
||||
if isOldPrefix {
|
||||
return reply[oldGWReplyStart:]
|
||||
}
|
||||
func getSubjectFromGWRoutedReply(reply []byte) []byte {
|
||||
return reply[gwSubjectOffset:]
|
||||
}
|
||||
|
||||
@@ -2946,8 +2896,8 @@ func getSubjectFromGWRoutedReply(reply []byte, isOldPrefix bool) []byte {
|
||||
// reply subject and whether the prefix was stripped.
|
||||
// If the subject is not routed, returns it unchanged.
|
||||
func getGWRoutedSubjectOrSelf(subject []byte) ([]byte, bool) {
|
||||
if isGWPrefix, oldPrefix := isGWRoutedSubjectAndIsOldPrefix(subject); isGWPrefix {
|
||||
return getSubjectFromGWRoutedReply(subject, oldPrefix), true
|
||||
if isGWRoutedReply(subject) {
|
||||
return getSubjectFromGWRoutedReply(subject), true
|
||||
}
|
||||
return subject, false
|
||||
}
|
||||
@@ -2966,41 +2916,26 @@ func (c *client) handleGatewayReply(msg []byte) (processed bool) {
|
||||
if !c.srv.gateway.enabled {
|
||||
return false
|
||||
}
|
||||
isGWPrefix, oldPrefix := isGWRoutedSubjectAndIsOldPrefix(c.pa.subject)
|
||||
if !isGWPrefix {
|
||||
if !isGWRoutedReply(c.pa.subject) {
|
||||
return false
|
||||
}
|
||||
// Save original subject (in case we have to forward)
|
||||
orgSubject := c.pa.subject
|
||||
|
||||
var clusterHash []byte
|
||||
var srvHash []byte
|
||||
var subject []byte
|
||||
|
||||
if oldPrefix {
|
||||
clusterHash = c.pa.subject[oldGWReplyPrefixLen : oldGWReplyStart-1]
|
||||
// Check if this reply is intended for our cluster.
|
||||
if !bytes.Equal(clusterHash, c.srv.gateway.oldHash) {
|
||||
// We could report, for now, just drop.
|
||||
return true
|
||||
}
|
||||
subject = c.pa.subject[oldGWReplyStart:]
|
||||
} else {
|
||||
clusterHash = c.pa.subject[gwClusterOffset : gwClusterOffset+gwHashLen]
|
||||
// Check if this reply is intended for our cluster.
|
||||
if !bytes.Equal(clusterHash, c.srv.gateway.getClusterHash()) {
|
||||
// We could report, for now, just drop.
|
||||
return true
|
||||
}
|
||||
srvHash = c.pa.subject[gwServerOffset : gwServerOffset+gwHashLen]
|
||||
subject = c.pa.subject[gwSubjectOffset:]
|
||||
clusterHash := c.pa.subject[gwClusterOffset : gwClusterOffset+gwHashLen]
|
||||
// Check if this reply is intended for our cluster.
|
||||
if !bytes.Equal(clusterHash, c.srv.gateway.getClusterHash()) {
|
||||
// We could report, for now, just drop.
|
||||
return true
|
||||
}
|
||||
srvHash := c.pa.subject[gwServerOffset : gwServerOffset+gwHashLen]
|
||||
subject := c.pa.subject[gwSubjectOffset:]
|
||||
|
||||
var route *client
|
||||
var perAccount bool
|
||||
|
||||
// If the origin is not this server, get the route this should be sent to.
|
||||
if c.kind == GATEWAY && srvHash != nil && !bytes.Equal(srvHash, c.srv.gateway.sIDHash) {
|
||||
if c.kind == GATEWAY && !bytes.Equal(srvHash, c.srv.gateway.sIDHash) {
|
||||
route, perAccount = c.srv.getRouteByHash(srvHash, c.pa.account)
|
||||
// This will be possibly nil, and in this case we will try to process
|
||||
// the interest from this server.
|
||||
@@ -3350,7 +3285,7 @@ func (s *Server) trackGWReply(c *client, acc *Account, reply, routedReply []byte
|
||||
ms := string(routedReply)
|
||||
grm := &gwReplyMap{ms: ms, exp: time.Now().Add(ttl).UnixNano()}
|
||||
// If we are here with the same key but different mapped replies
|
||||
// (say $GNR._.A.srv1.bar and then $GNR._.B.srv2.bar), we need to
|
||||
// (say _GR_.A.srv1.bar and then _GR_.B.srv2.bar), we need to
|
||||
// store it otherwise we would take the risk of the reply not
|
||||
// making it back.
|
||||
g.mapping[ms[gwSubjectOffset:]] = grm
|
||||
|
||||
+18
-18
@@ -1083,12 +1083,30 @@ func (s *Server) shutdownJetStream() {
|
||||
js.accountPurge = nil
|
||||
// Signal we are shutting down.
|
||||
js.shuttingDown = true
|
||||
var qch chan struct{}
|
||||
var stopped chan struct{}
|
||||
if cc := js.cluster; cc != nil && cc.qch != nil {
|
||||
qch, stopped = cc.qch, cc.stopped
|
||||
cc.qch, cc.stopped = nil, nil
|
||||
}
|
||||
js.mu.Unlock()
|
||||
|
||||
if accPurgeSub != nil {
|
||||
s.sysUnsubscribe(accPurgeSub)
|
||||
}
|
||||
|
||||
// If we were clustered signal the monitor cluster go routine.
|
||||
// We will wait for a bit for it to close, before removing the accounts' JetStream.
|
||||
// Do this without the lock.
|
||||
if qch != nil {
|
||||
close(qch) // Must be close() to signal *all* listeners
|
||||
select {
|
||||
case <-stopped:
|
||||
case <-time.After(10 * time.Second):
|
||||
s.Warnf("Did not receive signal for successful shutdown of cluster routine")
|
||||
}
|
||||
}
|
||||
|
||||
for _, a := range accounts {
|
||||
a.removeJetStream()
|
||||
}
|
||||
@@ -1098,13 +1116,7 @@ func (s *Server) shutdownJetStream() {
|
||||
js.mu.Lock()
|
||||
js.accounts = nil
|
||||
|
||||
var qch chan struct{}
|
||||
var stopped chan struct{}
|
||||
if cc := js.cluster; cc != nil {
|
||||
if cc.qch != nil {
|
||||
qch, stopped = cc.qch, cc.stopped
|
||||
cc.qch, cc.stopped = nil, nil
|
||||
}
|
||||
js.stopUpdatesSub()
|
||||
if cc.metaRescue != nil {
|
||||
s.sysUnsubscribe(cc.metaRescue)
|
||||
@@ -1119,18 +1131,6 @@ func (s *Server) shutdownJetStream() {
|
||||
s.jsClustered.Store(false)
|
||||
}
|
||||
js.mu.Unlock()
|
||||
|
||||
// If we were clustered signal the monitor cluster go routine.
|
||||
// We will wait for a bit for it to close.
|
||||
// Do this without the lock.
|
||||
if qch != nil {
|
||||
close(qch) // Must be close() to signal *all* listeners
|
||||
select {
|
||||
case <-stopped:
|
||||
case <-time.After(10 * time.Second):
|
||||
s.Warnf("Did not receive signal for successful shutdown of cluster routine")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// JetStreamConfig will return the current config. Useful if the system
|
||||
|
||||
+20
-8
@@ -402,6 +402,15 @@ func generateJSMappingTable(domain string) map[string]string {
|
||||
// JSMaxDescription is the maximum description length for streams and consumers.
|
||||
const JSMaxDescriptionLen = 4 * 1024
|
||||
|
||||
const (
|
||||
// S2 framing constants, mirrored from github.com/klauspost/compress/s2 where they are unexported.
|
||||
s2MagicChunk = "\xff\x06\x00\x00S2sTwO"
|
||||
s2ChunkHeaderSize = 4
|
||||
s2MaxChunkSize = 1<<24 - 1
|
||||
// jsRestoreFormatDetectLimit bounds bytes buffered while detecting the snapshot format: the S2 stream identifier plus one maximum-sized S2 chunk.
|
||||
jsRestoreFormatDetectLimit = len(s2MagicChunk) + s2ChunkHeaderSize + s2MaxChunkSize
|
||||
)
|
||||
|
||||
// JSMaxMetadataLen is the maximum length for streams and consumers metadata map.
|
||||
// It's calculated by summing length of all keys and values.
|
||||
const JSMaxMetadataLen = 128 * 1024
|
||||
@@ -2395,6 +2404,10 @@ func (s *Server) jsConsumerLeaderStepDownRequest(sub *subscription, c *client, _
|
||||
|
||||
js.mu.RLock()
|
||||
isLeader, sa := cc.isLeader(), js.streamAssignment(acc.Name, stream)
|
||||
var ca *consumerAssignment
|
||||
if sa != nil {
|
||||
ca = sa.consumers[consumer]
|
||||
}
|
||||
js.mu.RUnlock()
|
||||
|
||||
if isLeader && sa == nil {
|
||||
@@ -2411,10 +2424,6 @@ func (s *Server) jsConsumerLeaderStepDownRequest(sub *subscription, c *client, _
|
||||
return
|
||||
}
|
||||
|
||||
var ca *consumerAssignment
|
||||
if sa.consumers != nil {
|
||||
ca = sa.consumers[consumer]
|
||||
}
|
||||
if ca == nil {
|
||||
resp.Error = NewJSConsumerNotFoundError()
|
||||
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp))
|
||||
@@ -3277,7 +3286,8 @@ func (s *Server) jsLeaderServerStreamMoveRequest(sub *subscription, c *client, _
|
||||
// we need to expand into another one below.
|
||||
newCluster := currCluster
|
||||
|
||||
peers, e := cc.selectPeerGroup(cfg.Replicas+1, currCluster, &cfg, currPeers, 1, nil)
|
||||
haCost := cc.streamHACost(accName, &cfg)
|
||||
peers, e := cc.selectPeerGroup(cfg.Replicas+1, currCluster, &cfg, currPeers, 1, nil, haCost, nil)
|
||||
if len(peers) <= cfg.Replicas {
|
||||
// since expanding in the same cluster did not yield a result, try in different cluster
|
||||
peers = nil
|
||||
@@ -3292,7 +3302,7 @@ func (s *Server) jsLeaderServerStreamMoveRequest(sub *subscription, c *client, _
|
||||
errs := &selectPeerError{}
|
||||
errs.accumulate(e)
|
||||
for cluster := range clusters {
|
||||
newPeers, e := cc.selectPeerGroup(cfg.Replicas, cluster, &cfg, nil, 0, nil)
|
||||
newPeers, e := cc.selectPeerGroup(cfg.Replicas, cluster, &cfg, nil, 0, nil, haCost, nil)
|
||||
if len(newPeers) >= cfg.Replicas {
|
||||
peers = append([]string{}, currPeers...)
|
||||
peers = append(peers, newPeers[:cfg.Replicas]...)
|
||||
@@ -4491,10 +4501,12 @@ func (s *Server) processStreamRestore(ci *ClientInfo, acc *Account, cfg *StreamC
|
||||
|
||||
// Determine the snapshot format.
|
||||
var consumed bytes.Buffer
|
||||
tee := io.TeeReader(pr, &consumed)
|
||||
tee := io.TeeReader(io.LimitReader(pr, int64(jsRestoreFormatDetectLimit)), &consumed)
|
||||
sr := s2.NewReader(tee)
|
||||
var preamble [8]byte
|
||||
if _, err = io.ReadFull(sr, preamble[:]); err == nil {
|
||||
if _, err = io.ReadFull(sr, preamble[:]); err != nil && consumed.Len() >= jsRestoreFormatDetectLimit {
|
||||
err = errors.New("snapshot format not detected within size limit")
|
||||
} else if err == nil {
|
||||
replay := io.MultiReader(&consumed, pr)
|
||||
if bytes.Equal(preamble[:], []byte(archive.MagicBytes)) {
|
||||
mset, err = acc.RestoreStreamV2(cfg, replay)
|
||||
|
||||
+883
-260
File diff suppressed because it is too large.
Load diff
+14
@@ -479,6 +479,9 @@ const (
|
||||
// JSSnapshotDeliverSubjectInvalidErr deliver subject not valid
|
||||
JSSnapshotDeliverSubjectInvalidErr ErrorIdentifier = 10015
|
||||
|
||||
// JSSourceConsumerFlowControlStalledErr stream source consumer stalled on flow control
|
||||
JSSourceConsumerFlowControlStalledErr ErrorIdentifier = 10228
|
||||
|
||||
// JSSourceConsumerRequiresAckFCErr stream source consumer requires flow control ack policy
|
||||
JSSourceConsumerRequiresAckFCErr ErrorIdentifier = 10217
|
||||
|
||||
@@ -844,6 +847,7 @@ var (
|
||||
JSRestoreSubscribeFailedErrF: {Code: 500, ErrCode: 10042, Description: "JetStream unable to subscribe to restore snapshot {subject}: {err}"},
|
||||
JSSequenceNotFoundErrF: {Code: 400, ErrCode: 10043, Description: "sequence {seq} not found"},
|
||||
JSSnapshotDeliverSubjectInvalidErr: {Code: 400, ErrCode: 10015, Description: "deliver subject not valid"},
|
||||
JSSourceConsumerFlowControlStalledErr: {Code: 500, ErrCode: 10228, Description: "stream source consumer stalled on flow control"},
|
||||
JSSourceConsumerRequiresAckFCErr: {Code: 400, ErrCode: 10217, Description: "stream source consumer requires flow control ack policy"},
|
||||
JSSourceConsumerSetupFailedErrF: {Code: 500, ErrCode: 10045, Description: "{err}"},
|
||||
JSSourceDuplicateDetected: {Code: 400, ErrCode: 10140, Description: "duplicate source configuration detected"},
|
||||
@@ -2667,6 +2671,16 @@ func NewJSSnapshotDeliverSubjectInvalidError(opts ...ErrorOption) *ApiError {
|
||||
return ApiErrors[JSSnapshotDeliverSubjectInvalidErr]
|
||||
}
|
||||
|
||||
// NewJSSourceConsumerFlowControlStalledError creates a new JSSourceConsumerFlowControlStalledErr error: "stream source consumer stalled on flow control"
|
||||
func NewJSSourceConsumerFlowControlStalledError(opts ...ErrorOption) *ApiError {
|
||||
eopts := parseOpts(opts)
|
||||
if ae, ok := eopts.err.(*ApiError); ok {
|
||||
return ae
|
||||
}
|
||||
|
||||
return ApiErrors[JSSourceConsumerFlowControlStalledErr]
|
||||
}
|
||||
|
||||
// NewJSSourceConsumerRequiresAckFCError creates a new JSSourceConsumerRequiresAckFCErr error: "stream source consumer requires flow control ack policy"
|
||||
func NewJSSourceConsumerRequiresAckFCError(opts ...ErrorOption) *ApiError {
|
||||
eopts := parseOpts(opts)
|
||||
|
||||
+142
-45
@@ -385,6 +385,11 @@ func validateLeafNodeProxyOptions(remote *RemoteLeafOpts) ([]string, error) {
|
||||
var warnings []string
|
||||
|
||||
if remote.Proxy.URL == _EMPTY_ {
|
||||
// Without a URL the proxy is not used, so any other proxy option is a mistake.
|
||||
if remote.Proxy.Username != _EMPTY_ || remote.Proxy.Password != _EMPTY_ || remote.Proxy.Timeout != 0 ||
|
||||
remote.Proxy.TLSConfig != nil || remote.Proxy.TLSTimeout != 0 {
|
||||
return warnings, fmt.Errorf("proxy URL must be specified when other proxy options are set")
|
||||
}
|
||||
return warnings, nil
|
||||
}
|
||||
|
||||
@@ -401,34 +406,25 @@ func validateLeafNodeProxyOptions(remote *RemoteLeafOpts) ([]string, error) {
|
||||
return warnings, fmt.Errorf("proxy URL must specify a host")
|
||||
}
|
||||
|
||||
if remote.Proxy.TLSConfig != nil && proxyURL.Scheme != "https" {
|
||||
return warnings, fmt.Errorf("proxy TLS configuration requires an https proxy URL, got: %s", proxyURL.Scheme)
|
||||
}
|
||||
|
||||
if remote.Proxy.Timeout < 0 {
|
||||
return warnings, fmt.Errorf("proxy timeout must be >= 0")
|
||||
}
|
||||
|
||||
if remote.Proxy.TLSTimeout < 0 {
|
||||
return warnings, fmt.Errorf("proxy TLS timeout must be >= 0")
|
||||
}
|
||||
|
||||
if (remote.Proxy.Username == _EMPTY_) != (remote.Proxy.Password == _EMPTY_) {
|
||||
return warnings, fmt.Errorf("proxy username and password must both be specified or both be empty")
|
||||
}
|
||||
|
||||
if len(remote.URLs) > 0 {
|
||||
hasWebSocketURL := false
|
||||
hasNonWebSocketURL := false
|
||||
|
||||
for _, remoteURL := range remote.URLs {
|
||||
if remoteURL.Scheme == wsSchemePrefix || remoteURL.Scheme == wsSchemePrefixTLS {
|
||||
hasWebSocketURL = true
|
||||
if (remoteURL.Scheme == wsSchemePrefixTLS) &&
|
||||
remote.TLSConfig == nil && !remote.TLS {
|
||||
return warnings, fmt.Errorf("proxy is configured but remote URL %s requires TLS and no TLS configuration is provided. When using proxy with TLS endpoints, ensure TLS is properly configured for the leafnode remote", remoteURL.String())
|
||||
}
|
||||
} else {
|
||||
hasNonWebSocketURL = true
|
||||
}
|
||||
}
|
||||
|
||||
if !hasWebSocketURL {
|
||||
warnings = append(warnings, "proxy configuration will be ignored: proxy settings only apply to WebSocket connections (ws:// or wss://), but all configured URLs use TCP connections (nats://)")
|
||||
} else if hasNonWebSocketURL {
|
||||
warnings = append(warnings, "proxy configuration will only be used for WebSocket URLs: proxy settings do not apply to TCP connections (nats://)")
|
||||
for _, remoteURL := range remote.URLs {
|
||||
if remoteURL.Scheme == wsSchemePrefixTLS && remote.TLSConfig == nil && !remote.TLS {
|
||||
return warnings, fmt.Errorf("proxy is configured but remote URL %s requires TLS and no TLS configuration is provided. When using proxy with TLS endpoints, ensure TLS is properly configured for the leafnode remote", remoteURL.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -453,6 +449,9 @@ func (s *Server) reConnectToRemoteLeafNode(remote *leafNodeCfg) {
|
||||
case <-s.quitCh:
|
||||
return
|
||||
}
|
||||
if !s.isRunning() || s.isLameDuckMode() {
|
||||
return
|
||||
}
|
||||
clearInProgress = !connectToRemoteLeafNode(s, remote, false)
|
||||
}
|
||||
|
||||
@@ -611,8 +610,19 @@ func (s *Server) setLeafNodeNonExportedOptions() {
|
||||
|
||||
const sharedSysAccDelay = 250 * time.Millisecond
|
||||
|
||||
// proxyDialAddress returns the proxy's host:port, defaulting the port based on the scheme.
|
||||
func proxyDialAddress(u *url.URL) string {
|
||||
if u.Port() != _EMPTY_ {
|
||||
return u.Host
|
||||
}
|
||||
if u.Scheme == "https" {
|
||||
return net.JoinHostPort(u.Hostname(), "443")
|
||||
}
|
||||
return net.JoinHostPort(u.Hostname(), "80")
|
||||
}
|
||||
|
||||
// establishHTTPProxyTunnel establishes an HTTP CONNECT tunnel through a proxy server
|
||||
func establishHTTPProxyTunnel(proxyURL, targetHost string, timeout time.Duration, username, password string) (net.Conn, error) {
|
||||
func establishHTTPProxyTunnel(proxyURL, targetHost string, timeout time.Duration, username, password string, tlsConfig *tls.Config, tlsTimeout time.Duration) (net.Conn, error) {
|
||||
proxyAddr, err := url.Parse(proxyURL)
|
||||
if err != nil {
|
||||
// This should not happen since proxy URL is validated during configuration parsing
|
||||
@@ -620,12 +630,38 @@ func establishHTTPProxyTunnel(proxyURL, targetHost string, timeout time.Duration
|
||||
}
|
||||
|
||||
// Connect to the proxy server
|
||||
conn, err := natsDialTimeout("tcp", proxyAddr.Host, timeout)
|
||||
conn, err := natsDialTimeout("tcp", proxyDialAddress(proxyAddr), timeout)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to connect to proxy: %v", err)
|
||||
}
|
||||
|
||||
// Set deadline for the entire proxy handshake
|
||||
if proxyAddr.Scheme == "https" {
|
||||
var cfg *tls.Config
|
||||
if tlsConfig != nil {
|
||||
cfg = tlsConfig.Clone()
|
||||
} else {
|
||||
cfg = &tls.Config{MinVersion: tls.VersionTLS12}
|
||||
}
|
||||
if cfg.ServerName == _EMPTY_ {
|
||||
cfg.ServerName = proxyAddr.Hostname()
|
||||
}
|
||||
if tlsTimeout <= 0 {
|
||||
tlsTimeout = DEFAULT_LEAF_TLS_TIMEOUT
|
||||
}
|
||||
tlsConn := tls.Client(conn, cfg)
|
||||
// The TLS handshake has its own timeout, like other TLS handshakes.
|
||||
if err := tlsConn.SetDeadline(time.Now().Add(tlsTimeout)); err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("failed to set deadline: %v", err)
|
||||
}
|
||||
if err := tlsConn.Handshake(); err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("proxy TLS handshake failed: %v", err)
|
||||
}
|
||||
conn = tlsConn
|
||||
}
|
||||
|
||||
// Set deadline for the CONNECT exchange
|
||||
if err := conn.SetDeadline(time.Now().Add(timeout)); err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("failed to set deadline: %v", err)
|
||||
@@ -648,7 +684,8 @@ func establishHTTPProxyTunnel(proxyURL, targetHost string, timeout time.Duration
|
||||
return nil, fmt.Errorf("failed to write CONNECT request: %v", err)
|
||||
}
|
||||
|
||||
resp, err := http.ReadResponse(bufio.NewReader(conn), req)
|
||||
br := bufio.NewReader(conn)
|
||||
resp, err := http.ReadResponse(br, req)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("failed to read proxy response: %v", err)
|
||||
@@ -669,7 +706,46 @@ func establishHTTPProxyTunnel(proxyURL, targetHost string, timeout time.Duration
|
||||
return nil, fmt.Errorf("failed to clear deadline: %v", err)
|
||||
}
|
||||
|
||||
return conn, nil
|
||||
// Wrap TLS to the proxy, so it isn't mistaken for TLS to the remote.
|
||||
_, isTLS := conn.(*tls.Conn)
|
||||
n := br.Buffered()
|
||||
if !isTLS && n == 0 {
|
||||
return conn, nil
|
||||
}
|
||||
pc := &proxyTunnelConn{Conn: conn}
|
||||
// Keep bytes the target sent along with the CONNECT response, like a hub's INFO.
|
||||
if n > 0 {
|
||||
pre, _ := br.Peek(n)
|
||||
pc.pre = bytes.NewBuffer(pre)
|
||||
}
|
||||
return pc, nil
|
||||
}
|
||||
|
||||
// proxyTunnelConn is a connection tunneled through a proxy, returning bytes
|
||||
// read past the CONNECT response first.
|
||||
type proxyTunnelConn struct {
|
||||
net.Conn
|
||||
pre *bytes.Buffer
|
||||
}
|
||||
|
||||
func (c *proxyTunnelConn) Read(b []byte) (int, error) {
|
||||
if c.pre != nil {
|
||||
n, err := c.pre.Read(b)
|
||||
if c.pre.Len() == 0 {
|
||||
c.pre = nil
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
return c.Conn.Read(b)
|
||||
}
|
||||
|
||||
// Close the TLS connection to the proxy in a go routine, like closeConnection does for *tls.Conn.
|
||||
func (c *proxyTunnelConn) Close() error {
|
||||
if _, ok := c.Conn.(*tls.Conn); ok {
|
||||
go c.Conn.Close()
|
||||
return nil
|
||||
}
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
// Connect to a remote leaf node asynchronously (that is, this function will do
|
||||
@@ -776,7 +852,7 @@ func connectToRemoteLeafNode(s *Server, remote *leafNodeCfg, firstConnect bool)
|
||||
reconnectTimer.Stop()
|
||||
defer stopAndClearTimer(&reconnectTimer)
|
||||
|
||||
for s.isRunning() && remote.stillValid() {
|
||||
for s.isRunning() && !s.isLameDuckMode() && remote.stillValid() {
|
||||
rURL := remote.pickNextURL()
|
||||
url, err := s.getRandomIP(resolver, rURL.Host, nil)
|
||||
if err == nil {
|
||||
@@ -793,17 +869,12 @@ func connectToRemoteLeafNode(s *Server, remote *leafNodeCfg, firstConnect bool)
|
||||
|
||||
// Check if proxy is configured
|
||||
if proxyURL != _EMPTY_ {
|
||||
targetHost := rURL.Host
|
||||
// If URL doesn't include port, add the default port for the scheme
|
||||
if rURL.Port() == _EMPTY_ {
|
||||
defaultPort := "80"
|
||||
if rURL.Scheme == wsSchemePrefixTLS {
|
||||
defaultPort = "443"
|
||||
}
|
||||
targetHost = net.JoinHostPort(rURL.Hostname(), defaultPort)
|
||||
}
|
||||
|
||||
conn, err = establishHTTPProxyTunnel(proxyURL, targetHost, proxyTimeout, proxyUsername, proxyPassword)
|
||||
// Read per attempt so that a reloaded proxy TLS config is picked up.
|
||||
remote.RLock()
|
||||
proxyTLSConfig, proxyTLSTimeout := remote.Proxy.TLSConfig, secondsToDuration(remote.Proxy.TLSTimeout)
|
||||
remote.RUnlock()
|
||||
// Remote URLs always have a port, see setBaselineOptions.
|
||||
conn, err = establishHTTPProxyTunnel(proxyURL, rURL.Host, proxyTimeout, proxyUsername, proxyPassword, proxyTLSConfig, proxyTLSTimeout)
|
||||
} else {
|
||||
// Direct connection
|
||||
conn, err = dialer("tcp", url, dialTimeout)
|
||||
@@ -1068,7 +1139,15 @@ func (s *Server) startLeafNodeAcceptLoop() {
|
||||
if warn {
|
||||
s.Warnf(leafnodeTLSInsecureWarning)
|
||||
}
|
||||
go s.acceptConnections(l, "Leafnode", func(conn net.Conn) { s.createLeafNode(conn, nil, nil, nil) }, nil)
|
||||
go s.acceptConnections(l, "Leafnode", func(conn net.Conn) { s.createLeafNode(conn, nil, nil, nil) },
|
||||
func(_ error) bool {
|
||||
if s.isLameDuckMode() {
|
||||
s.ldmCh <- true
|
||||
<-s.quitCh
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
@@ -1396,6 +1475,15 @@ func (s *Server) createLeafNode(conn net.Conn, rURL *url.URL, remote *leafNodeCf
|
||||
// We will process the INFO from the readloop and finish by
|
||||
// sending the CONNECT and finish registration later.
|
||||
} else {
|
||||
// Websocket leafnodes do TLS in the websocket http server, so there is
|
||||
// no TLS initiation below. Mark the handshake as complete, as is done
|
||||
// for websocket clients, so that TLS state (e.g. verified client chains)
|
||||
// is available to auth callout.
|
||||
if c.isWebsocket() {
|
||||
if _, ok := c.nc.(*tls.Conn); ok {
|
||||
c.flags.set(handshakeComplete)
|
||||
}
|
||||
}
|
||||
// Send our info to the other side.
|
||||
// Remember the nonce we sent here for signatures, etc.
|
||||
c.nonce = make([]byte, nonceLen)
|
||||
@@ -1967,6 +2055,10 @@ func (s *Server) addLeafNodeConnection(c *client, srvName, clusterName string, c
|
||||
|
||||
var old *client
|
||||
s.mu.Lock()
|
||||
if s.ldm {
|
||||
s.mu.Unlock()
|
||||
return false
|
||||
}
|
||||
// We check for empty because in some test we may send empty CONNECT{}
|
||||
if checkForDup && srvName != _EMPTY_ {
|
||||
for _, ol := range s.leafs {
|
||||
@@ -2348,7 +2440,10 @@ func (c *client) processLeafNodeConnect(s *Server, arg []byte, lang string) erro
|
||||
}
|
||||
|
||||
// Add in the leafnode here since we passed through auth at this point.
|
||||
s.addLeafNodeConnection(c, proto.Name, proto.Cluster, true)
|
||||
if !s.addLeafNodeConnection(c, proto.Name, proto.Cluster, true) {
|
||||
c.closeConnection(ServerShutdown)
|
||||
return nil
|
||||
}
|
||||
|
||||
// If we have permissions bound to this leafnode we need to send then back to the
|
||||
// origin server for local enforcement.
|
||||
@@ -2470,7 +2565,14 @@ func (s *Server) initLeafNodeSmapAndSendSubs(c *client) {
|
||||
if c.isSpokeLeafNode() {
|
||||
acc.sl.localSubs(&subs, true)
|
||||
} else {
|
||||
acc.sl.All(&subs)
|
||||
// Don't advertise interest from leafnodes to other isolated leafnodes.
|
||||
if c.isIsolatedLeafNode() {
|
||||
acc.sl.Filter(&subs, func(sub *subscription) bool {
|
||||
return !sub.leaf && sub.client.kind != LEAF
|
||||
})
|
||||
} else {
|
||||
acc.sl.All(&subs)
|
||||
}
|
||||
}
|
||||
|
||||
// Check if we have an existing service import reply.
|
||||
@@ -2543,10 +2645,6 @@ func (s *Server) initLeafNodeSmapAndSendSubs(c *client) {
|
||||
c.Debugf("Not permitted to subscribe to %q on behalf of %s%s", sub.subject, accName, accNTag)
|
||||
continue
|
||||
}
|
||||
// Don't advertise interest from leafnodes to other isolated leafnodes.
|
||||
if (sub.client.kind == LEAF || sub.leaf) && c.isIsolatedLeafNode() {
|
||||
continue
|
||||
}
|
||||
// We ignore ourselves here.
|
||||
// Also don't add the subscription if it has a origin cluster and the
|
||||
// cluster name matches the one of the client we are sending to.
|
||||
@@ -2570,7 +2668,6 @@ func (s *Server) initLeafNodeSmapAndSendSubs(c *client) {
|
||||
// that have been augmented from the original subscription.
|
||||
// TODO(dlc) - Should we lock this down more?
|
||||
if applyGlobalRouting {
|
||||
c.leaf.smap[oldGWReplyPrefix+"*.>"]++
|
||||
c.leaf.smap[gwReplyPrefix+">"]++
|
||||
}
|
||||
// Detect loops by subscribing to a specific subject and checking
|
||||
|
||||
+6
-10
@@ -305,15 +305,6 @@ func (ms *memStore) storeRawMsg(subj string, hdr, msg []byte, seq uint64, ts, tt
|
||||
ms.state.FirstTime = now
|
||||
}
|
||||
|
||||
// Make copies
|
||||
// TODO(dlc) - Maybe be smarter here.
|
||||
if len(msg) > 0 {
|
||||
msg = copyBytes(msg)
|
||||
}
|
||||
if len(hdr) > 0 {
|
||||
hdr = copyBytes(hdr)
|
||||
}
|
||||
|
||||
// FIXME(dlc) - Could pool at this level?
|
||||
sm := &StoreMsg{subj, nil, nil, make([]byte, 0, len(hdr)+len(msg)), seq, ts}
|
||||
sm.buf = append(sm.buf, hdr...)
|
||||
@@ -1439,7 +1430,12 @@ func (ms *memStore) expireMsgs() {
|
||||
// Remove messages collected by THW.
|
||||
if !sdmEnabled {
|
||||
for _, rm := range rmSeqs {
|
||||
ms.removeMsg(rm.Seq, false)
|
||||
// The message may already be gone, removed out of band by a path that
|
||||
// does not consult the THW. Drop the entry in that case, otherwise it is
|
||||
// collected again on every pass forever.
|
||||
if !ms.removeMsg(rm.Seq, false) {
|
||||
ms.ttls.Remove(rm.Seq, rm.Expires)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// THW is unordered, so must sort by sequence and must not be holding the lock.
|
||||
|
||||
+13
-3
@@ -313,7 +313,7 @@ func (s *Server) Connz(opts *ConnzOptions) (*Connz, error) {
|
||||
c.ID = s.info.ID
|
||||
// select client by CID
|
||||
if cid > 0 {
|
||||
cidClient = s.clients[cid]
|
||||
cidClient = clist[cid]
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
|
||||
@@ -373,8 +373,16 @@ func (s *Server) Connz(opts *ConnzOptions) (*Connz, error) {
|
||||
// and look for opened connections.
|
||||
if state == ConnOpen || state == ConnAll {
|
||||
if cidClient != nil {
|
||||
openClients = append(openClients, cidClient)
|
||||
closedClients = nil
|
||||
// The account filter was already applied by scoping clist,
|
||||
// but user and MQTT client ID filters still need to be applied.
|
||||
cidClient.mu.RLock()
|
||||
cAuthUser := cidClient.getRawAuthUser()
|
||||
cMQTTID := cidClient.getMQTTClientID()
|
||||
cidClient.mu.RUnlock()
|
||||
if (user == _EMPTY_ || cAuthUser == user) && (mqttCID == _EMPTY_ || cMQTTID == mqttCID) {
|
||||
openClients = append(openClients, cidClient)
|
||||
closedClients = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
// If we did not find, and the user selected for ConnClosed or ConnAll,
|
||||
@@ -2451,6 +2459,7 @@ type LeafInfo struct {
|
||||
NumSubs uint32 `json:"subscriptions"`
|
||||
Subs []string `json:"subscriptions_list,omitempty"`
|
||||
Compression string `json:"compression,omitempty"`
|
||||
Websocket bool `json:"websocket,omitempty"`
|
||||
Proxy *ProxyInfo `json:"proxy,omitempty"`
|
||||
}
|
||||
|
||||
@@ -2495,6 +2504,7 @@ func (s *Server) Leafz(opts *LeafzOptions) (*Leafz, error) {
|
||||
OutBytes: ln.outBytes,
|
||||
NumSubs: uint32(len(ln.subs)),
|
||||
Compression: ln.leaf.compression,
|
||||
Websocket: ln.isWebsocket(),
|
||||
Proxy: createProxyInfo(ln),
|
||||
}
|
||||
if opts != nil && opts.Subscriptions {
|
||||
|
||||
+616
-227
File diff suppressed because it is too large.
Load diff
+53
-2
@@ -292,7 +292,7 @@ type RemoteLeafOpts struct {
|
||||
NoMasking bool `json:"-"`
|
||||
}
|
||||
|
||||
// HTTP Proxy configuration for WebSocket connections
|
||||
// HTTP proxy configuration, used for all remote URLs
|
||||
Proxy struct {
|
||||
// URL of the HTTP proxy server (e.g., "http://proxy.example.com:8080")
|
||||
URL string `json:"-"`
|
||||
@@ -302,6 +302,10 @@ type RemoteLeafOpts struct {
|
||||
Password string `json:"-"`
|
||||
// Timeout for proxy connection
|
||||
Timeout time.Duration `json:"-"`
|
||||
// TLSConfig for the connection to an https proxy, nil uses system roots
|
||||
TLSConfig *tls.Config `json:"-"`
|
||||
// TLSTimeout for the TLS handshake with an https proxy, in seconds, defaults to DEFAULT_LEAF_TLS_TIMEOUT
|
||||
TLSTimeout float64 `json:"-"`
|
||||
}
|
||||
|
||||
tlsConfigOpts *TLSConfigOpts
|
||||
@@ -375,7 +379,7 @@ func generateRemoteLeafOptsName(r *RemoteLeafOpts, redacted bool) string {
|
||||
type JSLimitOpts struct {
|
||||
MaxRequestBatch int `json:"max_request_batch,omitempty"` // MaxRequestBatch is the maximum amount of updates that can be sent in a batch
|
||||
MaxAckPending int `json:"max_ack_pending,omitempty"` // MaxAckPending is the server limit for maximum amount of outstanding Acks
|
||||
MaxHAAssets int `json:"max_ha_assets,omitempty"` // MaxHAAssets is the maximum of Streams and Consumers that may have more than 1 replica
|
||||
MaxHAAssets int `json:"max_ha_assets,omitempty"` // MaxHAAssets is the maximum number of Streams and Consumers that may have more than 1 replica, per server, enforced by the meta leader
|
||||
Duplicates time.Duration `json:"max_duplicate_window,omitempty"` // Duplicates is the maximum value for duplicate tracking on Streams
|
||||
MaxBatchInflightPerStream int `json:"max_batch_inflight_per_stream,omitempty"` // MaxBatchInflightPerStream is the maximum amount of open batches per stream
|
||||
MaxBatchInflightTotal int `json:"max_batch_inflight_total,omitempty"` // MaxBatchInflightTotal is the maximum amount of total open batches per server
|
||||
@@ -3079,6 +3083,26 @@ func parseLeafUsers(mv any, errors *[]error) ([]*User, error) {
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// proxyTLSSupportedKeys are the TLS options that apply to the client connection to a proxy.
|
||||
var proxyTLSSupportedKeys = map[string]struct{}{
|
||||
"cert_file": {},
|
||||
"key_file": {},
|
||||
"ca_file": {},
|
||||
"insecure": {},
|
||||
"cipher_suites": {},
|
||||
"allow_insecure_cipher_suites": {},
|
||||
"curve_preferences": {},
|
||||
"min_version": {},
|
||||
"timeout": {},
|
||||
"cert_store": {},
|
||||
"cert_match_by": {},
|
||||
"cert_match": {},
|
||||
"cert_match_skip_invalid": {},
|
||||
"ca_certs_match": {},
|
||||
"certs": {},
|
||||
"certificates": {},
|
||||
}
|
||||
|
||||
func parseRemoteLeafNodes(v any, errors *[]error, warnings *[]error) ([]*RemoteLeafOpts, error) {
|
||||
var lt token
|
||||
defer convertPanicToErrorList(<, errors)
|
||||
@@ -3246,6 +3270,33 @@ func parseRemoteLeafNodes(v any, errors *[]error, warnings *[]error) ([]*RemoteL
|
||||
remote.Proxy.Password = pv.(string)
|
||||
case "timeout":
|
||||
remote.Proxy.Timeout = parseDuration("proxy timeout", tk, pv, errors, warnings)
|
||||
case "tls":
|
||||
var unsupported bool
|
||||
tlsMap, _ := pv.(map[string]any)
|
||||
for tlsKey, tlsValue := range tlsMap {
|
||||
ttk, _ := unwrapValue(tlsValue, <)
|
||||
if _, ok := proxyTLSSupportedKeys[strings.ToLower(tlsKey)]; !ok {
|
||||
*errors = append(*errors, &configErr{ttk, fmt.Sprintf("%q is not supported for proxy TLS", tlsKey)})
|
||||
unsupported = true
|
||||
}
|
||||
}
|
||||
if unsupported {
|
||||
continue
|
||||
}
|
||||
tc, err := parseTLS(tk, true)
|
||||
if err != nil {
|
||||
*errors = append(*errors, err)
|
||||
continue
|
||||
}
|
||||
tlsConfig, err := GenTLSConfig(tc)
|
||||
if err != nil {
|
||||
*errors = append(*errors, &configErr{tk, err.Error()})
|
||||
continue
|
||||
}
|
||||
// Used as a client, so ca_file must populate RootCAs.
|
||||
tlsConfig.RootCAs = tlsConfig.ClientCAs
|
||||
remote.Proxy.TLSConfig = tlsConfig
|
||||
remote.Proxy.TLSTimeout = tc.Timeout
|
||||
default:
|
||||
if !tk.IsUsedVariable() {
|
||||
err := &unknownConfigFieldErr{
|
||||
|
||||
+3
-3
@@ -152,9 +152,9 @@ func getCounterArrayData(counter PDH_HCOUNTER) ([]float64, error) {
|
||||
initialBuf := make([]PDH_FMT_COUNTERVALUE_ITEM_DOUBLE, 1)
|
||||
ret := pdhGetFormattedCounterArrayDouble(counter, &bufSize, &bufCount, &initialBuf[0])
|
||||
if ret == PDH_MORE_DATA {
|
||||
// we'll likely never get here, but be safe.
|
||||
if bufCount > maxQuerySize {
|
||||
bufCount = maxQuerySize
|
||||
// Never let the pdh API write past the end of our buffer.
|
||||
if maxSize := uint32(unsafe.Sizeof(counterResults)); bufSize > maxSize {
|
||||
bufSize = maxSize
|
||||
}
|
||||
ret = pdhGetFormattedCounterArrayDouble(counter, &bufSize, &bufCount, &counterResults[0])
|
||||
if ret == 0 {
|
||||
|
||||
+519
-157
File diff suppressed because it is too large.
Load diff
+15
-3
@@ -1002,7 +1002,17 @@ forLoop:
|
||||
"TLS",
|
||||
"TLSHandshakeFirst",
|
||||
"TLSConfig",
|
||||
"Proxy",
|
||||
})
|
||||
if err == nil {
|
||||
// Proxy TLS is always applied, everything else in the proxy must be unchanged.
|
||||
oldProxy, newProxy := lrc.Proxy, rlo.Proxy
|
||||
oldProxy.TLSConfig, oldProxy.TLSTimeout = nil, 0
|
||||
newProxy.TLSConfig, newProxy.TLSTimeout = nil, 0
|
||||
if oldProxy != newProxy {
|
||||
err = fmt.Errorf("field %q: only the proxy TLS configuration can be changed", "Proxy")
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
lrc.RUnlock()
|
||||
s.mu.RUnlock()
|
||||
@@ -1149,6 +1159,8 @@ func (l *leafNodeOption) Apply(s *Server) {
|
||||
lrc.Lock()
|
||||
// TLSConfig is always applied.
|
||||
lrc.TLSConfig = rlo.opts.TLSConfig.Clone()
|
||||
lrc.Proxy.TLSConfig = rlo.opts.Proxy.TLSConfig.Clone()
|
||||
lrc.Proxy.TLSTimeout = rlo.opts.Proxy.TLSTimeout
|
||||
// Now update what has been detected has changed.
|
||||
if rlo.tlsFirstChanged {
|
||||
lrc.TLSHandshakeFirst = rlo.opts.TLSHandshakeFirst
|
||||
@@ -1313,13 +1325,13 @@ func (s *Server) recheckPinnedCerts(curOpts *Options, newOpts *Options) {
|
||||
disconnectClients := []*client{}
|
||||
protoToPinned := map[int]PinnedCertSet{}
|
||||
if !reflect.DeepEqual(newOpts.TLSPinnedCerts, curOpts.TLSPinnedCerts) {
|
||||
protoToPinned[NATS] = curOpts.TLSPinnedCerts
|
||||
protoToPinned[NATS] = newOpts.TLSPinnedCerts
|
||||
}
|
||||
if !reflect.DeepEqual(newOpts.MQTT.TLSPinnedCerts, curOpts.MQTT.TLSPinnedCerts) {
|
||||
protoToPinned[MQTT] = curOpts.MQTT.TLSPinnedCerts
|
||||
protoToPinned[MQTT] = newOpts.MQTT.TLSPinnedCerts
|
||||
}
|
||||
if !reflect.DeepEqual(newOpts.Websocket.TLSPinnedCerts, curOpts.Websocket.TLSPinnedCerts) {
|
||||
protoToPinned[WS] = curOpts.Websocket.TLSPinnedCerts
|
||||
protoToPinned[WS] = newOpts.Websocket.TLSPinnedCerts
|
||||
}
|
||||
for _, c := range s.clients {
|
||||
if c.kind != CLIENT {
|
||||
|
||||
+42
-7
@@ -156,7 +156,7 @@ type Info struct {
|
||||
GatewayURL string `json:"gateway_url,omitempty"` // Gateway URL on that server (sent by route's INFO)
|
||||
GatewayCmd byte `json:"gateway_cmd,omitempty"` // Command code for the receiving server to know what to do
|
||||
GatewayCmdPayload []byte `json:"gateway_cmd_payload,omitempty"` // Command payload when needed
|
||||
GatewayNRP bool `json:"gateway_nrp,omitempty"` // Uses new $GNR. prefix for mapped replies
|
||||
GatewayNRP bool `json:"gateway_nrp,omitempty"` // Uses the _GR_. prefix for mapped replies
|
||||
GatewayIOM bool `json:"gateway_iom,omitempty"` // Indicate that all accounts will be switched to InterestOnly mode "right away"
|
||||
|
||||
// LeafNode Specific
|
||||
@@ -298,7 +298,7 @@ type Server struct {
|
||||
varzUpdateRouteURLs bool
|
||||
|
||||
// Keeps a sublist of subscriptions attached to leafnode connections
|
||||
// for the $GNR.*.*.*.> subject so that a server can send back a mapped
|
||||
// for the _GR_.> subject so that a server can send back a mapped
|
||||
// gateway reply.
|
||||
gwLeafSubs *Sublist
|
||||
|
||||
@@ -1484,6 +1484,33 @@ func (s *Server) configureAccounts(reloading bool) (map[string]struct{}, error)
|
||||
s.mu.Unlock()
|
||||
s.addSystemAccountExports(sysAcc)
|
||||
s.mu.Lock()
|
||||
// On reload the system account's exports were rebuilt from the
|
||||
// options above, which dropped the internally added ones (such as
|
||||
// the JetStream API export) until addSystemAccountExports put them
|
||||
// back. Imports resolved in between were left with a nil export,
|
||||
// so re-resolve them now that every export exists again.
|
||||
if reloading {
|
||||
s.accounts.Range(func(_, v any) bool {
|
||||
acc := v.(*Account)
|
||||
acc.mu.Lock()
|
||||
for _, sis := range acc.imports.services {
|
||||
for _, si := range sis {
|
||||
if si.se != nil || si.acc == nil {
|
||||
continue
|
||||
}
|
||||
if si.acc == acc {
|
||||
si.se = acc.getServiceExport(si.to)
|
||||
continue
|
||||
}
|
||||
si.acc.mu.RLock()
|
||||
si.se = si.acc.getServiceExport(si.to)
|
||||
si.acc.mu.RUnlock()
|
||||
}
|
||||
}
|
||||
acc.mu.Unlock()
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return awcsti, nil
|
||||
@@ -4459,6 +4486,11 @@ func (s *Server) lameDuckMode() {
|
||||
s.listener.Close()
|
||||
s.listener = nil
|
||||
expected += s.closeWebsocketServer()
|
||||
if s.leafNodeListener != nil {
|
||||
expected++
|
||||
s.leafNodeListener.Close()
|
||||
s.leafNodeListener = nil
|
||||
}
|
||||
s.ldmCh = make(chan bool, expected)
|
||||
opts := s.getOpts()
|
||||
gp := opts.LameDuckGracePeriod
|
||||
@@ -4494,7 +4526,7 @@ func (s *Server) lameDuckMode() {
|
||||
|
||||
s.mu.Lock()
|
||||
// Need to recheck few things
|
||||
if s.isShuttingDown() || len(s.clients) == 0 {
|
||||
if s.isShuttingDown() || len(s.clients)+len(s.leafs) == 0 {
|
||||
s.mu.Unlock()
|
||||
// If there is no client, we need to call Shutdown() to complete
|
||||
// the LDMode. If server has been shutdown while lock was released,
|
||||
@@ -4507,9 +4539,9 @@ func (s *Server) lameDuckMode() {
|
||||
if dur <= 0 {
|
||||
dur = int64(time.Second)
|
||||
}
|
||||
numClients := int64(len(s.clients))
|
||||
numClients := int64(len(s.clients) + len(s.leafs))
|
||||
batch := 1
|
||||
// Sleep interval between each client connection close.
|
||||
// Sleep interval between each client or leaf connection close.
|
||||
var si int64
|
||||
if numClients != 0 {
|
||||
si = dur / numClients
|
||||
@@ -4527,11 +4559,14 @@ func (s *Server) lameDuckMode() {
|
||||
si = int64(time.Second)
|
||||
}
|
||||
|
||||
// Now capture all clients
|
||||
clients := make([]*client, 0, len(s.clients))
|
||||
clients := make([]*client, 0, len(s.clients)+len(s.leafs))
|
||||
for _, client := range s.clients {
|
||||
clients = append(clients, client)
|
||||
}
|
||||
for _, leaf := range s.leafs {
|
||||
clients = append(clients, leaf)
|
||||
}
|
||||
rand.Shuffle(len(clients), func(i, j int) { clients[i], clients[j] = clients[j], clients[i] })
|
||||
// Now that we know that no new client can be accepted,
|
||||
// send INFO to routes and clients to notify this state.
|
||||
s.sendLDMToRoutes()
|
||||
|
||||
+75
-7
@@ -301,12 +301,14 @@ func (ack BatchFlowAck) MarshalJSON() ([]byte, error) {
|
||||
}
|
||||
|
||||
// BatchFlowGap is used for reporting gaps when fast batch publishing into a stream.
|
||||
// A forward gap means messages were lost, a backward gap means a message was duplicated or reordered.
|
||||
// This message is purely informational and could technically be lost without the client receiving it.
|
||||
type BatchFlowGap struct {
|
||||
// Type: "gap"
|
||||
Type string `json:"type"`
|
||||
// ExpectedLastSequence is the sequence expected to be received next.
|
||||
// Messages starting from ExpectedLastSequence up to (but not including) CurrentSequence were lost.
|
||||
// If CurrentSequence is higher, messages starting from ExpectedLastSequence up to (but not including) CurrentSequence were lost.
|
||||
// If CurrentSequence is lower or equal, it's a backward gap and the batch is ended, the PubAck confirms what was persisted.
|
||||
ExpectedLastSequence uint64 `json:"last_seq"`
|
||||
// CurrentSequence is the sequence of the message that just came in and detected the gap.
|
||||
CurrentSequence uint64 `json:"seq"`
|
||||
@@ -713,6 +715,8 @@ type sourceInfo struct {
|
||||
lag uint64 // 0 or number of messages pending (as last reported by the consumer) - 1.
|
||||
err *ApiError // The API error that caused the last consumer setup to fail.
|
||||
fails int // The number of times trying to setup the consumer failed.
|
||||
fcid string // The last flow control reply subject the consumer reported being stalled on.
|
||||
fcsc int // Consecutive heartbeats reporting the same stalled flow control reply subject.
|
||||
last atomic.Int64 // Time the consumer was created or of last message it received.
|
||||
lreq time.Time // The last time setupMirrorConsumer/setupSourceConsumer was called.
|
||||
qch chan struct{} // Quit channel.
|
||||
@@ -1256,6 +1260,21 @@ func (ssi *StreamSource) setIndexName() {
|
||||
ssi.iname = ssi.composeIName()
|
||||
}
|
||||
|
||||
// matchSourceIndexNames sets the index names on cfg's sources only if they are also set on ocfg's sources.
|
||||
// The index name is not encoded, so this ensures a DeepEqual of both configs can succeed.
|
||||
func matchSourceIndexNames(cfg *StreamConfig, ocfg *StreamConfig) {
|
||||
currentIName := make(map[string]struct{}, len(ocfg.Sources))
|
||||
for _, s := range ocfg.Sources {
|
||||
currentIName[s.iname] = struct{}{}
|
||||
}
|
||||
for _, s := range cfg.Sources {
|
||||
s.setIndexName()
|
||||
if _, ok := currentIName[s.iname]; !ok {
|
||||
s.iname = _EMPTY_
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Composes the consumer index name. Contains the stream name and consumer name used for durable sourcing (if any).
|
||||
// When the stream is external we will use the api prefix as part of the index name
|
||||
// (as the same stream and consumer names could be used in multiple JS domains)
|
||||
@@ -3498,7 +3517,9 @@ func (mset *stream) processInboundMirrorMsg(m *inMsg) bool {
|
||||
needsRetry = true
|
||||
} else if fcReply := sliceHeader(JSConsumerStalled, m.hdr); len(fcReply) > 0 {
|
||||
// Other side thinks we are stalled, so send flow control reply.
|
||||
mset.outq.sendMsg(string(fcReply), nil)
|
||||
mset.processStalledFlowControl(mset.mirror, string(fcReply))
|
||||
} else {
|
||||
mset.clearStalledFlowControl(mset.mirror)
|
||||
}
|
||||
}
|
||||
mset.mu.Unlock()
|
||||
@@ -3555,6 +3576,8 @@ func (mset *stream) processInboundMirrorMsg(m *inMsg) bool {
|
||||
} else {
|
||||
mset.mirror.lag = pending - 1
|
||||
}
|
||||
// Receiving messages means we are not stalled on flow control.
|
||||
mset.clearStalledFlowControl(mset.mirror)
|
||||
|
||||
// Check if we allow mirror direct here. If so check they we have mostly caught up.
|
||||
// The reason we do not require 0 is if the source is active we may always be slightly behind.
|
||||
@@ -4125,6 +4148,7 @@ func (mset *stream) setupMirrorConsumer() error {
|
||||
// Capture consumer name.
|
||||
mirror.cname = ccr.ConsumerInfo.Name
|
||||
mirror.dseq = 0
|
||||
mirror.fcid, mirror.fcsc = _EMPTY_, 0
|
||||
mirror.sseq = max(ccr.ConsumerInfo.Delivered.Stream, state.LastSeq)
|
||||
mirror.qch = make(chan struct{})
|
||||
mirror.wg.Add(1)
|
||||
@@ -4636,6 +4660,7 @@ func (mset *stream) trySetupSourceConsumer(iname string, seq uint64, startTime t
|
||||
|
||||
// Do not set si.sseq to seq here. si.sseq will be set in processInboundSourceMsg
|
||||
si.dseq = 0
|
||||
si.fcid, si.fcsc = _EMPTY_, 0
|
||||
si.qch = make(chan struct{})
|
||||
// Set the last seen as now so that we don't fail at the first check.
|
||||
si.last.Store(time.Now().UnixNano())
|
||||
@@ -4798,6 +4823,43 @@ func (mset *stream) handleFlowControl(m *inMsg, dseq, sseq uint64) {
|
||||
}
|
||||
}
|
||||
|
||||
// Number of consecutive heartbeats reporting the same stalled flow control reply
|
||||
// before we consider our replies to not be reaching the consumer.
|
||||
const sourceFCStalledThreshold = 3
|
||||
|
||||
// processStalledFlowControl sends the flow control reply the consumer reports being stalled on.
|
||||
// If it keeps reporting the same one, our replies are not reaching it, so report an error.
|
||||
// Lock should be held.
|
||||
func (mset *stream) processStalledFlowControl(si *sourceInfo, fcReply string) {
|
||||
if fcReply != si.fcid {
|
||||
si.fcid, si.fcsc = fcReply, 0
|
||||
}
|
||||
si.fcsc++
|
||||
// Warn exactly once per stall.
|
||||
if si.fcsc == sourceFCStalledThreshold {
|
||||
si.err = NewJSSourceConsumerFlowControlStalledError()
|
||||
kind := "source"
|
||||
if si == mset.mirror {
|
||||
kind = "mirror"
|
||||
}
|
||||
mset.srv.Warnf("JetStream stream '%s > %s' %s '%s' is stalled on flow control, replies are not reaching the consumer",
|
||||
mset.acc.Name, mset.cfg.Name, kind, si.name)
|
||||
}
|
||||
mset.outq.sendMsg(fcReply, nil)
|
||||
}
|
||||
|
||||
// clearStalledFlowControl resets stalled flow control tracking once the consumer is no longer stalled.
|
||||
// Lock should be held.
|
||||
func (mset *stream) clearStalledFlowControl(si *sourceInfo) {
|
||||
if si.fcid == _EMPTY_ {
|
||||
return
|
||||
}
|
||||
si.fcid, si.fcsc = _EMPTY_, 0
|
||||
if si.err != nil && si.err.ErrCode == uint16(JSSourceConsumerFlowControlStalledErr) {
|
||||
si.err = nil
|
||||
}
|
||||
}
|
||||
|
||||
// processInboundSourceMsg handles processing other stream messages bound for this stream.
|
||||
func (mset *stream) processInboundSourceMsg(si *sourceInfo, m *inMsg) bool {
|
||||
mset.mu.Lock()
|
||||
@@ -4830,7 +4892,9 @@ func (mset *stream) processInboundSourceMsg(si *sourceInfo, m *inMsg) bool {
|
||||
mset.retrySourceConsumerAtSeq(si.iname, si.sseq+1)
|
||||
} else if fcReply := sliceHeader(JSConsumerStalled, m.hdr); len(fcReply) > 0 {
|
||||
// Other side thinks we are stalled, so send flow control reply.
|
||||
mset.outq.sendMsg(string(fcReply), nil)
|
||||
mset.processStalledFlowControl(si, string(fcReply))
|
||||
} else {
|
||||
mset.clearStalledFlowControl(si)
|
||||
}
|
||||
}
|
||||
mset.mu.Unlock()
|
||||
@@ -4876,6 +4940,8 @@ func (mset *stream) processInboundSourceMsg(si *sourceInfo, m *inMsg) bool {
|
||||
} else {
|
||||
si.lag = pending - 1
|
||||
}
|
||||
// Receiving messages means we are not stalled on flow control.
|
||||
mset.clearStalledFlowControl(si)
|
||||
node, ident := mset.node, si.ident
|
||||
mset.mu.Unlock()
|
||||
|
||||
@@ -8080,7 +8146,8 @@ func (mset *stream) processJetStreamFastBatchMsg(batch *FastBatch, subject, repl
|
||||
// Get batch.
|
||||
b, ok := batches.fast[batch.id]
|
||||
if !ok {
|
||||
if batch.seq != 1 {
|
||||
// A new batch can only be started at sequence 1 and not by a ping.
|
||||
if batch.seq != 1 || batch.ping {
|
||||
batches.mu.Unlock()
|
||||
mset.mu.Unlock()
|
||||
return respondError(NewJSBatchPublishUnknownBatchIDError())
|
||||
@@ -8172,8 +8239,8 @@ func (mset *stream) processJetStreamFastBatchMsg(batch *FastBatch, subject, repl
|
||||
// Detect gaps.
|
||||
b.lseq++
|
||||
if b.lseq != batch.seq || cleanup {
|
||||
// If a forward gap is detected, we always report about it.
|
||||
if batch.seq > b.lseq {
|
||||
// If a forward or backward gap is detected, we always report about it.
|
||||
if batch.seq != b.lseq {
|
||||
buf, _ := BatchFlowGap{ExpectedLastSequence: b.lseq, CurrentSequence: batch.seq}.MarshalJSON()
|
||||
outq.sendMsg(reply, buf)
|
||||
}
|
||||
@@ -8970,8 +9037,9 @@ func (mset *stream) checkInterestState() {
|
||||
rp := mset.cfg.Retention
|
||||
mset.cfgMu.RUnlock()
|
||||
// Remove as many messages from the "head" of the stream if there's no interest anymore.
|
||||
// Only compact up to the current stream state, consumers may be ahead while replaying.
|
||||
if rp == InterestPolicy && asflr != math.MaxUint64 {
|
||||
mset.store.Compact(asflr)
|
||||
mset.store.Compact(min(asflr, ss.LastSeq+1))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+6
-1
@@ -189,8 +189,13 @@ func (js *jetStream) streamSnapshotV2(store StreamStore, state *StreamState, w i
|
||||
errCh <- fmt.Errorf("failed to get consumer state for '%s > %s'", sa.Config.Name, ca.Name)
|
||||
return
|
||||
}
|
||||
// Ephemeral clustered consumers are named by their assignment. Their
|
||||
// original config may not carry that generated name, but snapshots
|
||||
// need it both for the archive entry and for restoration.
|
||||
config := *ca.Config
|
||||
config.Name = ca.Name
|
||||
if err := writeConsumerMsg(SnapshotConsumerState{
|
||||
ConsumerConfig: ca.Config,
|
||||
ConsumerConfig: &config,
|
||||
ConsumerState: consumerStateFromInfo(ci),
|
||||
}); err != nil {
|
||||
errCh <- err
|
||||
|
||||
+37
-12
@@ -61,6 +61,10 @@ type SublistResult struct {
|
||||
qsubs [][]*subscription // don't make this a map, too expensive to iterate
|
||||
}
|
||||
|
||||
// SublistFilter is a function that is used to decide if a subscription should
|
||||
// be returned by the Filter() call.
|
||||
type SublistFilter func(sub *subscription) bool
|
||||
|
||||
// A Sublist stores and efficiently retrieves subscriptions.
|
||||
type Sublist struct {
|
||||
sync.RWMutex
|
||||
@@ -175,7 +179,9 @@ func (s *Sublist) registerNotification(subject, queue string, notify chan<- bool
|
||||
}
|
||||
|
||||
var hasInterest bool
|
||||
r := s.Match(subject)
|
||||
// Match under the lock so a concurrent insert or remove can't be missed.
|
||||
s.Lock()
|
||||
r := s.matchNoLock(subject)
|
||||
|
||||
if len(r.psubs)+len(r.qsubs) > 0 {
|
||||
if queue == _EMPTY_ {
|
||||
@@ -199,7 +205,6 @@ func (s *Sublist) registerNotification(subject, queue string, notify chan<- bool
|
||||
key := keyFromSubjectAndQueue(subject, queue)
|
||||
var err error
|
||||
|
||||
s.Lock()
|
||||
if s.notify == nil {
|
||||
s.notify = ¬ifyMaps{
|
||||
insert: make(map[string][]chan<- bool),
|
||||
@@ -1619,39 +1624,59 @@ func (s *Sublist) localSubs(subs *[]*subscription, includeLeafHubs bool) {
|
||||
// All is used to collect all subscriptions.
|
||||
func (s *Sublist) All(subs *[]*subscription) {
|
||||
s.RLock()
|
||||
s.collectAllSubs(s.root, subs)
|
||||
s.collectAllSubs(s.root, subs, nil)
|
||||
s.RUnlock()
|
||||
}
|
||||
|
||||
func (s *Sublist) addAllNodeToSubs(n *node, subs *[]*subscription) {
|
||||
func (s *Sublist) Filter(subs *[]*subscription, filter SublistFilter) {
|
||||
s.RLock()
|
||||
s.collectAllSubs(s.root, subs, filter)
|
||||
s.RUnlock()
|
||||
}
|
||||
|
||||
func (s *Sublist) addAllNodeToSubs(n *node, subs *[]*subscription, filter SublistFilter) {
|
||||
// Normal subscriptions
|
||||
if n.plist != nil {
|
||||
*subs = append(*subs, n.plist...)
|
||||
if filter == nil {
|
||||
*subs = append(*subs, n.plist...)
|
||||
} else {
|
||||
for _, sub := range n.plist {
|
||||
if filter(sub) {
|
||||
*subs = append(*subs, sub)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for sub := range n.psubs {
|
||||
if filter != nil && !filter(sub) {
|
||||
continue
|
||||
}
|
||||
*subs = append(*subs, sub)
|
||||
}
|
||||
}
|
||||
// Queue subscriptions
|
||||
for _, qr := range n.qsubs {
|
||||
for sub := range qr {
|
||||
if filter != nil && !filter(sub) {
|
||||
continue
|
||||
}
|
||||
*subs = append(*subs, sub)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Sublist) collectAllSubs(l *level, subs *[]*subscription) {
|
||||
func (s *Sublist) collectAllSubs(l *level, subs *[]*subscription, filter SublistFilter) {
|
||||
for _, n := range l.nodes {
|
||||
s.addAllNodeToSubs(n, subs)
|
||||
s.collectAllSubs(n.next, subs)
|
||||
s.addAllNodeToSubs(n, subs, filter)
|
||||
s.collectAllSubs(n.next, subs, filter)
|
||||
}
|
||||
if l.pwc != nil {
|
||||
s.addAllNodeToSubs(l.pwc, subs)
|
||||
s.collectAllSubs(l.pwc.next, subs)
|
||||
s.addAllNodeToSubs(l.pwc, subs, filter)
|
||||
s.collectAllSubs(l.pwc.next, subs, filter)
|
||||
}
|
||||
if l.fwc != nil {
|
||||
s.addAllNodeToSubs(l.fwc, subs)
|
||||
s.collectAllSubs(l.fwc.next, subs)
|
||||
s.addAllNodeToSubs(l.fwc, subs, filter)
|
||||
s.collectAllSubs(l.fwc.next, subs, filter)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go
Generated
Vendored
+1
-1
@@ -39,7 +39,7 @@ func init() {
|
||||
// token = 1*<any CHAR except CTLs or separators>
|
||||
// qdtext = <any TEXT except <">>
|
||||
|
||||
for c := 0; c < 256; c++ {
|
||||
for c := range 256 {
|
||||
var t octetType
|
||||
isCtl := c <= 31 || c == 127
|
||||
isChar := 0 <= c && c <= 127
|
||||
|
||||
+2
-1
@@ -32,7 +32,8 @@ func NewBuildInfoCollector() Collector {
|
||||
"Build information about the main Go module.",
|
||||
nil, Labels{"path": path, "version": version, "checksum": sum},
|
||||
),
|
||||
GaugeValue, 1)}
|
||||
GaugeValue, 1,
|
||||
)}
|
||||
c.init(c.self)
|
||||
return c
|
||||
}
|
||||
+2
-3
@@ -21,7 +21,6 @@ import (
|
||||
"github.com/cespare/xxhash/v2"
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
"github.com/prometheus/common/model"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/internal"
|
||||
)
|
||||
@@ -181,8 +180,8 @@ func (v2) NewDesc(fqName, help string, variableLabels ConstrainableLabels, const
|
||||
d.constLabelPairs = make([]*dto.LabelPair, 0, len(constLabels))
|
||||
for n, v := range constLabels {
|
||||
d.constLabelPairs = append(d.constLabelPairs, &dto.LabelPair{
|
||||
Name: proto.String(n),
|
||||
Value: proto.String(v),
|
||||
Name: new(n),
|
||||
Value: new(v),
|
||||
})
|
||||
}
|
||||
sort.Sort(internal.LabelPairSorter(d.constLabelPairs))
|
||||
|
||||
-1
@@ -12,7 +12,6 @@
|
||||
// limitations under the License.
|
||||
|
||||
//go:build !js || wasm
|
||||
// +build !js wasm
|
||||
|
||||
package prometheus
|
||||
|
||||
|
||||
-1
@@ -12,7 +12,6 @@
|
||||
// limitations under the License.
|
||||
|
||||
//go:build js && !wasm
|
||||
// +build js,!wasm
|
||||
|
||||
package prometheus
|
||||
|
||||
|
||||
+10
-5
@@ -211,23 +211,28 @@ func newBaseGoCollector() baseGoCollector {
|
||||
goroutinesDesc: NewDesc(
|
||||
"go_goroutines",
|
||||
"Number of goroutines that currently exist.",
|
||||
nil, nil),
|
||||
nil, nil,
|
||||
),
|
||||
threadsDesc: NewDesc(
|
||||
"go_threads",
|
||||
"Number of OS threads created.",
|
||||
nil, nil),
|
||||
nil, nil,
|
||||
),
|
||||
gcDesc: NewDesc(
|
||||
"go_gc_duration_seconds",
|
||||
"A summary of the wall-time pause (stop-the-world) duration in garbage collection cycles.",
|
||||
nil, nil),
|
||||
nil, nil,
|
||||
),
|
||||
gcLastTimeDesc: NewDesc(
|
||||
"go_memstats_last_gc_time_seconds",
|
||||
"Number of seconds since 1970 of last garbage collection.",
|
||||
nil, nil),
|
||||
nil, nil,
|
||||
),
|
||||
goInfoDesc: NewDesc(
|
||||
"go_info",
|
||||
"Information about the Go environment.",
|
||||
nil, Labels{"version": runtime.Version()}),
|
||||
nil, Labels{"version": runtime.Version()},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+4
-8
@@ -11,9 +11,6 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//go:build go1.17
|
||||
// +build go1.17
|
||||
|
||||
package prometheus
|
||||
|
||||
import (
|
||||
@@ -27,7 +24,6 @@ import (
|
||||
"github.com/prometheus/client_golang/prometheus/internal"
|
||||
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -573,14 +569,14 @@ func (h *batchHistogram) Write(out *dto.Metric) error {
|
||||
// by obtaining the next float64 value down, in order.
|
||||
upperBound := math.Nextafter(h.buckets[i+1], h.buckets[i])
|
||||
dtoBuckets = append(dtoBuckets, &dto.Bucket{
|
||||
CumulativeCount: proto.Uint64(totalCount),
|
||||
UpperBound: proto.Float64(upperBound),
|
||||
CumulativeCount: new(totalCount),
|
||||
UpperBound: new(upperBound),
|
||||
})
|
||||
}
|
||||
out.Histogram = &dto.Histogram{
|
||||
Bucket: dtoBuckets,
|
||||
SampleCount: proto.Uint64(totalCount),
|
||||
SampleSum: proto.Float64(sum),
|
||||
SampleCount: new(totalCount),
|
||||
SampleSum: new(sum),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+21
-21
@@ -803,8 +803,8 @@ func (h *histogram) Write(out *dto.Metric) error {
|
||||
|
||||
his := &dto.Histogram{
|
||||
Bucket: make([]*dto.Bucket, len(h.upperBounds)),
|
||||
SampleCount: proto.Uint64(count),
|
||||
SampleSum: proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))),
|
||||
SampleCount: new(count),
|
||||
SampleSum: new(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))),
|
||||
CreatedTimestamp: timestamppb.New(h.lastResetTime),
|
||||
}
|
||||
out.Histogram = his
|
||||
@@ -814,8 +814,8 @@ func (h *histogram) Write(out *dto.Metric) error {
|
||||
for i, upperBound := range h.upperBounds {
|
||||
cumCount += atomic.LoadUint64(&coldCounts.buckets[i])
|
||||
his.Bucket[i] = &dto.Bucket{
|
||||
CumulativeCount: proto.Uint64(cumCount),
|
||||
UpperBound: proto.Float64(upperBound),
|
||||
CumulativeCount: new(cumCount),
|
||||
UpperBound: new(upperBound),
|
||||
}
|
||||
if e := h.exemplars[i].Load(); e != nil {
|
||||
his.Bucket[i].Exemplar = e.(*dto.Exemplar)
|
||||
@@ -824,15 +824,15 @@ func (h *histogram) Write(out *dto.Metric) error {
|
||||
// If there is an exemplar for the +Inf bucket, we have to add that bucket explicitly.
|
||||
if e := h.exemplars[len(h.upperBounds)].Load(); e != nil {
|
||||
b := &dto.Bucket{
|
||||
CumulativeCount: proto.Uint64(count),
|
||||
UpperBound: proto.Float64(math.Inf(1)),
|
||||
CumulativeCount: new(count),
|
||||
UpperBound: new(math.Inf(1)),
|
||||
Exemplar: e.(*dto.Exemplar),
|
||||
}
|
||||
his.Bucket = append(his.Bucket, b)
|
||||
}
|
||||
if h.nativeHistogramSchema > math.MinInt32 {
|
||||
his.ZeroThreshold = proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.nativeHistogramZeroThresholdBits)))
|
||||
his.Schema = proto.Int32(atomic.LoadInt32(&coldCounts.nativeHistogramSchema))
|
||||
his.ZeroThreshold = new(math.Float64frombits(atomic.LoadUint64(&coldCounts.nativeHistogramZeroThresholdBits)))
|
||||
his.Schema = new(atomic.LoadInt32(&coldCounts.nativeHistogramSchema))
|
||||
zeroBucket := atomic.LoadUint64(&coldCounts.nativeHistogramZeroBucket)
|
||||
|
||||
defer func() {
|
||||
@@ -840,7 +840,7 @@ func (h *histogram) Write(out *dto.Metric) error {
|
||||
coldCounts.nativeHistogramBucketsNegative.Range(addAndReset(&hotCounts.nativeHistogramBucketsNegative, &hotCounts.nativeHistogramBucketsNumber))
|
||||
}()
|
||||
|
||||
his.ZeroCount = proto.Uint64(zeroBucket)
|
||||
his.ZeroCount = new(zeroBucket)
|
||||
his.NegativeSpan, his.NegativeDelta = makeBuckets(&coldCounts.nativeHistogramBucketsNegative)
|
||||
his.PositiveSpan, his.PositiveDelta = makeBuckets(&coldCounts.nativeHistogramBucketsPositive)
|
||||
|
||||
@@ -1331,12 +1331,12 @@ func (h *constHistogram) Write(out *dto.Metric) error {
|
||||
|
||||
buckets := make([]*dto.Bucket, 0, len(h.buckets))
|
||||
|
||||
his.SampleCount = proto.Uint64(h.count)
|
||||
his.SampleSum = proto.Float64(h.sum)
|
||||
his.SampleCount = new(h.count)
|
||||
his.SampleSum = new(h.sum)
|
||||
for upperBound, count := range h.buckets {
|
||||
buckets = append(buckets, &dto.Bucket{
|
||||
CumulativeCount: proto.Uint64(count),
|
||||
UpperBound: proto.Float64(upperBound),
|
||||
CumulativeCount: new(count),
|
||||
UpperBound: new(upperBound),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1481,7 +1481,7 @@ func pickSchema(bucketFactor float64) int32 {
|
||||
|
||||
func makeBuckets(buckets *sync.Map) ([]*dto.BucketSpan, []int64) {
|
||||
var ii []int
|
||||
buckets.Range(func(k, v any) bool {
|
||||
buckets.Range(func(k, _ any) bool {
|
||||
ii = append(ii, k.(int))
|
||||
return true
|
||||
})
|
||||
@@ -1518,13 +1518,13 @@ func makeBuckets(buckets *sync.Map) ([]*dto.BucketSpan, []int64) {
|
||||
// at the very beginning, or because we have found a gap
|
||||
// of more than two buckets.
|
||||
spans = append(spans, &dto.BucketSpan{
|
||||
Offset: proto.Int32(iDelta),
|
||||
Offset: new(iDelta),
|
||||
Length: proto.Uint32(0),
|
||||
})
|
||||
} else {
|
||||
// We have found a small gap (or no gap at all).
|
||||
// Insert empty buckets as needed.
|
||||
for j := int32(0); j < iDelta; j++ {
|
||||
for range iDelta {
|
||||
appendDelta(0)
|
||||
}
|
||||
}
|
||||
@@ -1570,7 +1570,7 @@ func addAndReset(hotBuckets *sync.Map, bucketNumber *uint32) func(k, v any) bool
|
||||
}
|
||||
|
||||
func deleteSyncMap(m *sync.Map) {
|
||||
m.Range(func(k, v any) bool {
|
||||
m.Range(func(k, _ any) bool {
|
||||
m.Delete(k)
|
||||
return true
|
||||
})
|
||||
@@ -1578,7 +1578,7 @@ func deleteSyncMap(m *sync.Map) {
|
||||
|
||||
func findSmallestKey(m *sync.Map) int {
|
||||
result := math.MaxInt32
|
||||
m.Range(func(k, v any) bool {
|
||||
m.Range(func(k, _ any) bool {
|
||||
key := k.(int)
|
||||
if key < result {
|
||||
result = key
|
||||
@@ -1956,7 +1956,7 @@ func NewConstNativeHistogram(
|
||||
PositiveSpan: PositiveSpan,
|
||||
PositiveDelta: PositiveDelta,
|
||||
|
||||
ZeroCount: proto.Uint64(zeroBucket),
|
||||
ZeroCount: new(zeroBucket),
|
||||
},
|
||||
labelPairs: MakeLabelPairs(desc, labelValues),
|
||||
}
|
||||
@@ -2044,13 +2044,13 @@ func makeBucketsFromMap(buckets map[int]int64) ([]*dto.BucketSpan, []int64) {
|
||||
// at the very beginning, or because we have found a gap
|
||||
// of more than two buckets.
|
||||
spans = append(spans, &dto.BucketSpan{
|
||||
Offset: proto.Int32(iDelta),
|
||||
Offset: new(iDelta),
|
||||
Length: proto.Uint32(0),
|
||||
})
|
||||
} else {
|
||||
// We have found a small gap (or no gap at all).
|
||||
// Insert empty buckets as needed.
|
||||
for j := int32(0); j < iDelta; j++ {
|
||||
for range iDelta {
|
||||
appendDelta(0)
|
||||
}
|
||||
}
|
||||
|
||||
Generated
Vendored
-3
@@ -11,9 +11,6 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//go:build go1.17
|
||||
// +build go1.17
|
||||
|
||||
package internal
|
||||
|
||||
import (
|
||||
|
||||
+3
-4
@@ -22,7 +22,6 @@ import (
|
||||
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
"github.com/prometheus/common/model"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
var separatorByteSlice = []byte{model.SeparatorByte} // For convenient use with xxhash.
|
||||
@@ -153,7 +152,7 @@ type timestampedMetric struct {
|
||||
|
||||
func (m timestampedMetric) Write(pb *dto.Metric) error {
|
||||
e := m.Metric.Write(pb)
|
||||
pb.TimestampMs = proto.Int64(m.t.Unix()*1000 + int64(m.t.Nanosecond()/1000000))
|
||||
pb.TimestampMs = new(m.t.Unix()*1000 + int64(m.t.Nanosecond()/1000000))
|
||||
return e
|
||||
}
|
||||
|
||||
@@ -209,8 +208,8 @@ func (m *withExemplarsMetric) Write(pb *dto.Metric) error {
|
||||
} else {
|
||||
// The +Inf bucket should be explicitly added if there is an exemplar for it, similar to non-const histogram logic in https://github.com/prometheus/client_golang/blob/main/prometheus/histogram.go#L357-L365.
|
||||
b := &dto.Bucket{
|
||||
CumulativeCount: proto.Uint64(h.GetSampleCount()),
|
||||
UpperBound: proto.Float64(math.Inf(1)),
|
||||
CumulativeCount: new(h.GetSampleCount()),
|
||||
UpperBound: new(math.Inf(1)),
|
||||
Exemplar: e,
|
||||
}
|
||||
h.Bucket = append(h.Bucket, b)
|
||||
|
||||
Loaded 100 of 221 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user