chore: [stable-8.2] bump go and web packages (#12775)

chore: bump go and web packages (#12765)

* chore: bump go packages

* chore: bump web packages
This commit is contained in:
Michal Klos authored and GitHub committed 2026-08-12 13:29:50 +02:00
1 parent 42f7fdcfee
commit b7d887527b
525 files changed
+49044 -10658

No files matched your search

+30 -30
View File
@@ -20,7 +20,7 @@ require (
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8
github.com/dutchcoders/go-clamd v0.0.0-20170520113014-b970184f4d9e
github.com/egirna/icap-client v0.1.1
github.com/gabriel-vasile/mimetype v1.4.13
github.com/gabriel-vasile/mimetype v1.4.15
github.com/ggwhite/go-masker v1.1.0
github.com/go-chi/chi/v5 v5.3.1
github.com/go-chi/httprate v0.16.0
@@ -45,7 +45,7 @@ require (
github.com/gookit/config/v2 v2.2.9
github.com/gorilla/mux v1.8.1
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0
github.com/invopop/validation v0.8.0
github.com/jellydator/ttlcache/v2 v2.11.1
github.com/jellydator/ttlcache/v3 v3.4.1
@@ -58,21 +58,21 @@ 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.14.3
github.com/nats-io/nats-server/v2 v2.14.4
github.com/nats-io/nats.go v1.52.0
github.com/olekukonko/tablewriter v1.1.4
github.com/onsi/ginkgo v1.16.5
github.com/onsi/ginkgo/v2 v2.32.0
github.com/onsi/gomega v1.42.1
github.com/open-policy-agent/opa v1.18.2
github.com/open-policy-agent/opa v1.19.0
github.com/orcaman/concurrent-map v1.0.0
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
github.com/owncloud/reva/v2 v2.0.0-20260807092659-5e5d7767ea70
github.com/pkg/errors v0.9.1
github.com/pkg/xattr v0.4.12
github.com/prometheus/client_golang v1.23.2
github.com/prometheus/client_golang v1.24.1
github.com/r3labs/sse/v2 v2.10.0
github.com/rogpeppe/go-internal v1.15.0
github.com/rogpeppe/go-internal v1.16.0
github.com/rs/cors v1.11.1
github.com/rs/zerolog v1.35.1
github.com/shamaton/msgpack/v2 v2.4.1
@@ -89,14 +89,14 @@ require (
github.com/xhit/go-simple-mail/v2 v2.16.0
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.69.0
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0
go.opentelemetry.io/contrib/zpages v0.69.0
go.opentelemetry.io/otel v1.44.0
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0
go.opentelemetry.io/contrib/zpages v0.70.0
go.opentelemetry.io/otel v1.45.0
go.opentelemetry.io/otel/exporters/jaeger v1.17.0
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0
go.opentelemetry.io/otel/sdk v1.44.0
go.opentelemetry.io/otel/trace v1.44.0
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0
go.opentelemetry.io/otel/sdk v1.45.0
go.opentelemetry.io/otel/trace v1.45.0
golang.org/x/crypto v0.54.0
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f
golang.org/x/image v0.44.0
@@ -105,8 +105,8 @@ require (
golang.org/x/sync v0.22.0
golang.org/x/term v0.45.0
golang.org/x/text v0.40.0
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa
google.golang.org/grpc v1.82.1
google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d
google.golang.org/grpc v1.83.0
google.golang.org/protobuf v1.36.11
gopkg.in/yaml.v2 v2.4.0
gopkg.in/yaml.v3 v3.0.1
@@ -129,7 +129,7 @@ require (
github.com/ajg/form v1.5.1 // indirect
github.com/alexedwards/argon2id v1.0.0 // indirect
github.com/amoghe/go-crypt v0.0.0-20220222110647-20eada5f5964 // indirect
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op // indirect
github.com/antithesishq/antithesis-sdk-go v0.7.2-default-no-op // indirect
github.com/armon/go-radix v1.0.0 // indirect
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
github.com/aws/aws-sdk-go v1.55.8 // indirect
@@ -183,7 +183,7 @@ require (
github.com/emvi/iso-639-1 v1.1.1 // indirect
github.com/evanphx/json-patch/v5 v5.5.0 // indirect
github.com/fatih/color v1.19.0 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/felixge/httpsnoop v1.1.0 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/gdexlab/go-render v1.0.1 // indirect
github.com/go-acme/lego/v4 v4.34.0 // indirect
@@ -195,7 +195,7 @@ require (
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
github.com/go-kit/log v0.2.1 // indirect
github.com/go-logfmt/logfmt v0.5.1 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-micro/plugins/v4/events/natsjs v1.2.2 // indirect
github.com/go-micro/plugins/v4/store/nats-js v1.2.1 // indirect
@@ -241,7 +241,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.18.6 // indirect
github.com/klauspost/compress v1.19.1 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/klauspost/crc32 v1.3.0 // indirect
github.com/kovidgoyal/go-parallel v1.1.1 // indirect
@@ -261,7 +261,7 @@ require (
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.21 // indirect
github.com/mattn/go-runewidth v0.0.23 // indirect
github.com/mattn/go-sqlite3 v1.14.47 // indirect
github.com/mattn/go-sqlite3 v1.14.49 // indirect
github.com/maxymania/go-system v0.0.0-20170110133659-647cc364bf0b // indirect
github.com/mendsley/gojwk v0.0.0-20141217222730-4d5ec6e58103 // indirect
github.com/miekg/dns v1.1.72 // indirect
@@ -296,8 +296,8 @@ require (
github.com/pquerna/cachecontrol v0.2.0 // indirect
github.com/prometheus/alertmanager v0.33.1 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.67.5 // indirect
github.com/prometheus/procfs v0.20.1 // indirect
github.com/prometheus/common v0.70.1 // indirect
github.com/prometheus/procfs v0.21.1 // 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
@@ -309,7 +309,7 @@ require (
github.com/segmentio/ksuid v1.0.4 // indirect
github.com/sercand/kuberesolver/v5 v5.1.1 // indirect
github.com/sergi/go-diff v1.4.0 // indirect
github.com/sethvargo/go-password v0.3.1 // indirect
github.com/sethvargo/go-password v0.4.0 // indirect
github.com/skeema/knownhosts v1.3.1 // indirect
github.com/spacewander/go-suffix-tree v0.0.0-20191010040751-0865e368c784 // indirect
github.com/spf13/pflag v1.0.10 // indirect
@@ -322,7 +322,7 @@ require (
github.com/toorop/go-dkim v0.0.0-20201103131630-e1cd1a0a5208 // indirect
github.com/trustelem/zxcvbn v1.0.1 // indirect
github.com/valyala/fastjson v1.6.10 // indirect
github.com/vektah/gqlparser/v2 v2.5.34 // indirect
github.com/vektah/gqlparser/v2 v2.5.36 // indirect
github.com/wk8/go-ordered-map v1.0.0 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
@@ -335,19 +335,19 @@ require (
go.etcd.io/etcd/client/v3 v3.6.13 // indirect
go.opencensus.io v0.24.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect
go.opentelemetry.io/otel/metric v1.44.0 // indirect
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 // indirect
go.opentelemetry.io/otel/metric v1.45.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.0 // indirect
go.uber.org/zap v1.27.1 // indirect
go.yaml.in/yaml/v2 v2.4.4 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/mod v0.37.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/time v0.15.0 // indirect
golang.org/x/tools v0.47.0 // indirect
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d // indirect
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
gopkg.in/ini.v1 v1.67.3 // indirect
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
+66 -65
View File
@@ -90,8 +90,8 @@ github.com/amoghe/go-crypt v0.0.0-20220222110647-20eada5f5964 h1:I9YN9WMo3SUh7p/
github.com/amoghe/go-crypt v0.0.0-20220222110647-20eada5f5964/go.mod h1:eFiR01PwTcpbzXtdMces7zxg6utvFM5puiWHpWB8D/k=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op h1:Z/MZK75wC/NSrkgqeNIa7jexam9uWzhLmFTSCPI/kn0=
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI=
github.com/antithesishq/antithesis-sdk-go v0.7.2-default-no-op h1:p2zFsAzvhIpFya8AIOHIbWf7NGvO34QpLGclyf7nXj8=
github.com/antithesishq/antithesis-sdk-go v0.7.2-default-no-op/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE=
github.com/armon/go-radix v1.0.0 h1:F4z6KzEeeQIMeLFa97iZU6vupzoecKdU5TX24SNppXI=
@@ -162,8 +162,6 @@ github.com/bombsimon/logrusr/v3 v3.1.0 h1:zORbLM943D+hDMGgyjMhSAz/iDz86ZV72qaak/
github.com/bombsimon/logrusr/v3 v3.1.0/go.mod h1:PksPPgSFEL2I52pla2glgCyyd2OqOHAnFF5E+g8Ixco=
github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=
github.com/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=
github.com/bytecodealliance/wasmtime-go/v44 v44.0.0 h1:WRZXnLPIer/TWs5aYPaMlmVcOlzmR6Ur6wjLRIQOhTQ=
github.com/bytecodealliance/wasmtime-go/v44 v44.0.0/go.mod h1:GP93piU+39CoFVCQ5xfHrPOUtL0APlMnkbblJ2d3YY0=
github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4=
github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
@@ -220,8 +218,8 @@ github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1/go.mod h1:ZXNYxsqcloTdSy/rNShjY
github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE=
github.com/desertbit/timer v1.0.1 h1:yRpYNn5Vaaj6QXecdLMPMJsW81JLiI1eokUft5nBmeo=
github.com/desertbit/timer v1.0.1/go.mod h1:htRrYeY5V/t4iu1xCJ5XsQvp4xve8QulXXctAzxqcwE=
github.com/dgraph-io/badger/v4 v4.9.2 h1:Wb5qw8gElqwV1a8msHTeQKova9b1V10heFKMIiPd80E=
github.com/dgraph-io/badger/v4 v4.9.2/go.mod h1:nJjaJTUOSsQEBhsq209FmwCvMJzEA3e74RjZw6V2pQI=
github.com/dgraph-io/badger/v4 v4.9.4 h1:bcw+waCpzRZ2nmcSPbnPvDVhiEsn98TKmvnAhK7r7LM=
github.com/dgraph-io/badger/v4 v4.9.4/go.mod h1:nJjaJTUOSsQEBhsq209FmwCvMJzEA3e74RjZw6V2pQI=
github.com/dgraph-io/ristretto v0.2.0 h1:XAfl+7cmoUDWW/2Lx8TGZQjjxIQ2Ley9DSf52dru4WE=
github.com/dgraph-io/ristretto v0.2.0/go.mod h1:8uBHCU/PBV4Ag0CJrP47b9Ofby5dqWNh4FicAdoqFNU=
github.com/dgraph-io/ristretto/v2 v2.2.0 h1:bkY3XzJcXoMuELV8F+vS8kzNgicwQFAaGINAEJdWGOM=
@@ -258,8 +256,8 @@ github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYF
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw=
github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g=
github.com/foxcpp/go-mockdns v1.2.0 h1:omK3OrHRD1IWJz1FuFBCFquhXslXoF17OvBS6JPzZF0=
@@ -268,8 +266,8 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
github.com/gdexlab/go-render v1.0.1 h1:rxqB3vo5s4n1kF0ySmoNeSPRYkEsyHgln4jFIQY7v0U=
github.com/gdexlab/go-render v1.0.1/go.mod h1:wRi5nW2qfjiGj4mPukH4UV0IknS1cHD4VgFTmJX5JzM=
github.com/ggwhite/go-masker v1.1.0 h1:kN/KIvktu2U+hd3KWrSlLj7xBGD1iBfc9/xdbVgFbRc=
@@ -327,8 +325,8 @@ github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG
github.com/go-logfmt/logfmt v0.5.1 h1:otpy5pqBCBZ1ng9RQ0dPu4PN7ba75Y/aA+UpowDyNVA=
github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-micro/plugins/v4/client/grpc v1.2.1 h1:7xAwZRCO6mdUtBHsYIQs1/eCTdhCrnjF70GB+AVd6L0=
@@ -502,8 +500,8 @@ github.com/gorilla/schema v1.4.1 h1:jUg5hUjCSDZpNGLuXQOgIWGdlgrIdYvgQ0wZtdK1M3E=
github.com/gorilla/schema v1.4.1/go.mod h1:Dg5SSm5PV60mhF2NFaTV1xuYYj8tV8NOPRo4FggUMnM=
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI=
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0/go.mod h1:g5qyo/la0ALbONm6Vbp88Yd8NsDy6rZz+RcrMPxvld8=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY=
github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k=
github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M=
github.com/hashicorp/go-plugin v1.8.0 h1:ie8S6RRY8RvB2usYZv+AAZ/wBvx2AU5p5QeP5j/FORs=
@@ -576,8 +574,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.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
@@ -652,8 +650,8 @@ github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLG
github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mattn/go-sqlite3 v1.14.47 h1:jOBI62gS7nKeZv+as1oGEy0+1qISgXwH/QBlR6KbfIo=
github.com/mattn/go-sqlite3 v1.14.47/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
github.com/mattn/go-sqlite3 v1.14.49 h1:B8jBHC3xhxZgxztrgruTuLucebnULQnx4W7cF7SAE9w=
github.com/mattn/go-sqlite3 v1.14.49/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/maxymania/go-system v0.0.0-20170110133659-647cc364bf0b h1:Q53idHrTuQDDHyXaxZ6pUl0I9uyD6Z6uKFK3ocX6LzI=
github.com/maxymania/go-system v0.0.0-20170110133659-647cc364bf0b/go.mod h1:KirJrATYGbTyUwVR26xIkaipRqRcMRXBf8N5dacvGus=
@@ -699,8 +697,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.14.3 h1:+xjydPt7rkit67G+04TN0mcO2n+8nveZE7tK/PPV53A=
github.com/nats-io/nats-server/v2 v2.14.3/go.mod h1:5IlCtBzfwyzQzPMjmoJ9W2/LKmnJRtNyuOs/OT+NHDY=
github.com/nats-io/nats-server/v2 v2.14.4 h1:efgjZ8cdExAKRuqSg8UPJFprb+l7NlBtSDPhDlw3rO4=
github.com/nats-io/nats-server/v2 v2.14.4/go.mod h1:BltdpOYestjbtQSnVO2zGHdg5SGBZjt+GYTgB9LZq/I=
github.com/nats-io/nats.go v1.52.0 h1:n3avV4VBsCgsdwh71TppsTwtv+QdPs7ntSKM8qJLGsc=
github.com/nats-io/nats.go v1.52.0/go.mod h1:26HypzazeOkyO3/mqd1zZd53STJN0EjCYF9Uy2ZOBno=
github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg=
@@ -730,8 +728,8 @@ github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7J
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.42.1 h1:iN1rCUX+44NZ1Dc97MPoeFYbFR0vh8zxoxMFwKdyZ6I=
github.com/onsi/gomega v1.42.1/go.mod h1:REff/hsDsodHoKlWsP2mAPhu1+5/6hVYNf9rIEBpeSg=
github.com/open-policy-agent/opa v1.18.2 h1:VBiLJpioTuk7XTW1JoQi4ILo+FVxD2/8uD8iP9/OcxY=
github.com/open-policy-agent/opa v1.18.2/go.mod h1:9GY+hER4ZEXtxPlMjftVbqJJY9xLtCD3Q0oufRCfAKo=
github.com/open-policy-agent/opa v1.19.0 h1:+j2OCsjMezZEML2T1lI9giJdGJS/PL1XFKgkHPGIhpo=
github.com/open-policy-agent/opa v1.19.0/go.mod h1:pb6Y6klyf7X7X8uXNDflruA9dQC2gMqWROXI5w/kvv0=
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
@@ -780,8 +778,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.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
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_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=
@@ -796,8 +794,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.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=
github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=
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/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=
@@ -805,8 +803,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.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc=
github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo=
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/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=
@@ -815,8 +813,8 @@ github.com/r3labs/sse/v2 v2.10.0/go.mod h1:Igau6Whc+F17QUgML1fYe1VPZzTV6EMCnYktE
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 h1:bsUq1dX0N8AOIL7EB/X911+m4EHsnWEHeJ0c+3TTBrg=
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.15.0 h1:D0RCU5rMAp+SpgkiNdrjfJ+LX4J1M32V2NeCY7EJ6hc=
github.com/rogpeppe/go-internal v1.15.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs=
github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g=
github.com/rogpeppe/go-internal v1.16.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs=
github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=
github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
@@ -839,8 +837,8 @@ github.com/sercand/kuberesolver/v5 v5.1.1 h1:CYH+d67G0sGBj7q5wLK61yzqJJ8gLLC8aep
github.com/sercand/kuberesolver/v5 v5.1.1/go.mod h1:Fs1KbKhVRnB2aDWN12NjKCB+RgYMWZJ294T3BtmVCpQ=
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/sethvargo/go-password v0.3.1 h1:WqrLTjo7X6AcVYfC6R7GtSyuUQR9hGyAj/f1PYQZCJU=
github.com/sethvargo/go-password v0.3.1/go.mod h1:rXofC1zT54N7R8K/h1WDUdkf9BOx5OptoxrMBcrXzvs=
github.com/sethvargo/go-password v0.4.0 h1:eSidVKQw5C7CmTDAtH3RipBTSjdU1ZRxQaynD2GWLVU=
github.com/sethvargo/go-password v0.4.0/go.mod h1:PO3nYHwUpcHPR0F9woy7a4abZPvzRuqJr0GaeIYTm3k=
github.com/shamaton/msgpack/v2 v2.4.1 h1:JtJ141QoQ3NqgPDsjq2v9VXlaON8SiQOwEaoNLEK/MQ=
github.com/shamaton/msgpack/v2 v2.4.1/go.mod h1:6khjYnkx73f7VQU7wjcFS9DFjs+59naVWJv1TB7qdOI=
github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI=
@@ -887,6 +885,8 @@ github.com/tchap/go-patricia/v2 v2.3.3 h1:xfNEsODumaEcCcY3gI0hYPZ/PcpVv5ju6RMAhg
github.com/tchap/go-patricia/v2 v2.3.3/go.mod h1:VZRHKAb53DLaG+nA9EaYYiaEx6YztwDlLElMsnSHD4k=
github.com/test-go/testify v1.1.4 h1:Tf9lntrKUMHiXQ07qBScBTSA0dhYQlu83hswqelv1iE=
github.com/test-go/testify v1.1.4/go.mod h1:rH7cfJo/47vWGdi4GPj16x3/t1xGOj2YxzmNQzk2ghU=
github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU=
github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0=
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=
@@ -915,8 +915,8 @@ github.com/urfave/cli/v2 v2.27.7 h1:bH59vdhbjLv3LAvIu6gd0usJHgoTTPhCFib8qqOwXYU=
github.com/urfave/cli/v2 v2.27.7/go.mod h1:CyNAG/xg+iAOg0N4MPGZqVmv2rCoP267496AOXUZjA4=
github.com/valyala/fastjson v1.6.10 h1:/yjJg8jaVQdYR3arGxPE2X5z89xrlhS0eGXdv+ADTh4=
github.com/valyala/fastjson v1.6.10/go.mod h1:e6FubmQouUNP73jtMLmcbxS6ydWIpOfhz34TSfO3JaE=
github.com/vektah/gqlparser/v2 v2.5.34 h1:MEea5P0qhdcqfBL45ghKE+qr9laidVHTMHjav5h7ckk=
github.com/vektah/gqlparser/v2 v2.5.34/go.mod h1:mFdHLGCio7OGX1fby9ZjTW6FN+qxgmbnBcRIeeScE5s=
github.com/vektah/gqlparser/v2 v2.5.36 h1:CN9mKVHgMkc+XftdOWIhb4HEL8wKSYkFAqhf8booa7s=
github.com/vektah/gqlparser/v2 v2.5.36/go.mod h1:cAJ9qwVgPaUkWv6Gn8vn0mqOE0Ui5Pn56wNy5396XWo=
github.com/wk8/go-ordered-map v1.0.0 h1:BV7z+2PaK8LTSd/mWgY12HyMAo5CEgkHqbkVq2thqr8=
github.com/wk8/go-ordered-map v1.0.0/go.mod h1:9ZIbRunKbuvfPKyBP1SIKLcXNlv74YCOZ3t3VTS6gRk=
github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM=
@@ -966,30 +966,30 @@ go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
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.69.0 h1:2yEATaop1/a1I4psnSLgWVPLWwCzkqWakgJy7xTDVy0=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.69.0/go.mod h1:D7J12YRapIekYyPWgGPlA/23pRmpSEZC5xJC/TTLI9U=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
go.opentelemetry.io/contrib/zpages v0.69.0 h1:YQC1PumJq6lUGQNrLW14ID9a0dXSBcbC/aC6VRSIARU=
go.opentelemetry.io/contrib/zpages v0.69.0/go.mod h1:FGvUcMGN5atRzUIgUsqOi+MiMvlQsfbuYATBHPP4cGs=
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0 h1:oECp5f+hN7nkwjU/8BxQ/q23bGPb8FIrD839owX222E=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0/go.mod h1:DqEFwLumhzMBDQv9PcWbyoDxHI/4lAk6CM4nJBH39sc=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 h1:LMuyCAyfalSjDyjdC65nK6N0zoTT63+E/u95X0JovZI=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0/go.mod h1:085m8qbm4hgc8rZWGDEa4vmyyo2c3nPxUslYUKUIU04=
go.opentelemetry.io/contrib/zpages v0.70.0 h1:uBcclHekIrCRLO4KZfXiebDcWB52QQXaHGgvhUJ1K5I=
go.opentelemetry.io/contrib/zpages v0.70.0/go.mod h1:Nz9A1+68HVoJrk+cg92zJbcbHFAa+Jbl1uINwAlcK94=
go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU=
go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ=
go.opentelemetry.io/otel/exporters/jaeger v1.17.0 h1:D7UpUy2Xc2wsi1Ras6V40q806WM07rqoCWzXu7Sqy+4=
go.opentelemetry.io/otel/exporters/jaeger v1.17.0/go.mod h1:nPCqOnEH9rNLKqH/+rrUjiMzHJdV1BlpKcTwRTyKkKI=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 h1:4YsVu3B8+3qtWYYrsUYgn0OG78pN0rnNPRGX4SbokQI=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0/go.mod h1:+wnlSn0mD1ADVMe3v9Z/WIaiz6q6gL2J/ejaAmdmv80=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0 h1:qazEJlUOQzhCpzQpFETGby7EdqjI1wsd0W+6Gg1SCTU=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0/go.mod h1:fOD2Yefuxixkx3ahVNf0O/PERb6r4OlbxfATVnYvzCo=
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 h1:QRefszxJmfPdjXUUm3j6iDzY03mTPXMjqErFqQ67vUg=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0/go.mod h1:Tiz03lTBVBrm7eWZBOidzEaYaJa8tjwGUGv6d8mlTyk=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 h1:fG5MCxGz8+2VtrN/WgqSpJFctVz24gpxj8CxkKmc8Ww=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0/go.mod h1:BmAYTn+3ysbRe+IU2msxmf5Rx3g6DHvex+tWI3LdhYI=
go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M=
go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s=
go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw=
go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA=
go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o=
go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA=
go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag=
go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc=
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
@@ -998,12 +998,13 @@ go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9i
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
@@ -1326,10 +1327,10 @@ google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6D
google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0=
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I=
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8=
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d h1:FarXi840EJWSHYTN3ERkADbPWjl307+FGrA22KAVjjc=
google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d/go.mod h1:K/+WGbmBY7aNW1HDw1fJnKYo10i0DkAX6pows00dLig=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d h1:IL4hdHzcUv2l/gcg98/Rj3FbtE6axwqslOW8SW0C+S0=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
@@ -1343,8 +1344,8 @@ google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3Iji
google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc=
google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE=
google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
google.golang.org/grpc v1.83.0 h1:JeNZEKJFbQxArAMl+hiytHauacDNqJUllNfmIMmpqnQ=
google.golang.org/grpc v1.83.0/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ=
google.golang.org/grpc/examples v0.0.0-20211102180624-670c133e568e h1:m7aQHHqd0q89mRwhwS9Bx2rjyl/hsFAeta+uGrHsQaU=
google.golang.org/grpc/examples v0.0.0-20211102180624-670c133e568e/go.mod h1:gID3PKrg7pWKntu9Ss6zTLJ0ttC0X9IHgREOCZwbCVU=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
+1 -1
View File
@@ -6,7 +6,7 @@
//
// These functions are no-ops with minimal performance overhead when called outside of the Antithesis environment. However, if the environment variable ANTITHESIS_SDK_LOCAL_OUTPUT is set, these functions will log to the file pointed to by that variable using a structured JSON format defined [here]. This allows you to make use of the Antithesis assertions package in your regular testing, or even in production. In particular, very few assertions frameworks offer a convenient way to define [Sometimes assertions], but they can be quite useful even outside Antithesis.
//
// Each function in this package takes a parameter called message, which is a human readable identifier used to aggregate assertions. Antithesis generates one test property per unique message and this test property will be named "<message>" in the [triage report].
// Each function in this package takes a parameter called message, which is a human readable identifier used to aggregate assertions. Antithesis generates one test property per unique message and this test property will be named "<message>" in the [triage report]. Message must be provided as a string literal.
//
// This test property either passes or fails, which depends upon the evaluation of every assertion that shares its message. Different assertions in different parts of the code should have different message, but the same assertion should always have the same message even if it is moved to a different file.
//
+1 -1
View File
@@ -38,7 +38,7 @@ type libHandler interface {
}
const (
errorLogLinePrefix = "[* antithesis-sdk-go *]"
errorLogLinePrefix = "[* antithesis-sdk-go *]"
)
var handler libHandler
+1 -1
View File
@@ -3,7 +3,7 @@ package internal
// --------------------------------------------------------------------------------
// Versions
// --------------------------------------------------------------------------------
const SDK_Version = "0.7.0"
const SDK_Version = "0.7.2"
const Protocol_Version = "1.1.0"
// --------------------------------------------------------------------------------
@@ -4,8 +4,8 @@ package internal
import (
"fmt"
"unsafe"
"os"
"unsafe"
)
// --------------------------------------------------------------------------------
+36 -1
View File
@@ -69,6 +69,16 @@ func (m *Metrics) CaptureMetrics(w http.ResponseWriter, fn func(http.ResponseWri
}
},
WriteString: func(next WriteStringFunc) WriteStringFunc {
return func(s string) (int, error) {
n, err := next(s)
m.Written += int64(n)
headerWritten = true
return n, err
}
},
ReadFrom: func(next ReadFromFunc) ReadFromFunc {
return func(src io.Reader) (int64, error) {
n, err := next(src)
@@ -81,6 +91,31 @@ func (m *Metrics) CaptureMetrics(w http.ResponseWriter, fn func(http.ResponseWri
}
)
// defer to ensure duration is updated even if the handler panics
defer func() {
m.Duration += time.Since(start)
}()
fn(Wrap(w, hooks))
m.Duration += time.Since(start)
}
// deadliner defines two methods introduced in go 1.20. The standard library
// seems not to provide an interface we can import, hence its definition here.
type deadliner interface {
SetReadDeadline(deadline time.Time) error
SetWriteDeadline(deadline time.Time) error
}
// fullDuplexEnabler defines a method introduced in go 1.21. The standard
// library seems not to provide an interface we can import, hence its definition
// here.
type fullDuplexEnabler interface {
EnableFullDuplex() error
}
// httpFlushError defines a method introduced in go 1.20. The standard
// library seems not to provide an interface we can import, hence its definition
// here.
// See https://github.com/golang/go/blob/go1.20/src/net/http/responsecontroller.go#L50
type httpFlushError interface {
FlushError() error
}
File diff suppressed because it is too large. Load diff
-436
View File
@@ -1,436 +0,0 @@
// +build go1.8
// Code generated by "httpsnoop/codegen"; DO NOT EDIT.
package httpsnoop
import (
"bufio"
"io"
"net"
"net/http"
)
// HeaderFunc is part of the http.ResponseWriter interface.
type HeaderFunc func() http.Header
// WriteHeaderFunc is part of the http.ResponseWriter interface.
type WriteHeaderFunc func(code int)
// WriteFunc is part of the http.ResponseWriter interface.
type WriteFunc func(b []byte) (int, error)
// FlushFunc is part of the http.Flusher interface.
type FlushFunc func()
// CloseNotifyFunc is part of the http.CloseNotifier interface.
type CloseNotifyFunc func() <-chan bool
// HijackFunc is part of the http.Hijacker interface.
type HijackFunc func() (net.Conn, *bufio.ReadWriter, error)
// ReadFromFunc is part of the io.ReaderFrom interface.
type ReadFromFunc func(src io.Reader) (int64, error)
// PushFunc is part of the http.Pusher interface.
type PushFunc func(target string, opts *http.PushOptions) error
// Hooks defines a set of method interceptors for methods included in
// http.ResponseWriter as well as some others. You can think of them as
// middleware for the function calls they target. See Wrap for more details.
type Hooks struct {
Header func(HeaderFunc) HeaderFunc
WriteHeader func(WriteHeaderFunc) WriteHeaderFunc
Write func(WriteFunc) WriteFunc
Flush func(FlushFunc) FlushFunc
CloseNotify func(CloseNotifyFunc) CloseNotifyFunc
Hijack func(HijackFunc) HijackFunc
ReadFrom func(ReadFromFunc) ReadFromFunc
Push func(PushFunc) PushFunc
}
// Wrap returns a wrapped version of w that provides the exact same interface
// as w. Specifically if w implements any combination of:
//
// - http.Flusher
// - http.CloseNotifier
// - http.Hijacker
// - io.ReaderFrom
// - http.Pusher
//
// The wrapped version will implement the exact same combination. If no hooks
// are set, the wrapped version also behaves exactly as w. Hooks targeting
// methods not supported by w are ignored. Any other hooks will intercept the
// method they target and may modify the call's arguments and/or return values.
// The CaptureMetrics implementation serves as a working example for how the
// hooks can be used.
func Wrap(w http.ResponseWriter, hooks Hooks) http.ResponseWriter {
rw := &rw{w: w, h: hooks}
_, i0 := w.(http.Flusher)
_, i1 := w.(http.CloseNotifier)
_, i2 := w.(http.Hijacker)
_, i3 := w.(io.ReaderFrom)
_, i4 := w.(http.Pusher)
switch {
// combination 1/32
case !i0 && !i1 && !i2 && !i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
}{rw, rw}
// combination 2/32
case !i0 && !i1 && !i2 && !i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
http.Pusher
}{rw, rw, rw}
// combination 3/32
case !i0 && !i1 && !i2 && i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
io.ReaderFrom
}{rw, rw, rw}
// combination 4/32
case !i0 && !i1 && !i2 && i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
io.ReaderFrom
http.Pusher
}{rw, rw, rw, rw}
// combination 5/32
case !i0 && !i1 && i2 && !i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
http.Hijacker
}{rw, rw, rw}
// combination 6/32
case !i0 && !i1 && i2 && !i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
http.Hijacker
http.Pusher
}{rw, rw, rw, rw}
// combination 7/32
case !i0 && !i1 && i2 && i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
http.Hijacker
io.ReaderFrom
}{rw, rw, rw, rw}
// combination 8/32
case !i0 && !i1 && i2 && i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
http.Hijacker
io.ReaderFrom
http.Pusher
}{rw, rw, rw, rw, rw}
// combination 9/32
case !i0 && i1 && !i2 && !i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
http.CloseNotifier
}{rw, rw, rw}
// combination 10/32
case !i0 && i1 && !i2 && !i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
http.CloseNotifier
http.Pusher
}{rw, rw, rw, rw}
// combination 11/32
case !i0 && i1 && !i2 && i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
http.CloseNotifier
io.ReaderFrom
}{rw, rw, rw, rw}
// combination 12/32
case !i0 && i1 && !i2 && i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
http.CloseNotifier
io.ReaderFrom
http.Pusher
}{rw, rw, rw, rw, rw}
// combination 13/32
case !i0 && i1 && i2 && !i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
http.CloseNotifier
http.Hijacker
}{rw, rw, rw, rw}
// combination 14/32
case !i0 && i1 && i2 && !i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
http.CloseNotifier
http.Hijacker
http.Pusher
}{rw, rw, rw, rw, rw}
// combination 15/32
case !i0 && i1 && i2 && i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
http.CloseNotifier
http.Hijacker
io.ReaderFrom
}{rw, rw, rw, rw, rw}
// combination 16/32
case !i0 && i1 && i2 && i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
http.CloseNotifier
http.Hijacker
io.ReaderFrom
http.Pusher
}{rw, rw, rw, rw, rw, rw}
// combination 17/32
case i0 && !i1 && !i2 && !i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
}{rw, rw, rw}
// combination 18/32
case i0 && !i1 && !i2 && !i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.Pusher
}{rw, rw, rw, rw}
// combination 19/32
case i0 && !i1 && !i2 && i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
io.ReaderFrom
}{rw, rw, rw, rw}
// combination 20/32
case i0 && !i1 && !i2 && i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
io.ReaderFrom
http.Pusher
}{rw, rw, rw, rw, rw}
// combination 21/32
case i0 && !i1 && i2 && !i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.Hijacker
}{rw, rw, rw, rw}
// combination 22/32
case i0 && !i1 && i2 && !i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.Hijacker
http.Pusher
}{rw, rw, rw, rw, rw}
// combination 23/32
case i0 && !i1 && i2 && i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.Hijacker
io.ReaderFrom
}{rw, rw, rw, rw, rw}
// combination 24/32
case i0 && !i1 && i2 && i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.Hijacker
io.ReaderFrom
http.Pusher
}{rw, rw, rw, rw, rw, rw}
// combination 25/32
case i0 && i1 && !i2 && !i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.CloseNotifier
}{rw, rw, rw, rw}
// combination 26/32
case i0 && i1 && !i2 && !i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.CloseNotifier
http.Pusher
}{rw, rw, rw, rw, rw}
// combination 27/32
case i0 && i1 && !i2 && i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.CloseNotifier
io.ReaderFrom
}{rw, rw, rw, rw, rw}
// combination 28/32
case i0 && i1 && !i2 && i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.CloseNotifier
io.ReaderFrom
http.Pusher
}{rw, rw, rw, rw, rw, rw}
// combination 29/32
case i0 && i1 && i2 && !i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.CloseNotifier
http.Hijacker
}{rw, rw, rw, rw, rw}
// combination 30/32
case i0 && i1 && i2 && !i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.CloseNotifier
http.Hijacker
http.Pusher
}{rw, rw, rw, rw, rw, rw}
// combination 31/32
case i0 && i1 && i2 && i3 && !i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.CloseNotifier
http.Hijacker
io.ReaderFrom
}{rw, rw, rw, rw, rw, rw}
// combination 32/32
case i0 && i1 && i2 && i3 && i4:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.CloseNotifier
http.Hijacker
io.ReaderFrom
http.Pusher
}{rw, rw, rw, rw, rw, rw, rw}
}
panic("unreachable")
}
type rw struct {
w http.ResponseWriter
h Hooks
}
func (w *rw) Unwrap() http.ResponseWriter {
return w.w
}
func (w *rw) Header() http.Header {
f := w.w.(http.ResponseWriter).Header
if w.h.Header != nil {
f = w.h.Header(f)
}
return f()
}
func (w *rw) WriteHeader(code int) {
f := w.w.(http.ResponseWriter).WriteHeader
if w.h.WriteHeader != nil {
f = w.h.WriteHeader(f)
}
f(code)
}
func (w *rw) Write(b []byte) (int, error) {
f := w.w.(http.ResponseWriter).Write
if w.h.Write != nil {
f = w.h.Write(f)
}
return f(b)
}
func (w *rw) Flush() {
f := w.w.(http.Flusher).Flush
if w.h.Flush != nil {
f = w.h.Flush(f)
}
f()
}
func (w *rw) CloseNotify() <-chan bool {
f := w.w.(http.CloseNotifier).CloseNotify
if w.h.CloseNotify != nil {
f = w.h.CloseNotify(f)
}
return f()
}
func (w *rw) Hijack() (net.Conn, *bufio.ReadWriter, error) {
f := w.w.(http.Hijacker).Hijack
if w.h.Hijack != nil {
f = w.h.Hijack(f)
}
return f()
}
func (w *rw) ReadFrom(src io.Reader) (int64, error) {
f := w.w.(io.ReaderFrom).ReadFrom
if w.h.ReadFrom != nil {
f = w.h.ReadFrom(f)
}
return f(src)
}
func (w *rw) Push(target string, opts *http.PushOptions) error {
f := w.w.(http.Pusher).Push
if w.h.Push != nil {
f = w.h.Push(f)
}
return f(target, opts)
}
type Unwrapper interface {
Unwrap() http.ResponseWriter
}
// Unwrap returns the underlying http.ResponseWriter from within zero or more
// layers of httpsnoop wrappers.
func Unwrap(w http.ResponseWriter) http.ResponseWriter {
if rw, ok := w.(Unwrapper); ok {
// recurse until rw.Unwrap() returns a non-Unwrapper
return Unwrap(rw.Unwrap())
} else {
return w
}
}
-278
View File
@@ -1,278 +0,0 @@
// +build !go1.8
// Code generated by "httpsnoop/codegen"; DO NOT EDIT.
package httpsnoop
import (
"bufio"
"io"
"net"
"net/http"
)
// HeaderFunc is part of the http.ResponseWriter interface.
type HeaderFunc func() http.Header
// WriteHeaderFunc is part of the http.ResponseWriter interface.
type WriteHeaderFunc func(code int)
// WriteFunc is part of the http.ResponseWriter interface.
type WriteFunc func(b []byte) (int, error)
// FlushFunc is part of the http.Flusher interface.
type FlushFunc func()
// CloseNotifyFunc is part of the http.CloseNotifier interface.
type CloseNotifyFunc func() <-chan bool
// HijackFunc is part of the http.Hijacker interface.
type HijackFunc func() (net.Conn, *bufio.ReadWriter, error)
// ReadFromFunc is part of the io.ReaderFrom interface.
type ReadFromFunc func(src io.Reader) (int64, error)
// Hooks defines a set of method interceptors for methods included in
// http.ResponseWriter as well as some others. You can think of them as
// middleware for the function calls they target. See Wrap for more details.
type Hooks struct {
Header func(HeaderFunc) HeaderFunc
WriteHeader func(WriteHeaderFunc) WriteHeaderFunc
Write func(WriteFunc) WriteFunc
Flush func(FlushFunc) FlushFunc
CloseNotify func(CloseNotifyFunc) CloseNotifyFunc
Hijack func(HijackFunc) HijackFunc
ReadFrom func(ReadFromFunc) ReadFromFunc
}
// Wrap returns a wrapped version of w that provides the exact same interface
// as w. Specifically if w implements any combination of:
//
// - http.Flusher
// - http.CloseNotifier
// - http.Hijacker
// - io.ReaderFrom
//
// The wrapped version will implement the exact same combination. If no hooks
// are set, the wrapped version also behaves exactly as w. Hooks targeting
// methods not supported by w are ignored. Any other hooks will intercept the
// method they target and may modify the call's arguments and/or return values.
// The CaptureMetrics implementation serves as a working example for how the
// hooks can be used.
func Wrap(w http.ResponseWriter, hooks Hooks) http.ResponseWriter {
rw := &rw{w: w, h: hooks}
_, i0 := w.(http.Flusher)
_, i1 := w.(http.CloseNotifier)
_, i2 := w.(http.Hijacker)
_, i3 := w.(io.ReaderFrom)
switch {
// combination 1/16
case !i0 && !i1 && !i2 && !i3:
return struct {
Unwrapper
http.ResponseWriter
}{rw, rw}
// combination 2/16
case !i0 && !i1 && !i2 && i3:
return struct {
Unwrapper
http.ResponseWriter
io.ReaderFrom
}{rw, rw, rw}
// combination 3/16
case !i0 && !i1 && i2 && !i3:
return struct {
Unwrapper
http.ResponseWriter
http.Hijacker
}{rw, rw, rw}
// combination 4/16
case !i0 && !i1 && i2 && i3:
return struct {
Unwrapper
http.ResponseWriter
http.Hijacker
io.ReaderFrom
}{rw, rw, rw, rw}
// combination 5/16
case !i0 && i1 && !i2 && !i3:
return struct {
Unwrapper
http.ResponseWriter
http.CloseNotifier
}{rw, rw, rw}
// combination 6/16
case !i0 && i1 && !i2 && i3:
return struct {
Unwrapper
http.ResponseWriter
http.CloseNotifier
io.ReaderFrom
}{rw, rw, rw, rw}
// combination 7/16
case !i0 && i1 && i2 && !i3:
return struct {
Unwrapper
http.ResponseWriter
http.CloseNotifier
http.Hijacker
}{rw, rw, rw, rw}
// combination 8/16
case !i0 && i1 && i2 && i3:
return struct {
Unwrapper
http.ResponseWriter
http.CloseNotifier
http.Hijacker
io.ReaderFrom
}{rw, rw, rw, rw, rw}
// combination 9/16
case i0 && !i1 && !i2 && !i3:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
}{rw, rw, rw}
// combination 10/16
case i0 && !i1 && !i2 && i3:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
io.ReaderFrom
}{rw, rw, rw, rw}
// combination 11/16
case i0 && !i1 && i2 && !i3:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.Hijacker
}{rw, rw, rw, rw}
// combination 12/16
case i0 && !i1 && i2 && i3:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.Hijacker
io.ReaderFrom
}{rw, rw, rw, rw, rw}
// combination 13/16
case i0 && i1 && !i2 && !i3:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.CloseNotifier
}{rw, rw, rw, rw}
// combination 14/16
case i0 && i1 && !i2 && i3:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.CloseNotifier
io.ReaderFrom
}{rw, rw, rw, rw, rw}
// combination 15/16
case i0 && i1 && i2 && !i3:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.CloseNotifier
http.Hijacker
}{rw, rw, rw, rw, rw}
// combination 16/16
case i0 && i1 && i2 && i3:
return struct {
Unwrapper
http.ResponseWriter
http.Flusher
http.CloseNotifier
http.Hijacker
io.ReaderFrom
}{rw, rw, rw, rw, rw, rw}
}
panic("unreachable")
}
type rw struct {
w http.ResponseWriter
h Hooks
}
func (w *rw) Unwrap() http.ResponseWriter {
return w.w
}
func (w *rw) Header() http.Header {
f := w.w.(http.ResponseWriter).Header
if w.h.Header != nil {
f = w.h.Header(f)
}
return f()
}
func (w *rw) WriteHeader(code int) {
f := w.w.(http.ResponseWriter).WriteHeader
if w.h.WriteHeader != nil {
f = w.h.WriteHeader(f)
}
f(code)
}
func (w *rw) Write(b []byte) (int, error) {
f := w.w.(http.ResponseWriter).Write
if w.h.Write != nil {
f = w.h.Write(f)
}
return f(b)
}
func (w *rw) Flush() {
f := w.w.(http.Flusher).Flush
if w.h.Flush != nil {
f = w.h.Flush(f)
}
f()
}
func (w *rw) CloseNotify() <-chan bool {
f := w.w.(http.CloseNotifier).CloseNotify
if w.h.CloseNotify != nil {
f = w.h.CloseNotify(f)
}
return f()
}
func (w *rw) Hijack() (net.Conn, *bufio.ReadWriter, error) {
f := w.w.(http.Hijacker).Hijack
if w.h.Hijack != nil {
f = w.h.Hijack(f)
}
return f()
}
func (w *rw) ReadFrom(src io.Reader) (int64, error) {
f := w.w.(io.ReaderFrom).ReadFrom
if w.h.ReadFrom != nil {
f = w.h.ReadFrom(f)
}
return f(src)
}
type Unwrapper interface {
Unwrap() http.ResponseWriter
}
// Unwrap returns the underlying http.ResponseWriter from within zero or more
// layers of httpsnoop wrappers.
func Unwrap(w http.ResponseWriter) http.ResponseWriter {
if rw, ok := w.(Unwrapper); ok {
// recurse until rw.Unwrap() returns a non-Unwrapper
return Unwrap(rw.Unwrap())
} else {
return w
}
}
+7
View File
@@ -7,6 +7,12 @@ linters:
exclusions:
presets:
- std-error-handling
rules:
# Test fixtures construct CDF binary blobs from known small constants, so
# gosec's integer-overflow checks (G115) add no value there.
- path: internal/cdf/cdf_test\.go
linters:
- gosec
enable:
- gosec # Detects security problems.
# Keep all extras disabled for now to focus on the integer overflow problem.
@@ -31,6 +37,7 @@ linters:
- unused
- usestdlibvars # Detects the possibility to use variables/constants from the Go standard library.
- usetesting # Reports uses of functions with replacement inside the testing package.
- asciicheck # https://daniel.haxx.se/blog/2025/05/16/detecting-malicious-unicode/
settings:
govet:
disable:
+9 -2
View File
@@ -13,8 +13,8 @@
<a href="https://pkg.go.dev/github.com/gabriel-vasile/mimetype">
<img alt="Go Reference" src="https://pkg.go.dev/badge/github.com/gabriel-vasile/mimetype.svg">
</a>
<a href="https://goreportcard.com/report/github.com/gabriel-vasile/mimetype">
<img alt="Go report card" src="https://goreportcard.com/badge/github.com/gabriel-vasile/mimetype">
<a href="https://codecov.io/gh/gabriel-vasile/mimetype">
<img alt="Code coverage" src="https://codecov.io/gh/gabriel-vasile/mimetype/graph/badge.svg">
</a>
<a href="LICENSE">
<img alt="License" src="https://img.shields.io/badge/License-MIT-green.svg">
@@ -103,3 +103,10 @@ shows which file formats are most often misidentified and can help prioritise.
When submitting a PR for detection of a new file format, please make sure to
add a record to the list of testcases in [mimetype_test.go](mimetype_test.go).
For complex files a record can be added in the [testdata](testdata) directory.
Code contributions must respect following rules:
- code must be test covered
- code must be formatted using the `gofmt` tool
- exported names must be documented
**Important**: By submitting a pull request, you agree to allow the project
owner to license your work under the same license as that used by the project.
+1
View File
@@ -0,0 +1 @@
comment: false
+667
View File
@@ -0,0 +1,667 @@
// Package cdf implements parsing of CDF (OLE2) files. It is greatly inspired
// by src/readcdf.c from libmagic. One difference is this implementation is
// permissive of truncated inputs. See readLimit in mimetype.go for the
// reason why truncated inputs need to be handled.
// http://sc.openoffice.org/compdocfileformat.pdf
package cdf
import (
"bytes"
"encoding/binary"
"github.com/gabriel-vasile/mimetype/internal/scan"
)
type CDFType int8
const (
CDFTypeGeneric CDFType = iota
CDFTypeInstaller
CDFTypeDoc
CDFTypePpt
CDFTypeXls
CDFTypeMsg
)
// Detect parses raw as a CDF (OLE2) compound file and returns the document type
// it contains. It returns CDFTypeGeneric for input that is not a CDF file or
// whose type cannot be narrowed down.
func Detect(raw []byte) CDFType {
if len(raw) < 512 {
return CDFTypeGeneric
}
var c cdf
if !parse(raw, &c) {
return CDFTypeGeneric
}
return c.detect()
}
// cdf holds everything we need from a CDF file to do detection.
type cdf struct {
data []byte
secSize int
shortSecSize int
minStdStream uint32
satSecs int32s // list of SAT sector ids; usually a sub-slice of raw input
satEntries int // number of valid SAT entries reachable through satSecs
firstSSAT int32
dirRaw []byte // directory stream bytes (entries are decoded on demand)
sst []byte // short-stream pool (root storage's stream)
sstBuilt bool // whether sst was already loaded (it is loaded lazily)
rootStreamFirst int32 // first sector of the root storage short-stream pool
rootStreamSize uint32 // size of the root storage short-stream pool
rootStorageUUID []byte
}
// parse reads the entire on-disk structure required for type detection. It
// returns true on success and false if the header does not look like a CDF file.
// Truncated or partially malformed bodies are tolerated: sector reads degrade
// to whatever could be collected so detection can still succeed from partial data.
func parse(raw []byte, c *cdf) bool {
if len(raw) < 512 || binary.LittleEndian.Uint64(raw) != cdfMagic {
return false
}
secP2 := binary.LittleEndian.Uint16(raw[30:32])
shortP2 := binary.LittleEndian.Uint16(raw[32:34])
if secP2 > 20 || shortP2 > 20 {
return false
}
c.data = raw
c.secSize = 1 << secP2
c.shortSecSize = 1 << shortP2
c.minStdStream = binary.LittleEndian.Uint32(raw[56:60])
if c.secSize < dirEntrySize {
return false
}
firstDirSec := readSecID(raw[48:52])
c.firstSSAT = readSecID(raw[60:64])
firstMSAT := readSecID(raw[68:72])
nMSAT := binary.LittleEndian.Uint32(raw[72:76])
masterSAT := int32s{b: raw[76 : 76+4*masterSATSize]}
c.buildSAT(masterSAT, firstMSAT, nMSAT)
c.dirRaw = c.readLong(firstDirSec, 0)
c.rootStreamFirst = -1
var d dirEntry
for i, n := 0, c.dirLen(); i < n; i++ {
c.dirAt(i, &d)
if d.typ != dirTypeRootStorage || d.streamFirst < 0 {
continue
}
c.rootStorageUUID = d.storageUUID[:]
// Record where the short-stream pool lives; it is loaded lazily by
// shortStream the first time a short stream is actually read.
c.rootStreamFirst = d.streamFirst
c.rootStreamSize = d.size
break
}
return true
}
func (c *cdf) detect() CDFType {
for _, name := range []string{"\x05SummaryInformation", "\x05DocumentSummaryInformation"} {
if t, ok := c.detectFromSummary(name); ok {
return t
}
}
var d dirEntry
for i, n := 0, c.dirLen(); i < n; i++ {
c.dirAt(i, &d)
if t, ok := lookupSection(d.nameBytes(), d.typ); ok {
return t
}
}
return CDFTypeGeneric
}
// detectFromSummary inspects a (Doc)SummaryInformation stream and tries to
// derive a CDFType from the root-storage CLSID, the property NameOfApplication,
// and finally the names of sibling user streams.
func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) {
if c.rootStorageUUID != nil && bytes.Equal(c.rootStorageUUID, msiCLSID) {
return CDFTypeInstaller, true
}
raw, ok := c.userStream(streamName)
if !ok {
return CDFTypeGeneric, false
}
if app := summaryAppName(raw); len(app) > 0 {
if t, ok := lookupSubstring(app, app2type); ok {
return t, true
}
}
for i, n := 0, c.dirLen(); i < n; i++ {
var d dirEntry
c.dirAt(i, &d)
if d.nameLen == 0 {
continue
}
if t, ok := lookupSubstring(d.nameBytes(), name2type); ok {
return t, true
}
}
return CDFTypeGeneric, true
}
const (
cdfMagic uint64 = 0xE11AB1A1E011CFD0
dirTypeUserStorage = 1
dirTypeUserStream = 2
dirTypeRootStorage = 5
dirEntrySize = 128
masterSATSize = 109 // first 109 SAT secids live in the file header
)
// dirEntry is a single CDF directory record. The UTF-16LE name is pre-decoded
// into an inline ASCII buffer at parse time, avoiding a per-entry heap
// allocation while keeping comparisons trivial. CDF names are at most 32
// UTF-16 code units, so 32 bytes always suffice.
type dirEntry struct {
name [32]byte
nameLen uint8
typ uint8
streamFirst int32
size uint32
storageUUID [16]byte
}
// nameBytes returns the decoded ASCII name without copying.
func (d *dirEntry) nameBytes() []byte { return d.name[:d.nameLen] }
func (c *cdf) ssatAt(i int32) int32 {
for sid := c.firstSSAT; sid >= 0; {
if int(sid) >= c.satLen() {
break // SAT is truncated; stop collecting
}
buf, ok := c.sector(sid)
if !ok {
break
}
lbuf := int32(len(buf) / 4) //nolint:gosec // anything divided by 4 fits int32
if i < lbuf {
return int32(binary.LittleEndian.Uint32(buf[4*i:])) //nolint:gosec // intentional two's-complement reinterpretation of a sector id
}
i -= lbuf
sid = c.satAt(sid)
}
return -1
}
// shortStream returns the root storage short-stream pool, loading it on first
// use. Detection often finishes (e.g. via the root CLSID or a long-stream
// summary) without ever reading a short stream, so building this eagerly would
// be wasted work.
func (c *cdf) shortStream() []byte {
if !c.sstBuilt {
c.sstBuilt = true
if c.rootStreamFirst >= 0 {
c.sst = c.readLong(c.rootStreamFirst, c.rootStreamSize)
}
}
return c.sst
}
// int32s works like a slice of LE int32 and is backed by a slice of bytes.
// int32s could very well be type int32s []byte, but that would mean
// len function can be called on it. We don't want that, we always want to use
// the len method.
type int32s struct {
b []byte
}
func (b int32s) at(i int) int32 {
//nolint:gosec // intentional two's-complement reinterpretation of a sector id
return int32(binary.LittleEndian.Uint32(b.b[4*i:]))
}
func (b int32s) len() int {
return len(b.b) / 4
}
// readSecID reinterprets four little-endian bytes as a signed sector id.
// Every 32-bit pattern is a valid id (values >= 0 are sector numbers,
// negatives are CDF sentinels such as -2 end-of-chain), so the conversion is
// an intentional two's-complement reinterpretation rather than an overflow.
func readSecID(b []byte) int32 {
return int32(binary.LittleEndian.Uint32(b)) //nolint:gosec // intentional two's-complement reinterpretation
}
// satLen is the number of sector ids reachable through the SAT.
func (c *cdf) satLen() int { return c.satEntries }
// satAt returns the i-th sector id from the SAT. Callers must ensure
// i < satLen(). The SAT is not materialized; the entry is fetched directly
// from the input by translating i into (SAT sector index, entry offset).
func (c *cdf) satAt(i int32) int32 {
perSec := c.secSize / 4
secIdx := int(i) / perSec
entryIdx := int(i) % perSec
secID := c.satSecs.at(secIdx)
off := c.secSize*(1+int(secID)) + 4*entryIdx
return readSecID(c.data[off:])
}
// sector returns the bytes of long sector secid. If the file is truncated
// inside the requested sector the result is the available bytes (no padding).
// If the sector starts past EOF or secid is negative, then ok is false.
func (c *cdf) sector(secid int32) (_ []byte, ok bool) {
if secid < 0 {
return nil, false
}
off := int64(c.secSize) * (1 + int64(secid))
if off >= int64(len(c.data)) {
return nil, false
}
// The returned sector might be truncated,
// but we still return it as best effort.
end := min(off+int64(c.secSize), int64(len(c.data)))
// If not even one int32 fits, then fail.
if end-off < 4 {
return nil, false
}
return c.data[off:end], true
}
func (c *cdf) sectorIDs(secid int32) (int32s, bool) {
buf, ok := c.sector(secid)
if !ok {
return int32s{}, ok
}
return int32s{b: buf}, true
}
// buildSAT records the list of SAT sector ids from the master-SAT (header)
// plus any extension blocks chained via firstMSAT. The SAT itself is not
// materialized: satAt computes the requested entry directly from c.data via
// satSecs. In the common case (no extension chain) satSecs is a zero-copy
// sub-slice of the input header.
func (c *cdf) buildSAT(masterSAT int32s, firstMSAT int32, nMSAT uint32) {
// Fast path: no extension chain. masterSAT is already a sub-slice of raw
// input; reuse it directly.
if firstMSAT < 0 || nMSAT == 0 {
c.satSecs = masterSAT
c.satEntries = c.computeSATLen()
return
}
// Slow path: gather sector ids from the header plus the extension chain
// into a fresh buffer. Even here we only allocate space for ids (4 bytes
// each), not the full SAT contents.
maxIDs := len(c.data)/c.secSize + 1
buf := make([]byte, 0, 4*masterSATSize)
for i := 0; i < masterSAT.len(); i++ {
if masterSAT.at(i) < 0 {
break
}
buf = append(buf, masterSAT.b[4*i:4*i+4]...)
}
perSec := c.secSize/4 - 1
mid := firstMSAT
chain:
for j := uint32(0); j < nMSAT && mid >= 0; j++ {
msa, ok := c.sectorIDs(mid)
if !ok {
break
}
for k := 0; k < perSec; k++ {
if k >= msa.len() || msa.at(k) < 0 {
break chain
}
buf = append(buf, msa.b[4*k:4*k+4]...)
if len(buf)/4 > maxIDs {
break chain // cyclic MSAT chain; stop allocating
}
}
if perSec >= msa.len() {
break // no next-MSAT pointer available
}
mid = msa.at(perSec)
}
c.satSecs = int32s{b: buf}
c.satEntries = c.computeSATLen()
}
// computeSATLen walks satSecs and counts how many SAT entries are actually
// reachable in c.data, stopping at the first sentinel id or sector that is not
// fully present in the file.
func (c *cdf) computeSATLen() int {
perSec := c.secSize / 4
total := 0
for i := 0; i < c.satSecs.len(); i++ {
sec := c.satSecs.at(i)
if sec < 0 {
break
}
off := int64(c.secSize) * (1 + int64(sec))
if off >= int64(len(c.data)) {
break
}
avail := int64(len(c.data)) - off
if avail >= int64(c.secSize) {
total += perSec
continue
}
total += int(avail / 4)
break
}
return total
}
// readLong reads a long-sector chain starting at sid. If length > 0 the
// result is truncated to that many bytes. On truncation or any other failure
// it returns whatever sectors were readable.
func (c *cdf) readLong(sid int32, length uint32) []byte {
// Fast path: when the chain is a single physically contiguous run of
// sectors (the common case for the directory and summary streams) the data
// is already laid out sequentially in the input, so return a sub-slice of
// it instead of allocating a buffer and copying every sector.
if sid >= 0 {
maxSec := len(c.data)/c.secSize + 1
n, s := 0, sid
contiguous := true
for s >= 0 {
if int(s) >= c.satLen() {
break // SAT truncated; what remains is still contiguous
}
n++
if n > maxSec {
contiguous = false // cyclic chain; let the slow path guard it
break
}
next := c.satAt(s)
if next >= 0 && int64(next) != int64(s)+1 {
contiguous = false
break
}
s = next
}
if contiguous {
off64 := int64(c.secSize) * (1 + int64(sid))
if off64 >= int64(len(c.data)) {
return nil
}
end64 := min(off64+int64(n)*int64(c.secSize), int64(len(c.data)))
out := c.data[off64:end64]
if length > 0 && int64(length) < int64(len(out)) {
out = out[:length]
}
return out
}
}
// Slow path: gather a fragmented chain into a fresh buffer. Real-world
// writers (MSI builders, edited Office documents) routinely produce
// non-contiguous directory and stream chains, so this fallback is required
// for correct detection on those files.
maxBytes := len(c.data)
out := make([]byte, 0, c.secSize)
for sid >= 0 {
if int(sid) >= c.satLen() {
break // SAT truncated; return what we have
}
buf, ok := c.sector(sid)
if !ok {
break
}
out = append(out, buf...)
if len(out) >= maxBytes {
break // chain longer than the file: cyclic SAT, stop
}
sid = c.satAt(sid)
}
if length > 0 && int64(length) < int64(len(out)) {
out = out[:length]
}
return out
}
// readShort reads a short-sector chain at sid by indexing into the short-stream
// pool. On truncation or if the pool is unavailable it returns whatever was
// readable (possibly nil).
func (c *cdf) readShort(sid int32, length uint32) []byte {
sst := c.shortStream()
if sst == nil {
return nil
}
// TODO: anyway to avoid allocating and copying the bytes?
out := make([]byte, 0, c.shortSecSize)
for sid >= 0 {
off64 := int64(sid) * int64(c.shortSecSize)
if off64+int64(c.shortSecSize) > int64(len(sst)) {
break // short-stream pool truncated or sid out of range
}
off := int(off64)
out = append(out, sst[off:off+c.shortSecSize]...)
if len(out) >= len(sst) {
break // chain longer than the pool: cyclic SSAT, stop
}
sid = c.ssatAt(sid)
}
if length > 0 && int64(length) < int64(len(out)) {
out = out[:length]
}
return out
}
// readChain dispatches to the long or short reader depending on stream size.
func (c *cdf) readChain(sid int32, length uint32) []byte {
if length < c.minStdStream && c.rootStreamFirst >= 0 {
return c.readShort(sid, length)
}
return c.readLong(sid, length)
}
// dirLen returns the number of directory entries in dirRaw.
func (c *cdf) dirLen() int { return len(c.dirRaw) / dirEntrySize }
// dirAt decodes the i-th directory entry into *out. Callers must ensure
// i < dirLen(). The UTF-16LE name is decoded into out.name, ASCII-style,
// stopping at the first NUL.
func (c *cdf) dirAt(i int, out *dirEntry) {
raw := c.dirRaw[i*dirEntrySize:]
nameLen := min(int(binary.LittleEndian.Uint16(raw[64:])), 64)
k := uint8(0)
for j := 0; j < nameLen/2; j++ {
// Names are ASCII; keep the low byte of each little-endian UTF-16
// code unit and stop at the first NUL.
lo, hi := raw[2*j], raw[2*j+1]
if lo == 0 && hi == 0 {
break
}
out.name[k] = lo
k++
}
out.nameLen = k
out.typ = raw[66]
out.streamFirst = readSecID(raw[116:120])
out.size = binary.LittleEndian.Uint32(raw[120:])
copy(out.storageUUID[:], raw[80:96])
}
// userStream finds a user stream by name and returns its bytes.
func (c *cdf) userStream(name string) ([]byte, bool) {
var d dirEntry
for i, n := 0, c.dirLen(); i < n; i++ {
c.dirAt(i, &d)
if d.typ == dirTypeUserStream && string(d.nameBytes()) == name {
buf := c.readChain(d.streamFirst, d.size)
if buf == nil {
return nil, false
}
return buf, true
}
}
return nil, false
}
const (
propIDNameOfApplication = 0x12
typeMask = 0x0fff
typeVector = 0x1000
typeStringASCII = 0x1e
typeStringWide = 0x1f
sectionDeclOffset = 0x1c // section declaration in property-set header
)
// summaryAppName parses a (Doc)SummaryInformation stream and returns the
// value of property NameOfApplication (0x12) as printable ASCII, or nil if
// not present or the stream is malformed. This is the only summary property
// the detection logic ever consults.
func summaryAppName(stream []byte) []byte {
if len(stream) < sectionDeclOffset+20 {
return nil
}
sdOff := binary.LittleEndian.Uint32(stream[sectionDeclOffset+16:])
if uint64(sdOff)+8 > uint64(len(stream)) {
return nil
}
section := stream[sdOff:]
shLen := binary.LittleEndian.Uint32(section[0:])
nProps := binary.LittleEndian.Uint32(section[4:])
if uint64(shLen) > uint64(len(section)) || nProps > 1<<16 || 8+8*nProps > shLen {
return nil
}
for i := uint32(0); i < nProps; i++ {
base := 8 + 8*i
id := binary.LittleEndian.Uint32(section[base:])
if id != propIDNameOfApplication {
continue
}
off := binary.LittleEndian.Uint32(section[base+4:])
if uint64(off)+8 > uint64(shLen) {
return nil
}
typ := binary.LittleEndian.Uint32(section[off:])
if typ&typeVector != 0 {
return nil
}
step := uint32(0)
switch typ & typeMask {
case typeStringASCII:
step = 1
case typeStringWide:
step = 2
default:
return nil
}
slen := binary.LittleEndian.Uint32(section[off+4:])
start := uint64(off) + 8
end := start + uint64(slen)*uint64(step)
if end > uint64(shLen) {
return nil
}
return printableLowBytes(section[start:end], int(step))
}
return nil
}
// printableLowBytes copies the printable low byte of each step-byte unit
// in b, stopping at the first NUL.
func printableLowBytes(b []byte, step int) []byte {
out := make([]byte, 0, len(b)/step)
for i := 0; i+step <= len(b); i += step {
c := b[i]
if c == 0 {
break
}
if c >= 0x20 && c < 0x7f {
out = append(out, c)
}
}
return out
}
// pattern is a case-insensitive substring → CDFType mapping. Entries are
// tested in order; first match wins. needle is stored upper-cased so it can be
// matched case-insensitively by scan.Bytes.Search with scan.IgnoreCase.
type pattern struct {
needle []byte
typ CDFType
}
// app2type maps NameOfApplication values to CDFTypes.
// Mirrors app2mime[] in libmagic. Needles are upper-cased for case-insensitive
// matching via scan.IgnoreCase.
var app2type = []pattern{
{[]byte("WORD"), CDFTypeDoc},
{[]byte("EXCEL"), CDFTypeXls},
{[]byte("POWERPOINT"), CDFTypePpt},
{[]byte("ADVANCED INSTALLER"), CDFTypeInstaller},
{[]byte("INSTALLSHIELD"), CDFTypeInstaller},
{[]byte("MICROSOFT PATCH COMPILER"), CDFTypeInstaller},
{[]byte("NANT"), CDFTypeInstaller},
{[]byte("WINDOWS INSTALLER"), CDFTypeInstaller},
}
// name2type maps directory entry names to CDFTypes.
// Mirrors name2mime[] in libmagic. Needles are upper-cased for case-insensitive
// matching via scan.IgnoreCase.
var name2type = []pattern{
{[]byte("BOOK"), CDFTypeXls},
{[]byte("WORKBOOK"), CDFTypeXls},
{[]byte("WORDDOCUMENT"), CDFTypeDoc},
{[]byte("POWERPOINT"), CDFTypePpt},
{[]byte("DIGITALSIGNATURE"), CDFTypeInstaller},
}
// lookupSubstring returns the CDFType for the first entry in t whose needle
// is a case-insensitive substring of v. Mirrors C's strcasestr semantics
// under the C locale. It allocates nothing: scan.IgnoreCase matches the
// upper-cased needle against input of either case.
func lookupSubstring(v []byte, t []pattern) (CDFType, bool) {
s := scan.Bytes(v)
for _, p := range t {
if i, _ := s.Search(p.needle, scan.IgnoreCase); i != -1 {
return p.typ, true
}
}
return CDFTypeGeneric, false
}
// msiCLSID is the Microsoft Installer root-storage CLSID, in on-disk byte
// order (cdf_directory_t.d_storage_uuid stores two little-endian uint64s).
var msiCLSID = []byte{
0x84, 0x10, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00,
0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46,
}
// section is a (directory entry name, type) → CDFType mapping.
type section struct {
name string
typ uint8
cdf CDFType
}
// sectionTypes maps distinctive directory entries to CDFTypes — a flattened
// equivalent of sectioninfo[] in libmagic. Used as a fallback when no
// SummaryInformation stream is present. A slice (rather than a map) lets
// lookupSection compare entry names without allocating a string key.
var sectionTypes = []section{
// libmagic uses application/encrypted, but that is not a registered media type.
// For now, we skip identifying that and fall-back on CDFTypeGeneric
// {"EncryptedPackage", dirTypeUserStream, CDFTypeEncrypted},
// {"EncryptedSummary", dirTypeUserStream, CDFTypeEncrypted},
{"Book", dirTypeUserStream, CDFTypeXls},
{"Workbook", dirTypeUserStream, CDFTypeXls},
{"WordDocument", dirTypeUserStream, CDFTypeDoc},
{"PowerPoint Document", dirTypeUserStream, CDFTypePpt},
{"__properties_version1.0", dirTypeUserStream, CDFTypeMsg},
{"__recip_version1.0_#00000000", dirTypeUserStorage, CDFTypeMsg},
}
// lookupSection returns the CDFType for a directory entry whose name and type
// match a sectionTypes entry exactly. The string(name) == comparison is
// optimized by the compiler to avoid allocating.
func lookupSection(name []byte, typ uint8) (CDFType, bool) {
for _, s := range sectionTypes {
if s.typ == typ && string(name) == s.name {
return s.cdf, true
}
}
return CDFTypeGeneric, false
}
+1 -21
View File
@@ -84,19 +84,8 @@ func FromPlain(content []byte) string {
break
}
}
hasHighBit := false
for _, c := range content {
if c >= 0x80 {
hasHighBit = true
break
}
}
if hasHighBit && utf8.Valid(content) {
return "utf-8"
}
// ASCII is a subset of UTF8. Follow W3C recommendation and replace with UTF8.
if ascii(origContent) {
if utf8.Valid(content) {
return "utf-8"
}
@@ -123,15 +112,6 @@ func latin(content []byte) string {
return "iso-8859-1"
}
func ascii(content []byte) bool {
for _, b := range content {
if textChars[b] != T {
return false
}
}
return true
}
// FromXML returns the charset of an XML document. It relies on the XML
// header <?xml version="1.0" encoding="UTF-8"?> and falls back on the plain
// text content.
+3 -3
View File
@@ -12,10 +12,10 @@ import (
type Parser struct {
comma byte
comment byte
s scan.Bytes
s *scan.Bytes
}
func NewParser(comma, comment byte, s scan.Bytes) *Parser {
func NewParser(comma, comment byte, s *scan.Bytes) *Parser {
return &Parser{
comma: comma,
comment: comment,
@@ -55,7 +55,7 @@ func (r *Parser) CountFields(collectIndexes bool) (fields int, fieldPos []int, h
if finished {
return 0, nil, false
}
finished = len(r.s) == 0 && len(line) == 0
finished = len(*r.s) == 0 && len(line) == 0
if len(line) == lengthNL(line) {
line = nil
continue // Skip empty lines.
+5
View File
@@ -10,6 +10,7 @@ const (
QueryGeo = "geo"
QueryHAR = "har"
QueryGLTF = "gltf"
QueryCDX = "cdx"
maxRecursion = 4096
)
@@ -40,6 +41,10 @@ var queries = map[string][]query{
SearchPath: [][]byte{[]byte("asset"), []byte("version")},
SearchVals: [][]byte{[]byte(`"1.0"`), []byte(`"2.0"`)},
}},
QueryCDX: {{
SearchPath: [][]byte{[]byte("bomFormat")},
SearchVals: [][]byte{[]byte(`"CycloneDX"`)},
}},
}
var parserPool = sync.Pool{
+68 -15
View File
@@ -3,6 +3,8 @@ package magic
import (
"bytes"
"encoding/binary"
"github.com/gabriel-vasile/mimetype/internal/mp3"
)
// Flac matches a Free Lossless Audio Codec file.
@@ -51,32 +53,83 @@ func AAC(raw []byte, _ uint32) bool {
return len(raw) > 1 && ((raw[0] == 0xFF && raw[1] == 0xF1) || (raw[0] == 0xFF && raw[1] == 0xF9))
}
// Mp3 matches an mp3 file.
func Mp3(raw []byte, limit uint32) bool {
// MP3 matches a .mp3 file.
func MP3(raw []byte, limit uint32) bool {
if len(raw) < 3 {
return false
}
if bytes.HasPrefix(raw, []byte("ID3")) {
// MP3s with an ID3v2 tag will start with "ID3"
// ID3v1 tags, however appear at the end of the file.
// Any ID3v2 is reported as MP3. Not entirely correct, but the mimesniff
// standard says so. https://mimesniff.spec.whatwg.org/#matching-an-audio-or-video-type-pattern
// Despite the standard only checking for "ID3", we do more validations to
// avoid false positives.
if id3v2(raw) {
return true
}
// Match MP3 files without tags
// If no ID3v2 tag found, then we will look for MP3 frames, but:
// a. Layer III files are a lot more prevalent than Layer I and II.
// b. Layer I frame header has looser constraints than the others: many files
// with regularly repeating 0xFFFF bytes can be misidentified as MP3.
// c. MP3 files are composed of individual frames and those frames can have
// leading garbage bytes: if we want to find all valid MP3s, we have to do a
// linear search. #775, #310
// d. There are file formats that contain MP3s inside: .mo3 and .swa
//
// Given a, b, c and d, this code:
// - initially tries to match by first two bytes in header
// - checks for .mo3 and .swa and disqualifies them
// - does linear search for Layer III
switch binary.BigEndian.Uint16(raw[:2]) & 0xFFFE {
case 0xFFFA:
// MPEG ADTS, layer III, v1
return true
case 0xFFF2:
// MPEG ADTS, layer III, v2
return true
case 0xFFE2:
// MPEG ADTS, layer III, v2.5
case 0xFFFA, 0xFFF2, 0xFFE2, // layer III: v1, v2, v2.5
0xFFFC, 0xFFF4, // layer II: v1, v2
0xFFF5: // layer I: v2
return true
}
// http://lclevy.free.fr/mo3/
if bytes.HasPrefix(raw, []byte("MO3")) {
return false
}
return false
// From PRONOM:
// Macromedia licensed the MP3 technology in 1995 to use in their Shockwave
// product. .swa or Shockwave Audio was originally added as a free plugin
// (Xtras) to SoundEdit 16 to export AIFF files to .swa.
// There is no media type assigned for .swa.
if bytes.HasPrefix(raw, []byte{0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00}) {
return false
}
_, size := mp3.ExtractFrame(raw)
return size > 0
}
// Based on https://id3.org/Developer%20Information.
func id3v2(raw []byte) bool {
if len(raw) < 10 || !bytes.HasPrefix(raw, []byte("ID3")) {
return false
}
if raw[3] < 2 || raw[3] > 4 { // Version: ID3v2.2 - ID3v2.4.
return false
}
if raw[4] != 0 { // Revision is 0 for all versions.
return false
}
// v2.2 uses 2 bits, v2.3 uses 3 bits and v2.4 uses 4.
// For all versions least significant 4 bits should be 0
if raw[5]&0b1111 != 0 {
return false
}
// Size bytes are synchsafe: most significant bit always 0.
if raw[6]&0x80 != 0 || raw[7]&0x80 != 0 || raw[8]&0x80 != 0 || raw[9]&0x80 != 0 {
return false
}
size := uint32(raw[6])<<21 | uint32(raw[7])<<14 | uint32(raw[8])<<7 | uint32(raw[9])
// Disallow too big frames, let's say 10MB.
return size > 0 && size < 10*1024*1024
}
// Wav matches a Waveform Audio File Format file.
+62 -7
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"debug/macho"
"encoding/binary"
"slices"
)
// Lnk matches Microsoft lnk binary format.
@@ -117,13 +118,7 @@ func Dbf(raw []byte, limit uint32) bool {
0x02, 0x03, 0x04, 0x05, 0x30, 0x31, 0x32, 0x42, 0x62, 0x7B, 0x82,
0x83, 0x87, 0x8A, 0x8B, 0x8E, 0xB3, 0xCB, 0xE5, 0xF5, 0xF4, 0xFB,
}
for _, b := range dbfTypes {
if raw[0] == b {
return true
}
}
return false
return slices.Contains(dbfTypes, raw[0])
}
// ElfObj matches an object file.
@@ -229,3 +224,63 @@ func TzIf(raw []byte, limit uint32) bool {
// Version has to be NUL (0x00), '2' (0x32) or '3' (0x33).
return raw[4] == 0x00 || raw[4] == 0x32 || raw[4] == 0x33
}
// Pyc matches a Python compiled file.
// The signatures are sourced from libmagic v5.47
func Pyc(raw []byte, limit uint32) bool {
if len(raw) < 8 {
return false
}
// python 1.0 through 3.7 signatures, magic/Magdir/python:13:190
pycMagic := []uint32{
0x02099900, 0x03099900, 0x892e0d0a, 0x04170d0a, 0x994e0d0a, 0xfcc40d0a,
0xfdc40d0a, 0x87c60d0a, 0x88c60d0a, 0x2aeb0d0a, 0x2beb0d0a, 0x2ded0d0a,
0x2eed0d0a, 0x3bf20d0a, 0x3cf20d0a, 0x45f20d0a, 0x59f20d0a, 0x63f20d0a,
0x6df20d0a, 0x6ef20d0a, 0x77f20d0a, 0x81f20d0a, 0x8bf20d0a, 0x8cf20d0a,
0x95f20d0a, 0x9ff20d0a, 0xa9f20d0a, 0xb3f20d0a, 0xb4f20d0a, 0xc7f20d0a,
0xd1f20d0a, 0xd2f20d0a, 0xdbf20d0a, 0xe5f20d0a, 0xeff20d0a, 0xf9f20d0a,
0x03f30d0a, 0x04f30d0a, 0x0af30d0a, 0xb80b0d0a, 0xc20b0d0a, 0xcc0b0d0a,
0xd60b0d0a, 0xe00b0d0a, 0xea0b0d0a, 0xf40b0d0a, 0xf50b0d0a, 0xff0b0d0a,
0x090c0d0a, 0x130c0d0a, 0x1d0c0d0a, 0x1f0c0d0a, 0x270c0d0a, 0x3b0c0d0a,
0x450c0d0a, 0x4f0c0d0a, 0x580c0d0a, 0x620c0d0a, 0x6c0c0d0a, 0x760c0d0a,
0x800c0d0a, 0x8a0c0d0a, 0x940c0d0a, 0x9e0c0d0a, 0xb20c0d0a, 0xbc0c0d0a,
0xc60c0d0a, 0xd00c0d0a, 0xda0c0d0a, 0xe40c0d0a, 0xee0c0d0a, 0xf80c0d0a,
0x020d0d0a, 0x0c0d0d0a, 0x160d0d0a, 0x170d0d0a, 0x200d0d0a, 0x210d0d0a,
0x2a0d0d0a, 0x2b0d0d0a, 0x2c0d0d0a, 0x2d0d0d0a, 0x2f0d0d0a, 0x300d0d0a,
0x310d0d0a, 0x320d0d0a, 0x330d0d0a, 0x3e0d0d0a, 0x3f0d0d0a,
}
n := binary.BigEndian.Uint32(raw)
if slices.Contains(pycMagic, n) {
return true
}
if raw[2] == 0x0d && raw[3] == 0x0a {
// Only two bits of flag field are currently used.
if l := binary.LittleEndian.Uint32(raw[4:]); l > 3 {
return false
}
if raw[1] == 0x0d || raw[1] == 0x0e {
return true
}
// PyPy magic numbers, magic/Magdir/python:233
n := binary.LittleEndian.Uint16(raw)
return n == 240 || n == 256 || n == 336 || n == 384 || n == 416
}
return false
}
// Pcap identifies "libpcap" capture files.
// https://www.tcpdump.org/manpages/pcap-savefile.5.html
func Pcap(raw []byte, _ uint32) bool {
if len(raw) < 4 {
return false
}
be := binary.BigEndian.Uint32(raw)
le := binary.LittleEndian.Uint32(raw)
return be == 0xa1b2c3d4 || be == 0xa1b23c4d ||
le == 0xa1b2c3d4 || le == 0xa1b23c4d
}
+41 -8
View File
@@ -3,6 +3,7 @@ package magic
import (
"bytes"
"encoding/binary"
"slices"
)
// Woff matches a Web Open Font Format file.
@@ -29,12 +30,13 @@ func Ttf(raw []byte, limit uint32) bool {
if !bytes.HasPrefix(raw, []byte{0x00, 0x01, 0x00, 0x00}) {
return false
}
// We cannot rely on the first 4 bytes because of false-positives.
// We have to digg deeper into the SFNT tables.
return hasSFNTTable(raw)
}
func hasSFNTTable(raw []byte) bool {
// 49 possible tables as explained below
if len(raw) < 16 || binary.BigEndian.Uint16(raw[4:]) >= 49 {
if len(raw) < 16 {
return false
}
@@ -87,14 +89,45 @@ func hasSFNTTable(raw []byte) bool {
0x6e616d65, // "name"
0x6f706264, // "opbd"
0x4f532f32, // "OS/2"
// The above tables come from the original Apple TTF specification,
// but the later Microsoft specification has additional tables.
// Common tables: https://learn.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats
// Layout tables: https://learn.microsoft.com/en-us/typography/opentype/spec/chapter2
// Even if the Microsoft specification says OpenType, the tables are
// valid for TrueType as well.
0x47535542, // "GSUB"
0x47504f53, // "GPOS"
0x42415345, // "BASE"
0x4a535446, // "JSTF"
0x47444546, // "GDEF"
0x4d415448, // "MATH"
0x43424454, // "CBDT"
0x43424c43, // "CBLC"
0x43464620, // "CFF "
0x43464632, // "CFF2"
0x434f4c52, // "COLR"
0x4350414c, // "CPAL"
0x44534947, // "DSIG"
0x45424454, // "EBDT"
0x45424c43, // "EBLC"
0x48564152, // "HVAR"
0x4c545348, // "LTSH"
0x4d455247, // "MERG"
0x4d564152, // "MVAR"
0x50434c54, // "PCLT"
0x706f7374, // "post"
0x70726570, // "prep"
0x73626978, // "sbix"
0x53544154, // "STAT"
0x53564720, // "SVG "
0x56444d58, // "VDMX"
0x76686561, // "vhea"
0x766d7478, // "vmtx"
0x564f5247, // "VORG"
0x56564152, // "VVAR"
}
ourTable := binary.BigEndian.Uint32(raw[12:16])
for _, t := range possibleTables {
if ourTable == t {
return true
}
}
return false
return slices.Contains(possibleTables, ourTable)
}
// Eot matches an Embedded OpenType font file.
+2 -7
View File
@@ -3,6 +3,7 @@ package magic
import (
"bytes"
"encoding/binary"
"slices"
)
// Shp matches a shape format file.
@@ -39,13 +40,7 @@ func Shp(raw []byte, limit uint32) bool {
31, // MultiPatch
}
for _, st := range shapeTypes {
if st == int(binary.LittleEndian.Uint32(raw[108:112])) {
return true
}
}
return false
return slices.Contains(shapeTypes, int(binary.LittleEndian.Uint32(raw[108:112])))
}
// Shx matches a shape index format file.
+27 -1
View File
@@ -4,6 +4,8 @@ import (
"bytes"
"encoding/binary"
"slices"
"github.com/gabriel-vasile/mimetype/internal/scan"
)
// Png matches a Portable Network Graphics file.
@@ -15,7 +17,31 @@ func Png(raw []byte, _ uint32) bool {
// Apng matches an Animated Portable Network Graphics file.
// https://wiki.mozilla.org/APNG_Specification
func Apng(raw []byte, _ uint32) bool {
return offset(raw, []byte("acTL"), 37)
b := scan.Bytes(raw)
b.Advance(8) // the first 8 bytes matched by regular png
// PNG chunks are composed of:
// 4 bytes: length in big endian
// 4 bytes: chunk type
// length bytes: chunk data
// 4 bytes: CRC
//
// Limit to 32, so we don't waste time on huge inputs.
// acTL chunk must come before any IDAT chunks.
// https://www.w3.org/TR/png-3/#structure
for i := 0; i < 32 && len(b) > 0; i++ {
sz, _ := b.Uint32be()
if bytes.HasPrefix(b, []byte("acTL")) {
return true
}
if bytes.HasPrefix(b, []byte("IDAT")) {
return false
}
if !b.Advance(int(sz + 8)) {
return false
}
}
return false
}
// Jpg matches a Joint Photographic Experts Group file.
+7 -2
View File
@@ -136,6 +136,11 @@ func ftyp(raw []byte, sigs ...[]byte) bool {
return false
}
type shebangSig struct {
sig []byte
flag scan.Flags
}
// A valid shebang starts with the "#!" characters,
// followed by any number of spaces,
// followed by the path to the interpreter,
@@ -146,7 +151,7 @@ func ftyp(raw []byte, sigs ...[]byte) bool {
// #! /usr/bin/env php
//
// /usr/bin/env is the interpreter, php is the first and only argument.
func shebang(b scan.Bytes, matchFlags scan.Flags, sigs ...[]byte) bool {
func shebang(b scan.Bytes, sigs ...shebangSig) bool {
line := b.Line()
if len(line) < 2 || line[0] != '#' || line[1] != '!' {
return false
@@ -154,7 +159,7 @@ func shebang(b scan.Bytes, matchFlags scan.Flags, sigs ...[]byte) bool {
line = line[2:]
line.TrimLWS()
for _, s := range sigs {
if line.Match(s, matchFlags) != -1 {
if line.Match(s.sig, s.flag) != -1 {
return true
}
}
+39 -13
View File
@@ -3,6 +3,8 @@ package magic
import (
"bytes"
"encoding/binary"
"github.com/gabriel-vasile/mimetype/internal/cdf"
)
// Xlsx matches a Microsoft Excel 2007 file.
@@ -47,6 +49,15 @@ func Ole(raw []byte, limit uint32) bool {
// Doc matches a Microsoft Word 97-2003 file.
// See: https://github.com/decalage2/oletools/blob/412ee36ae45e70f42123e835871bac956d958461/oletools/common/clsid.py
func Doc(raw []byte, _ uint32) bool {
fromParsing := cdf.Detect(raw)
if fromParsing == cdf.CDFTypeDoc {
return true
}
if fromParsing != cdf.CDFTypeGeneric {
return false
}
// Fallback for inputs where the CDF directory is past the read limit: match
// the root storage CLSID, which often lies within the first sectors.
clsids := [][]byte{
// Microsoft Word 97-2003 Document (Word.Document.8)
{0x06, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
@@ -55,19 +66,25 @@ func Doc(raw []byte, _ uint32) bool {
// Microsoft Word Picture (Word.Picture.8)
{0x07, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
}
for _, clsid := range clsids {
if matchOleClsid(raw, clsid) {
return true
}
}
return false
}
// Ppt matches a Microsoft PowerPoint 97-2003 file or a PowerPoint 95 presentation.
func Ppt(raw []byte, limit uint32) bool {
// Root CLSID test is the safest way to detect identify OLE, however, the format
fromParsing := cdf.Detect(raw)
if fromParsing == cdf.CDFTypePpt {
return true
}
if fromParsing != cdf.CDFTypeGeneric {
return false
}
// Fallback for inputs where the CDF directory is past the read limit.
// Root CLSID test is the safest way to identify the OLE, however, the format
// often places the root CLSID at the end of the file.
if matchOleClsid(raw, []byte{
0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11,
@@ -94,18 +111,21 @@ func Ppt(raw []byte, limit uint32) bool {
}
}
if bytes.HasPrefix(raw[512:], []byte{0xFD, 0xFF, 0xFF, 0xFF}) &&
raw[518] == 0x00 && raw[519] == 0x00 {
return true
}
return lin > 1152 && bytes.Contains(raw[1152:min(4096, lin)],
[]byte("P\x00o\x00w\x00e\x00r\x00P\x00o\x00i\x00n\x00t\x00 D\x00o\x00c\x00u\x00m\x00e\x00n\x00t"))
}
// Xls matches a Microsoft Excel 97-2003 file.
func Xls(raw []byte, limit uint32) bool {
// Root CLSID test is the safest way to detect identify OLE, however, the format
fromParsing := cdf.Detect(raw)
if fromParsing == cdf.CDFTypeXls {
return true
}
if fromParsing != cdf.CDFTypeGeneric {
return false
}
// Fallback for inputs where the CDF directory is past the read limit.
// Root CLSID test is the safest way to identify the OLE, however, the format
// often places the root CLSID at the end of the file.
if matchOleClsid(raw, []byte{
0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
@@ -148,6 +168,15 @@ func Pub(raw []byte, limit uint32) bool {
// Msg matches a Microsoft Outlook email file.
func Msg(raw []byte, limit uint32) bool {
fromParsing := cdf.Detect(raw)
if fromParsing == cdf.CDFTypeMsg {
return true
}
if fromParsing != cdf.CDFTypeGeneric {
return false
}
// Fallback for inputs where the CDF directory does not carry the streams the
// parser keys on: match the root storage CLSID instead.
return matchOleClsid(raw, []byte{
0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46,
@@ -157,10 +186,7 @@ func Msg(raw []byte, limit uint32) bool {
// Msi matches a Microsoft Windows Installer file.
// http://fileformats.archiveteam.org/wiki/Microsoft_Compound_File
func Msi(raw []byte, limit uint32) bool {
return matchOleClsid(raw, []byte{
0x84, 0x10, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00,
0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46,
})
return cdf.Detect(raw) == cdf.CDFTypeInstaller
}
// One matches a Microsoft OneNote file.
+147 -82
View File
@@ -130,6 +130,14 @@ func Xfdf(raw []byte, _ uint32) bool {
return xml(raw, xmlSig{[]byte("<xfdf"), []byte(`xmlns="http://ns.adobe.com/xfdf/"`)})
}
// CDXXML matches a CycloneDX XML BOM file.
// https://cyclonedx.org/docs/1.7/xml/
func CDXXML(raw []byte, _ uint32) bool {
// xmlns is missing the version suffix because there are too many past versions
// and probably future versions to come.
return xml(raw, xmlSig{[]byte("<bom"), []byte(`xmlns="http://cyclonedx.org/schema/bom/`)})
}
// VCard matches a Virtual Contact File.
func VCard(raw []byte, _ uint32) bool {
return ciPrefix(raw, []byte("BEGIN:VCARD\n"), []byte("BEGIN:VCARD\r\n"))
@@ -139,6 +147,14 @@ func VCard(raw []byte, _ uint32) bool {
func ICalendar(raw []byte, _ uint32) bool {
return ciPrefix(raw, []byte("BEGIN:VCALENDAR\n"), []byte("BEGIN:VCALENDAR\r\n"))
}
const (
snone = 0
scws = scan.CompactWS
sfw = scan.FullWord
scwsfw = scan.CompactWS | scan.FullWord
)
func phpPageF(raw []byte, _ uint32) bool {
return ciPrefix(raw,
[]byte("<?PHP"),
@@ -149,66 +165,61 @@ func phpPageF(raw []byte, _ uint32) bool {
}
func phpScriptF(raw []byte, _ uint32) bool {
return shebang(raw,
scan.CompactWS,
[]byte("/usr/local/bin/php"),
[]byte("/usr/bin/php"),
[]byte("/usr/bin/env php"),
[]byte("/usr/bin/env -S php"),
shebangSig{[]byte("/usr/local/bin/php"), snone},
shebangSig{[]byte("/usr/bin/php"), snone},
shebangSig{[]byte("/usr/bin/env php"), scws},
shebangSig{[]byte("/usr/bin/env -S php"), scws},
)
}
// Js matches a Javascript file.
func Js(raw []byte, _ uint32) bool {
return shebang(raw,
scan.CompactWS,
[]byte("/bin/node"),
[]byte("/usr/bin/node"),
[]byte("/bin/nodejs"),
[]byte("/usr/bin/nodejs"),
[]byte("/usr/bin/env node"),
[]byte("/usr/bin/env -S node"),
[]byte("/usr/bin/env nodejs"),
[]byte("/usr/bin/env -S nodejs"),
shebangSig{[]byte("/bin/node"), snone},
shebangSig{[]byte("/usr/bin/node"), snone},
shebangSig{[]byte("/bin/nodejs"), snone},
shebangSig{[]byte("/usr/bin/nodejs"), snone},
shebangSig{[]byte("/usr/bin/env node"), scws},
shebangSig{[]byte("/usr/bin/env -S node"), scws},
shebangSig{[]byte("/usr/bin/env nodejs"), scws},
shebangSig{[]byte("/usr/bin/env -S nodejs"), scws},
)
}
// Lua matches a Lua programming language file.
func Lua(raw []byte, _ uint32) bool {
return shebang(raw,
scan.CompactWS|scan.FullWord,
[]byte("/usr/bin/lua"),
[]byte("/usr/local/bin/lua"),
[]byte("/usr/bin/env lua"),
[]byte("/usr/bin/env -S lua"),
shebangSig{[]byte("/usr/bin/lua"), sfw},
shebangSig{[]byte("/usr/local/bin/lua"), sfw},
shebangSig{[]byte("/usr/bin/env lua"), scwsfw},
shebangSig{[]byte("/usr/bin/env -S lua"), scwsfw},
)
}
// Perl matches a Perl programming language file.
func Perl(raw []byte, _ uint32) bool {
return shebang(raw,
scan.CompactWS|scan.FullWord,
[]byte("/usr/bin/perl"),
[]byte("/usr/bin/env perl"),
[]byte("/usr/bin/env -S perl"),
shebangSig{[]byte("/usr/bin/perl"), sfw},
shebangSig{[]byte("/usr/bin/env perl"), scwsfw},
shebangSig{[]byte("/usr/bin/env -S perl"), scwsfw},
)
}
// Python matches a Python programming language file.
func Python(raw []byte, _ uint32) bool {
return shebang(raw,
scan.CompactWS,
[]byte("/usr/bin/python"),
[]byte("/usr/local/bin/python"),
[]byte("/usr/bin/env python"),
[]byte("/usr/bin/env -S python"),
[]byte("/usr/bin/python2"),
[]byte("/usr/local/bin/python2"),
[]byte("/usr/bin/env python2"),
[]byte("/usr/bin/env -S python2"),
[]byte("/usr/bin/python3"),
[]byte("/usr/local/bin/python3"),
[]byte("/usr/bin/env python3"),
[]byte("/usr/bin/env -S python3"),
shebangSig{[]byte("/usr/bin/python"), snone},
shebangSig{[]byte("/usr/local/bin/python"), snone},
shebangSig{[]byte("/usr/bin/env python"), scws},
shebangSig{[]byte("/usr/bin/env -S python"), scws},
shebangSig{[]byte("/usr/bin/python2"), snone},
shebangSig{[]byte("/usr/local/bin/python2"), snone},
shebangSig{[]byte("/usr/bin/env python2"), scws},
shebangSig{[]byte("/usr/bin/env -S python2"), scws},
shebangSig{[]byte("/usr/bin/python3"), snone},
shebangSig{[]byte("/usr/local/bin/python3"), snone},
shebangSig{[]byte("/usr/bin/env python3"), scws},
shebangSig{[]byte("/usr/bin/env -S python3"), scws},
)
}
@@ -216,30 +227,28 @@ func Python(raw []byte, _ uint32) bool {
// Ruby matches a Ruby programming language file.
func Ruby(raw []byte, _ uint32) bool {
return shebang(raw,
scan.CompactWS,
[]byte("/usr/bin/ruby"),
[]byte("/usr/local/bin/ruby"),
[]byte("/usr/bin/env ruby"),
[]byte("/usr/bin/env -S ruby"),
shebangSig{[]byte("/usr/bin/ruby"), snone},
shebangSig{[]byte("/usr/local/bin/ruby"), snone},
shebangSig{[]byte("/usr/bin/env ruby"), scws},
shebangSig{[]byte("/usr/bin/env -S ruby"), scws},
)
}
// Tcl matches a Tcl programming language file.
func Tcl(raw []byte, _ uint32) bool {
return shebang(raw,
scan.CompactWS,
[]byte("/usr/bin/tcl"),
[]byte("/usr/local/bin/tcl"),
[]byte("/usr/bin/env tcl"),
[]byte("/usr/bin/env -S tcl"),
[]byte("/usr/bin/tclsh"),
[]byte("/usr/local/bin/tclsh"),
[]byte("/usr/bin/env tclsh"),
[]byte("/usr/bin/env -S tclsh"),
[]byte("/usr/bin/wish"),
[]byte("/usr/local/bin/wish"),
[]byte("/usr/bin/env wish"),
[]byte("/usr/bin/env -S wish"),
shebangSig{[]byte("/usr/bin/tcl"), snone},
shebangSig{[]byte("/usr/local/bin/tcl"), snone},
shebangSig{[]byte("/usr/bin/env tcl"), scws},
shebangSig{[]byte("/usr/bin/env -S tcl"), scws},
shebangSig{[]byte("/usr/bin/tclsh"), snone},
shebangSig{[]byte("/usr/local/bin/tclsh"), snone},
shebangSig{[]byte("/usr/bin/env tclsh"), scws},
shebangSig{[]byte("/usr/bin/env -S tclsh"), scws},
shebangSig{[]byte("/usr/bin/wish"), snone},
shebangSig{[]byte("/usr/local/bin/wish"), snone},
shebangSig{[]byte("/usr/bin/env wish"), scws},
shebangSig{[]byte("/usr/bin/env -S wish"), scws},
)
}
@@ -251,32 +260,31 @@ func Rtf(raw []byte, _ uint32) bool {
// Shell matches a shell script file.
func Shell(raw []byte, _ uint32) bool {
return shebang(raw,
scan.CompactWS|scan.FullWord,
[]byte("/bin/sh"),
[]byte("/bin/bash"),
[]byte("/usr/local/bin/bash"),
[]byte("/usr/bin/env bash"),
[]byte("/usr/bin/env -S bash"),
[]byte("/bin/csh"),
[]byte("/usr/local/bin/csh"),
[]byte("/usr/bin/env csh"),
[]byte("/usr/bin/env -S csh"),
[]byte("/bin/dash"),
[]byte("/usr/local/bin/dash"),
[]byte("/usr/bin/env dash"),
[]byte("/usr/bin/env -S dash"),
[]byte("/bin/ksh"),
[]byte("/usr/local/bin/ksh"),
[]byte("/usr/bin/env ksh"),
[]byte("/usr/bin/env -S ksh"),
[]byte("/bin/tcsh"),
[]byte("/usr/local/bin/tcsh"),
[]byte("/usr/bin/env tcsh"),
[]byte("/usr/bin/env -S tcsh"),
[]byte("/bin/zsh"),
[]byte("/usr/local/bin/zsh"),
[]byte("/usr/bin/env zsh"),
[]byte("/usr/bin/env -S zsh"),
shebangSig{[]byte("/bin/sh"), sfw},
shebangSig{[]byte("/bin/bash"), sfw},
shebangSig{[]byte("/usr/local/bin/bash"), sfw},
shebangSig{[]byte("/usr/bin/env bash"), scwsfw},
shebangSig{[]byte("/usr/bin/env -S bash"), scwsfw},
shebangSig{[]byte("/bin/csh"), sfw},
shebangSig{[]byte("/usr/local/bin/csh"), sfw},
shebangSig{[]byte("/usr/bin/env csh"), scwsfw},
shebangSig{[]byte("/usr/bin/env -S csh"), scwsfw},
shebangSig{[]byte("/bin/dash"), sfw},
shebangSig{[]byte("/usr/local/bin/dash"), sfw},
shebangSig{[]byte("/usr/bin/env dash"), scwsfw},
shebangSig{[]byte("/usr/bin/env -S dash"), scwsfw},
shebangSig{[]byte("/bin/ksh"), sfw},
shebangSig{[]byte("/usr/local/bin/ksh"), sfw},
shebangSig{[]byte("/usr/bin/env ksh"), scwsfw},
shebangSig{[]byte("/usr/bin/env -S ksh"), scwsfw},
shebangSig{[]byte("/bin/tcsh"), sfw},
shebangSig{[]byte("/usr/local/bin/tcsh"), sfw},
shebangSig{[]byte("/usr/bin/env tcsh"), scwsfw},
shebangSig{[]byte("/usr/bin/env -S tcsh"), scwsfw},
shebangSig{[]byte("/bin/zsh"), sfw},
shebangSig{[]byte("/usr/local/bin/zsh"), sfw},
shebangSig{[]byte("/usr/bin/env zsh"), scwsfw},
shebangSig{[]byte("/usr/bin/env -S zsh"), scwsfw},
)
}
@@ -352,6 +360,12 @@ func GLTF(raw []byte, limit uint32) bool {
return jsonHelper(raw, limit, json.QueryGLTF, json.TokObject)
}
// CDXJSON matches a CycloneDX JSON BOM file.
// https://cyclonedx.org/docs/1.7/json/
func CDXJSON(raw []byte, limit uint32) bool {
return jsonHelper(raw, limit, json.QueryCDX, json.TokObject)
}
// jsonHelper parses raw and tries to match the q query against it. wantToks
// ensures we're not wasting time parsing an input that would not pass anyway,
// ex: the input is a valid JSON array, but we're looking for a JSON object.
@@ -393,8 +407,16 @@ func NdJSON(raw []byte, limit uint32) bool {
var l scan.Bytes
for len(s) != 0 {
l = s.Line()
_, inspected, firstToken, _ := json.Parse(json.QueryNone, l)
if len(l) != inspected {
parsed, inspected, firstToken, _ := json.Parse(json.QueryNone, l)
// Only the last line may be truncated by the read limit; for it, it is
// enough that the parser inspected all of it. Every other line must be a
// complete, valid JSON document, otherwise a single JSON document spread
// over multiple lines would be mistaken for NDJSON. #803
if len(s) == 0 {
if inspected != len(l) {
return false
}
} else if parsed != len(l) {
return false
}
if firstToken == json.TokArray || firstToken == json.TokObject {
@@ -563,6 +585,8 @@ func RFC822(raw []byte, limit uint32) bool {
// Some of the hints are IgnoreCase, some not. I selected based on what libmagic
// does and based on personal observations from sample files.
hints := []rfc822Hint{
// Enron dataset has Message-ID, Message-Id and Message-id.
{[]byte("Message-ID: "), scan.IgnoreCase},
{[]byte("From: "), 0},
{[]byte("To: "), 0},
{[]byte("CC: "), scan.IgnoreCase},
@@ -599,3 +623,44 @@ func lineHasRFC822Hint(b scan.Bytes, hints []rfc822Hint) bool {
}
return false
}
func GEDCOM(raw []byte, limit uint32) bool {
// Skip if empty
if len(raw) == 0 {
return false
}
// GEDCOM header fits within first 4KB
searchLimit := min(len(raw), 4096)
raw = raw[:searchLimit]
b := scan.Bytes(raw)
// Skip BOM if present: UTF-8, UTF-16BE, UTF-16LE
for _, bom := range [][]byte{
{0xEF, 0xBB, 0xBF}, // UTF-8
{0xFE, 0xFF}, // UTF-16BE
{0xFF, 0xFE}, // UTF-16LE
} {
if bytes.HasPrefix(b, bom) {
b.Advance(len(bom))
break // Only one BOM can exist at the start
}
}
b.TrimLWS()
firstLine := b.Line()
if !bytes.Equal(firstLine, []byte("0 HEAD")) {
return false
}
// "1 GEDC" is mandatory in the header
for i := 0; i < 10; i++ {
line := b.Line()
if bytes.Equal(line, []byte("1 GEDC")) {
return true
}
}
return false
}
+17 -4
View File
@@ -17,8 +17,7 @@ func TSV(raw []byte, limit uint32) bool {
func sv(in []byte, comma byte, limit uint32) bool {
s := scan.Bytes(in)
s.DropLastLine(limit)
r := csv.NewParser(comma, '#', s)
r := csv.NewParser(comma, '#', &s)
headerFields, _, hasMore := r.CountFields(false)
if headerFields < 2 || !hasMore {
@@ -30,8 +29,22 @@ func sv(in []byte, comma byte, limit uint32) bool {
if !hasMore && fields == 0 {
break
}
csvLines++
if fields != headerFields {
if fields == headerFields {
csvLines++
} else {
// maybeTruncated signals the input was cut at the read limit,
// meaning the last line may be an incomplete CSV record.
maybeTruncated := limit > 0 && uint64(len(in)) >= uint64(limit)
if maybeTruncated && fields < headerFields {
// Allow the last row to have any number of fields
// if the input is maybeTruncated.
// BUG: if len(input) == limit, then the input is not truncated
// but it is still allowed to have the wrong number of fields
// and it will be reported as valid CSV.
if len(s) == 0 {
break
}
}
return false
}
if csvLines >= 10 {
+2 -4
View File
@@ -49,10 +49,8 @@ func isMatroskaFileTypeMatched(in []byte, flType string) bool {
// The logic of search is: find first instance of \x42\x82 and then
// search for given string after n bytes of above instance.
func isFileTypeNamePresent(in []byte, flType string) bool {
ind, maxInd, lenIn := 0, 4096, len(in)
if lenIn < maxInd { // restricting length to 4096
maxInd = lenIn
}
ind, lenIn := 0, len(in)
maxInd := min(4096, lenIn)
ind = bytes.Index(in[:maxInd], []byte("\x42\x82"))
if ind > 0 && lenIn > ind+2 {
ind += 2
+79 -4
View File
@@ -187,11 +187,11 @@ func msoxml(raw scan.Bytes, searchFor zipEntries, stopAfter int) bool {
return false
}
var zipLocalFileHeader = []byte("PK\003\004")
// next extracts the name of the next zip entry.
func (i *zipIterator) next() []byte {
pk := []byte("PK\003\004")
n := bytes.Index(i.b, pk)
n := bytes.Index(i.b, zipLocalFileHeader)
if n == -1 {
return nil
}
@@ -212,10 +212,85 @@ func (i *zipIterator) next() []byte {
return i.b[:l]
}
// skipZipflingerEntry tries to detect a Zipflinger virtual entry and skips it.
// The detection is based on the following properties:
// - compression method is 0
// - CRC32 is 0
// - compressed size is 0
// - uncompressed size is 0
// - file name is empty
// Returns true if it was found and skipped.
func (i *zipIterator) skipZipflingerEntry() (skipped bool) {
// Make a backup of the data so the inspection does not loses it.
b := i.b
defer func() {
// If no zipflinger was found, restore the original data.
if !skipped {
i.b = b
}
}()
n := bytes.Index(i.b, zipLocalFileHeader)
if n == -1 {
return false
}
if !i.b.Advance(0x08) {
return false
}
// Check compression method
if cm, ok := i.b.Uint16(); !ok || cm != 0 {
return false
}
// Advance up to the CRC32 field
if !i.b.Advance(0x04) {
return false
}
// Check CRC32
if crc32, ok := i.b.Uint32(); !ok || crc32 != 0 {
return false
}
// Check compressed size
if compressedSize, ok := i.b.Uint32(); !ok || compressedSize != 0 {
return false
}
// Check uncompressed size
if uncompressedSize, ok := i.b.Uint32(); !ok || uncompressedSize != 0 {
return false
}
// Check for empty file name
if l, ok := i.b.Uint16(); !ok || l != 0 {
return false
}
// Reached a zipflinger virtual entry: skip extra data
l, ok := i.b.Uint16()
if !ok {
return false
}
if !i.b.Advance(int(l)) {
return false
}
return true
}
// APK matches an Android Package Archive.
// The source of signatures is https://github.com/file/file/blob/1778642b8ba3d947a779a36fcd81f8e807220a19/magic/Magdir/archive#L1820-L1887
func APK(raw []byte, _ uint32) bool {
return zipHas(raw, zipEntries{{
iter := zipIterator{raw}
// If a Zipflinger Virtual Entry is detected, then the data is considered APK
if iter.skipZipflingerEntry() {
return true
}
return zipHas(iter.b, zipEntries{{
name: []byte("AndroidManifest.xml"),
}, {
name: []byte("META-INF/com/android/build/gradle/app-metadata.properties"),
+140
View File
@@ -0,0 +1,140 @@
package mp3
import "bytes"
// minTruncatedSyncMatches is the minimum number of confirmed successive
// header matches required to accept a candidate frame when the buffer ends
// before maxFrameSyncMatches confirmations can be performed.
const minTruncatedSyncMatches = 2
func ExtractFrame(b []byte) (start, size int) {
limit := min(len(b), 2048+headerSize)
for i := 0; i < limit-headerSize; i++ {
j := bytes.IndexByte(b[i:limit-headerSize], 0xFF)
if j < 0 {
break
}
i += j
hdr := header{b[i], b[i+1], b[i+2], b[i+3]}
if !hdr.valid() {
continue
}
frameBytes := hdr.frameBytes()
frameAndPad := frameBytes + hdr.padding()
validHere := frameBytes > 0 && i+frameAndPad <= len(b) && matchFrame(b[i:])
// When the buffer is exactly one frame, matchFrame cannot look ahead for
// a subsequent header to confirm the stream. Trust the validated header.
exact := i == 0 && frameAndPad == len(b)
if validHere || exact {
return i, frameAndPad
}
}
return 0, 0
}
// matchFrame confirms a candidate header by stepping forward and checking that
// subsequent headers are consistent.
func matchFrame(buf []byte) bool {
// maxFrameSyncMatches limits how many valid frames we look at.
const maxFrameSyncMatches = 10
hdr := header{buf[0], buf[1], buf[2], buf[3]}
i := hdr.frameBytes() + hdr.padding()
for nmatch := 0; nmatch < maxFrameSyncMatches; nmatch++ {
if i+headerSize > len(buf) {
return nmatch >= minTruncatedSyncMatches
}
cmp := header{buf[i], buf[i+1], buf[i+2], buf[i+3]}
if !hdr.compatibleWith(cmp) {
return false
}
i += cmp.frameBytes() + cmp.padding()
}
return true
}
const headerSize = 4
type header [headerSize]byte
func (h header) isFreeFormat() bool { return h[2]&0xF0 == 0 }
func (h header) isMPEG1() bool { return h[1]&0x8 != 0 }
func (h header) isMPEG25() bool { return h[1]&0x10 == 0 }
func (h header) rawLayer() byte { return h[1] >> 1 & 3 }
func (h header) rawBitrate() byte { return h[2] >> 4 }
func (h header) rawSampleRate() byte { return h[2] >> 2 & 3 }
func (h header) rawEmphasis() byte { return h[3] & 0b11 }
func (h header) isFrame576() bool { return h[1]&14 == 2 }
func (h header) padding() int {
if h[2]&0x2 != 0 {
return 1
}
return 0
}
// valid reports whether the four bytes form a syntactically valid MP3 header.
func (h header) valid() bool {
return h[0] == 0xff &&
((h[1]&0xF0) == 0xf0 || (h[1]&0xFE) == 0xe2) &&
h.rawLayer() == 1 && // Layer III
h.rawBitrate() != 15 && // Not allowed by spec.
h.rawSampleRate() != 3 &&
h.rawEmphasis() != 2 &&
// The code for extracting frame size for free-format is tedious and
// free-format MP3s are extinct.
!h.isFreeFormat()
}
// compatibleWith reports whether two headers describe frames belonging to the
// same MP3 stream — same MPEG version, layer, sample-rate index.
func (h header) compatibleWith(o header) bool {
return o.valid() &&
(h[1]^o[1])&0xFE == 0 &&
(h[2]^o[2])&0x0C == 0
}
// bitrateKbps returns the bitrate of the frame in kilobits per second.
func (h header) bitrateKbps() int {
// halfrate[mpeg1?][bitrate_idx] holds bitrate/2 in kbps.
halfrate := [2][15]uint8{
{0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 72, 80},
{0, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160},
}
mpeg1 := 0
if h.isMPEG1() {
mpeg1 = 1
}
return 2 * int(halfrate[mpeg1][h.rawBitrate()])
}
// sampleRateHz returns the sampling rate of the frame in Hz.
func (h header) sampleRateHz() int {
base := [3]int{44100, 48000, 32000}[h.rawSampleRate()]
if !h.isMPEG1() {
base >>= 1
}
if h.isMPEG25() {
base >>= 1
}
return base
}
// frameSamples returns the number of audio samples per channel encoded in
// the frame.
func (h header) frameSamples() int {
if h.isFrame576() {
return 576
}
return 1152
}
// frameBytes returns the size of the frame body (header + side info + audio
// data, excluding padding) in bytes.
func (h header) frameBytes() int {
br := h.bitrateKbps()
sr := h.sampleRateHz()
if br == 0 || sr == 0 {
return 0
}
return h.frameSamples() * br * 125 / sr
}
+21 -25
View File
@@ -122,26 +122,6 @@ func (b *Bytes) Line() Bytes {
return line
}
// DropLastLine drops the last incomplete line from b.
//
// mimetype limits itself to ReadLimit bytes when performing a detection.
// This means, for file formats like CSV for NDJSON, the last line of the input
// can be an incomplete line.
// If b length is less than readLimit, it means we received an incomplete file
// and proceed with dropping the last line.
func (b *Bytes) DropLastLine(readLimit uint32) {
if readLimit == 0 || uint64(len(*b)) < uint64(readLimit) {
return
}
for i := len(*b) - 1; i > 0; i-- {
if (*b)[i] == '\n' {
*b = (*b)[:i]
return
}
}
}
func (b *Bytes) Uint16() (uint16, bool) {
if len(*b) < 2 {
return 0, false
@@ -151,6 +131,24 @@ func (b *Bytes) Uint16() (uint16, bool) {
return v, true
}
func (b *Bytes) Uint32() (uint32, bool) {
if len(*b) < 4 {
return 0, false
}
v := binary.LittleEndian.Uint32(*b)
*b = (*b)[4:]
return v, true
}
func (b *Bytes) Uint32be() (uint32, bool) {
if len(*b) < 4 {
return 0, false
}
v := binary.BigEndian.Uint32(*b)
*b = (*b)[4:]
return v, true
}
type Flags int
const (
@@ -205,10 +203,8 @@ func (b Bytes) Match(p []byte, flags Flags) int {
if l == 0 {
return -1
}
// If no flags, or scanning for full word at the end of pattern then
// do a fast HasPrefix check.
// For other flags it's not possible to use HasPrefix.
if flags == 0 || flags&FullWord > 0 {
// Some cases we can handle with a simple bytes.HasPrefix.
if flags == 0 || flags == FullWord {
if bytes.HasPrefix(b, p) {
b = b[len(p):]
p = p[len(p):]
@@ -232,7 +228,7 @@ func (b Bytes) Match(p []byte, flags Flags) int {
return -1
}
b = b[1:]
if !ByteIsWS(p[0]) {
if len(p) > 0 && !ByteIsWS(p[0]) {
b.TrimLWS()
}
} else {
+15 -5
View File
@@ -23,6 +23,14 @@ type MIME struct {
}
// String returns the string representation of the MIME type, e.g., "application/zip".
// String return values can change between releases, for example, when [IANA]
// assigns a new media type. Use [MIME.Is] to avoid breaking changes.
//
// mtype := mimetype.Detect(zipFile)
// if mtype.String() == "application/zip" { /* Plain string comparison is brittle. */ }
// if mtype.Is("application/zip") { /* Will continue to work between releases */ }
//
// [IANA]: https://www.iana.org/assignments/media-types/media-types.xhtml
func (m *MIME) String() string {
return m.mime
}
@@ -38,17 +46,19 @@ func (m *MIME) Extension() string {
// Each MIME type has a non-nil parent, except for the root MIME type.
//
// For example, the application/json and text/html MIME types have text/plain as
// their parent because they are text files who happen to contain JSON or HTML.
// their parent because they are text files that happen to contain JSON or HTML.
// Another example is the ZIP format, which is used as container
// for Microsoft Office files, EPUB files, JAR files, and others.
func (m *MIME) Parent() *MIME {
return m.parent
}
// Is checks whether this MIME type, or any of its aliases, is equal to the
// Is checks whether this MIME type, or any of its [aliases], is equal to the
// expected MIME type. MIME type equality test is done on the "type/subtype"
// section, ignores any optional MIME parameters, ignores any leading and
// trailing whitespace, and is case insensitive.
//
// [aliases]: https://github.com/gabriel-vasile/mimetype/blob/master/supported_mimes.md
func (m *MIME) Is(expectedMIME string) bool {
// Parsing is needed because some detected MIME types contain parameters
// that need to be stripped for the comparison.
@@ -129,7 +139,7 @@ func (m *MIME) flatten() []*MIME {
// hierarchy returns an easy to read list of ancestors for m.
// For example, application/json would return json>txt>root.
func (m *MIME) hierarchy() string {
h := ""
var h strings.Builder
for m := m; m != nil; m = m.Parent() {
e := strings.TrimPrefix(m.Extension(), ".")
if e == "" {
@@ -142,9 +152,9 @@ func (m *MIME) hierarchy() string {
e = "root"
}
}
h += ">" + e
h.WriteString(">" + e)
}
return strings.TrimPrefix(h, ">")
return strings.TrimPrefix(h.String(), ">")
}
// clone creates a new MIME with the provided optional MIME parameters.
+6 -6
View File
@@ -1,6 +1,6 @@
// Package mimetype uses magic number signatures to detect the MIME type of a file.
//
// File formats are stored in a hierarchy with application/octet-stream at its root.
// File formats are stored in a hierarchy with "application/octet-stream" at its root.
// For example, the hierarchy for HTML format is application/octet-stream ->
// text/plain -> text/html.
package mimetype
@@ -12,14 +12,14 @@ import (
"sync/atomic"
)
const defaultLimit uint32 = 3072
const defaultLimit uint32 = 4096
// readLimit is the maximum number of bytes from the input used when detecting.
var readLimit uint32 = defaultLimit
// Detect returns the MIME type found from the provided byte slice.
//
// The result is always a valid MIME type, with application/octet-stream
// The result is always a valid MIME type, with "application/octet-stream"
// returned when identification failed.
func Detect(in []byte) *MIME {
// Using atomic because readLimit can be written at the same time in other goroutine.
@@ -34,7 +34,7 @@ func Detect(in []byte) *MIME {
// DetectReader returns the MIME type of the provided reader.
//
// The result is always a valid MIME type, with application/octet-stream
// The result is always a valid MIME type, with "application/octet-stream"
// returned when identification failed with or without an error.
// Any error returned is related to the reading from the input reader.
//
@@ -72,7 +72,7 @@ func DetectReader(r io.Reader) (*MIME, error) {
// DetectFile returns the MIME type of the provided file.
//
// The result is always a valid MIME type, with application/octet-stream
// The result is always a valid MIME type, with "application/octet-stream"
// returned when identification failed with or without an error.
// Any error returned is related to the opening and reading from the input file.
func DetectFile(path string) (*MIME, error) {
@@ -112,7 +112,7 @@ func SetLimit(limit uint32) {
}
// Extend adds detection for other file formats.
// It is equivalent to calling Extend() on the root MIME type "application/octet-stream".
// It is equivalent to calling [MIME.Extend] on the root MIME type "application/octet-stream".
func Extend(detector func(raw []byte, limit uint32) bool, mime, extension string, aliases ...string) {
root.Extend(detector, mime, extension, aliases...)
}
+10 -5
View File
@@ -1,4 +1,4 @@
## 199 Supported MIME types
## 204 Supported MIME types
This file is automatically generated when running tests. Do not edit manually.
Extension | MIME type <br> Aliases | Hierarchy
@@ -42,7 +42,7 @@ Extension | MIME type <br> Aliases | Hierarchy
**.oga** | **audio/ogg** | oga>ogg>root
**.ogv** | **video/ogg** | ogv>ogg>root
**.png** | **image/png** | png>root
**.png** | **image/vnd.mozilla.apng** | png>png>root
**.apng** | **image/apng** <br> image/vnd.mozilla.apng | apng>png>root
**.jpg** | **image/jpeg** | jpg>root
**.jxl** | **image/jxl** | jxl>root
**.jp2** | **image/jp2** | jp2>root
@@ -67,7 +67,6 @@ Extension | MIME type <br> Aliases | Hierarchy
**.bmp** | **image/bmp** <br> image/x-bmp, image/x-ms-bmp | bmp>root
**.123** | **application/vnd.lotus-1-2-3** | 123>root
**.ico** | **image/x-icon** | ico>root
**.mp3** | **audio/mpeg** <br> audio/x-mpeg, audio/mp3 | mp3>root
**.flac** | **audio/flac** | flac>root
**.midi** | **audio/midi** <br> audio/mid, audio/sp-midi, audio/x-mid, audio/x-midi | midi>root
**.ape** | **audio/ape** | ape>root
@@ -95,7 +94,7 @@ Extension | MIME type <br> Aliases | Hierarchy
**.webm** | **video/webm** <br> audio/webm | webm>root
**.avi** | **video/x-msvideo** <br> video/avi, video/msvideo | avi>root
**.flv** | **video/x-flv** | flv>root
**.mkv** | **video/x-matroska** | mkv>root
**.mkv** | **video/matroska** <br> video/x-matroska | mkv>root
**.asf** | **video/x-ms-asf** <br> video/asf, video/x-ms-wmv | asf>root
**.aac** | **audio/aac** | aac>root
**.voc** | **audio/x-unknown** | voc>root
@@ -116,7 +115,7 @@ Extension | MIME type <br> Aliases | Hierarchy
**.shp** | **application/vnd.shp** | shp>shx>root
**.dbf** | **application/x-dbf** | dbf>root
**.dcm** | **application/dicom** | dcm>root
**.rar** | **application/x-rar-compressed** <br> application/x-rar | rar>root
**.rar** | **application/vnd.rar** <br> application/x-rar-compressed, application/x-rar | rar>root
**.djvu** | **image/vnd.djvu** | djvu>root
**.mobi** | **application/x-mobipocket-ebook** | mobi>root
**.lit** | **application/x-ms-reader** | lit>root
@@ -158,6 +157,9 @@ Extension | MIME type <br> Aliases | Hierarchy
**.hlp** | **application/x-os2-hlp** | hlp>root
**.fm** | **application/vnd.framemaker** | fm>root
**.bufr** | **application/bufr** | bufr>root
**.pyc** | **application/x-bytecode.python** | pyc>root
**.pcap** | **application/vnd.tcpdump.pcap** | pcap>root
**.mp3** | **audio/mpeg** <br> audio/x-mpeg, audio/mp3 | mp3>root
**.txt** | **text/plain** | txt>root
**.svg** | **image/svg+xml** | svg>txt>root
**.html** | **text/html** | html>txt>root
@@ -176,6 +178,7 @@ Extension | MIME type <br> Aliases | Hierarchy
**.xfdf** | **application/vnd.adobe.xfdf** | xfdf>xml>txt>root
**.owl** | **application/owl+xml** | owl>xml>txt>root
**.html** | **application/xhtml+xml** | html>xml>txt>root
**.xml** | **application/vnd.cyclonedx+xml** | xml>xml>txt>root
**.php** | **text/x-php** | php>txt>root
**.js** | **text/javascript** <br> application/x-javascript, application/javascript | js>txt>root
**.lua** | **text/x-lua** | lua>txt>root
@@ -186,6 +189,7 @@ Extension | MIME type <br> Aliases | Hierarchy
**.geojson** | **application/geo+json** | geojson>json>txt>root
**.har** | **application/json** | har>json>txt>root
**.gltf** | **model/gltf+json** | gltf>json>txt>root
**.json** | **application/vnd.cyclonedx+json** | json>json>txt>root
**.ndjson** | **application/x-ndjson** | ndjson>txt>root
**.rtf** | **text/rtf** <br> application/rtf | rtf>txt>root
**.srt** | **application/x-subrip** <br> application/x-srt, text/x-srt | srt>txt>root
@@ -202,3 +206,4 @@ Extension | MIME type <br> Aliases | Hierarchy
**.ppm** | **image/x-portable-pixmap** | ppm>txt>root
**.pam** | **image/x-portable-arbitrarymap** | pam>txt>root
**.eml** | **message/rfc822** | eml>txt>root
**.ged** | **text/vnd.familysearch.gedcom** | ged>txt>root
+26 -15
View File
@@ -19,12 +19,16 @@ var root = newMIME("application/octet-stream", "",
func([]byte, uint32) bool { return true },
xpm, sevenZ, zip, pdf, fdf, ole, ps, psd, p7s, ogg, png, jpg, jxl, jp2, jpx,
jpm, jxs, gif, webp, exe, elf, ar, tar, xar, bz2, fits, tiff, bmp, lotus, ico,
mp3, flac, midi, ape, musePack, amr, wav, aiff, au, mpeg, quickTime, mp4, webM,
flac, midi, ape, musePack, amr, wav, aiff, au, mpeg, quickTime, mp4, webM,
avi, flv, mkv, asf, aac, voc, m3u, rmvb, gzip, class, swf, crx, ttf, woff,
woff2, otf, ttc, eot, wasm, shx, dbf, dcm, rar, djvu, mobi, lit, bpg, cbor,
sqlite3, dwg, nes, lnk, macho, qcp, icns, hdr, mrc, mdb, accdb, zstd, cab,
rpm, xz, lzip, torrent, cpio, tzif, xcf, pat, gbr, glb, cabIS, jxr, parquet,
oneNote, chm, wpd, dxf, grib, zlib, inf, hlp, fm, bufr,
oneNote, chm, wpd, dxf, grib, zlib, inf, hlp, fm, bufr, pyc, pcap,
// MP3 is late because it does a linear search in the input. That means
// containers that embed an MP3, for example: an mp4 file, or a zip without
// compression, would pass as MP3s.
mp3,
// Keep text last because it is the slowest check.
text,
)
@@ -82,16 +86,17 @@ var (
alias("application/x-ogg")
oggAudio = newMIME("audio/ogg", ".oga", magic.OggAudio)
oggVideo = newMIME("video/ogg", ".ogv", magic.OggVideo)
text = newMIME("text/plain", ".txt", magic.Text, svg, html, xml, php, js, lua, perl, python, ruby, json, ndJSON, rtf, srt, tcl, csv, tsv, vCard, iCalendar, warc, vtt, shell, netpbm, netpgm, netppm, netpam, rfc822)
xml = newMIME("text/xml", ".xml", magic.XML, rss, atom, x3d, kml, xliff, collada, gml, gpx, tcx, amf, threemf, xfdf, owl2, xhtml).
text = newMIME("text/plain", ".txt", magic.Text, svg, html, xml, php, js, lua, perl, python, ruby, json, ndJSON, rtf, srt, tcl, csv, tsv, vCard, iCalendar, warc, vtt, shell, netpbm, netpgm, netppm, netpam, rfc822, gedcom)
xml = newMIME("text/xml", ".xml", magic.XML, rss, atom, x3d, kml, xliff, collada, gml, gpx, tcx, amf, threemf, xfdf, owl2, xhtml, cdxxml).
alias("application/xml")
xhtml = newMIME("application/xhtml+xml", ".html", magic.XHTML)
json = newMIME("application/json", ".json", magic.JSON, geoJSON, har, gltf)
json = newMIME("application/json", ".json", magic.JSON, geoJSON, har, gltf, cdxJSON)
har = newMIME("application/json", ".har", magic.HAR)
csv = newMIME("text/csv", ".csv", magic.CSV)
tsv = newMIME("text/tab-separated-values", ".tsv", magic.TSV)
geoJSON = newMIME("application/geo+json", ".geojson", magic.GeoJSON)
ndJSON = newMIME("application/x-ndjson", ".ndjson", magic.NdJSON)
cdxJSON = newMIME("application/vnd.cyclonedx+json", ".json", magic.CDXJSON)
html = newMIME("text/html", ".html", magic.HTML)
php = newMIME("text/x-php", ".php", magic.Php)
rtf = newMIME("text/rtf", ".rtf", magic.Rtf).alias("application/rtf")
@@ -104,6 +109,7 @@ var (
perl = newMIME("text/x-perl", ".pl", magic.Perl)
python = newMIME("text/x-python", ".py", magic.Python).
alias("text/x-script.python", "application/x-python")
pyc = newMIME("application/x-bytecode.python", ".pyc", magic.Pyc)
ruby = newMIME("text/x-ruby", ".rb", magic.Ruby).
alias("application/x-ruby")
shell = newMIME("text/x-shellscript", ".sh", magic.Shell).
@@ -127,13 +133,15 @@ var (
tcx = newMIME("application/vnd.garmin.tcx+xml", ".tcx", magic.Tcx)
amf = newMIME("application/x-amf", ".amf", magic.Amf)
threemf = newMIME("application/vnd.ms-package.3dmanufacturing-3dmodel+xml", ".3mf", magic.Threemf)
cdxxml = newMIME("application/vnd.cyclonedx+xml", ".xml", magic.CDXXML)
png = newMIME("image/png", ".png", magic.Png, apng)
apng = newMIME("image/vnd.mozilla.apng", ".png", magic.Apng)
jpg = newMIME("image/jpeg", ".jpg", magic.Jpg)
jxl = newMIME("image/jxl", ".jxl", magic.Jxl)
jp2 = newMIME("image/jp2", ".jp2", magic.Jp2)
jpx = newMIME("image/jpx", ".jpf", magic.Jpx)
jpm = newMIME("image/jpm", ".jpm", magic.Jpm).
apng = newMIME("image/apng", ".apng", magic.Apng).
alias("image/vnd.mozilla.apng")
jpg = newMIME("image/jpeg", ".jpg", magic.Jpg)
jxl = newMIME("image/jxl", ".jxl", magic.Jxl)
jp2 = newMIME("image/jp2", ".jp2", magic.Jp2)
jpx = newMIME("image/jpx", ".jpf", magic.Jpx)
jpm = newMIME("image/jpm", ".jpm", magic.Jpm).
alias("video/jpm")
jxs = newMIME("image/jxs", ".jxs", magic.Jxs)
xpm = newMIME("image/x-xpixmap", ".xpm", magic.Xpm)
@@ -156,7 +164,7 @@ var (
heifSeq = newMIME("image/heif-sequence", ".heif", magic.HeifSequence)
hdr = newMIME("image/vnd.radiance", ".hdr", magic.Hdr)
avif = newMIME("image/avif", ".avif", magic.AVIF)
mp3 = newMIME("audio/mpeg", ".mp3", magic.Mp3).
mp3 = newMIME("audio/mpeg", ".mp3", magic.MP3).
alias("audio/x-mpeg", "audio/mp3")
flac = newMIME("audio/flac", ".flac", magic.Flac)
midi = newMIME("audio/midi", ".midi", magic.Midi).
@@ -192,7 +200,8 @@ var (
avi = newMIME("video/x-msvideo", ".avi", magic.Avi).
alias("video/avi", "video/msvideo")
flv = newMIME("video/x-flv", ".flv", magic.Flv)
mkv = newMIME("video/x-matroska", ".mkv", magic.Mkv)
mkv = newMIME("video/matroska", ".mkv", magic.Mkv).
alias("video/x-matroska")
asf = newMIME("video/x-ms-asf", ".asf", magic.Asf).
alias("video/asf", "video/x-ms-wmv")
rmvb = newMIME("application/vnd.rn-realmedia-vbr", ".rmvb", magic.Rmvb)
@@ -242,8 +251,8 @@ var (
odc = newMIME("application/vnd.oasis.opendocument.chart", ".odc", magic.Odc).
alias("application/x-vnd.oasis.opendocument.chart")
sxc = newMIME("application/vnd.sun.xml.calc", ".sxc", magic.Sxc)
rar = newMIME("application/x-rar-compressed", ".rar", magic.RAR).
alias("application/x-rar")
rar = newMIME("application/vnd.rar", ".rar", magic.RAR).
alias("application/x-rar-compressed", "application/x-rar")
djvu = newMIME("image/vnd.djvu", ".djvu", magic.DjVu)
mobi = newMIME("application/x-mobipocket-ebook", ".mobi", magic.Mobi)
lit = newMIME("application/x-ms-reader", ".lit", magic.Lit)
@@ -294,4 +303,6 @@ var (
hlp = newMIME("application/x-os2-hlp", ".hlp", magic.Hlp)
fm = newMIME("application/vnd.framemaker", ".fm", magic.FrameMaker)
bufr = newMIME("application/bufr", ".bufr", magic.BUFR)
gedcom = newMIME("text/vnd.familysearch.gedcom", ".ged", magic.GEDCOM)
pcap = newMIME("application/vnd.tcpdump.pcap", ".pcap", magic.Pcap)
)
-1
View File
@@ -1,5 +1,4 @@
//go:build !go1.21
// +build !go1.21
/*
Copyright 2019 The logr Authors.
-1
View File
@@ -1,5 +1,4 @@
//go:build go1.21
// +build go1.21
/*
Copyright 2019 The logr Authors.
+36 -11
View File
@@ -426,7 +426,7 @@ func (f Formatter) colon() byte {
}
func (f Formatter) pretty(value any) string {
return f.prettyWithFlags(value, 0, 0)
return f.prettyWithFlags(value, 0, 0, 0, nil)
}
const (
@@ -434,7 +434,13 @@ const (
)
// TODO: This is not fast. Most of the overhead goes here.
func (f Formatter) prettyWithFlags(value any, flags uint32, depth int) string {
// value: The value to render
// flags: Bitmask of flags (see above)
// depth: The current depth of nested structs, slices, arrays, and maps
// ptrDepth: The current depth of including pointer dereferences
// ptrMap: A map of pointers already seen, to avoid infinite recursion (usually
// nil unless ptrDepth is large)
func (f Formatter) prettyWithFlags(value any, flags uint32, depth int, ptrDepth int, ptrMap map[uintptr]bool) string {
if depth > f.opts.MaxLogDepth {
return `"<max-log-depth-exceeded>"`
}
@@ -504,7 +510,7 @@ func (f Formatter) prettyWithFlags(value any, flags uint32, depth int) string {
// arbitrary keys might need escaping
buf.WriteString(prettyString(k))
buf.WriteByte(f.colon())
buf.WriteString(f.prettyWithFlags(v[i+1], 0, depth+1))
buf.WriteString(f.prettyWithFlags(v[i+1], 0, depth+1, ptrDepth+1, ptrMap))
}
if flags&flagRawStruct == 0 {
buf.WriteByte('}')
@@ -576,7 +582,7 @@ func (f Formatter) prettyWithFlags(value any, flags uint32, depth int) string {
}
printComma = true // if we got here, we are rendering a field
if fld.Anonymous && fld.Type.Kind() == reflect.Struct && name == "" {
buf.WriteString(f.prettyWithFlags(v.Field(i).Interface(), flags|flagRawStruct, depth+1))
buf.WriteString(f.prettyWithFlags(v.Field(i).Interface(), flags|flagRawStruct, depth+1, ptrDepth+1, ptrMap))
continue
}
if name == "" {
@@ -585,7 +591,7 @@ func (f Formatter) prettyWithFlags(value any, flags uint32, depth int) string {
// field names can't contain characters which need escaping
buf.WriteString(f.quoted(name, false))
buf.WriteByte(f.colon())
buf.WriteString(f.prettyWithFlags(v.Field(i).Interface(), 0, depth+1))
buf.WriteString(f.prettyWithFlags(v.Field(i).Interface(), 0, depth+1, ptrDepth+1, ptrMap))
}
if flags&flagRawStruct == 0 {
buf.WriteByte('}')
@@ -612,7 +618,7 @@ func (f Formatter) prettyWithFlags(value any, flags uint32, depth int) string {
buf.WriteByte(f.comma())
}
e := v.Index(i)
buf.WriteString(f.prettyWithFlags(e.Interface(), 0, depth+1))
buf.WriteString(f.prettyWithFlags(e.Interface(), 0, depth+1, ptrDepth+1, ptrMap))
}
buf.WriteByte(']')
return buf.String()
@@ -637,7 +643,8 @@ func (f Formatter) prettyWithFlags(value any, flags uint32, depth int) string {
keystr = prettyString(keystr)
} else {
// prettyWithFlags will produce already-escaped values
keystr = f.prettyWithFlags(it.Key().Interface(), 0, depth+1)
// key depth is unrelated to overall depth
keystr = f.prettyWithFlags(it.Key().Interface(), 0, 0, ptrDepth, ptrMap)
if t.Key().Kind() != reflect.String {
// JSON only does string keys. Unlike Go's standard JSON, we'll
// convert just about anything to a string.
@@ -646,16 +653,34 @@ func (f Formatter) prettyWithFlags(value any, flags uint32, depth int) string {
}
buf.WriteString(keystr)
buf.WriteByte(f.colon())
buf.WriteString(f.prettyWithFlags(it.Value().Interface(), 0, depth+1))
buf.WriteString(f.prettyWithFlags(it.Value().Interface(), 0, depth+1, ptrDepth+1, ptrMap))
i++
}
buf.WriteByte('}')
return buf.String()
case reflect.Ptr, reflect.Interface:
case reflect.Pointer, reflect.Interface:
if v.IsNil() {
return "null"
}
return f.prettyWithFlags(v.Elem().Interface(), 0, depth)
// Special case: recursive pointers. For normal use we do not want to
// count pointer dereferences as depth, but if we see the same pointer
// again we have a recursion and need to stop. After a large number of
// pointer dereferences we will start tracking pointers to avoid the
// perf hit of doing it in the normal path.
//
// This should not happen accidentally (e.g. json decoding should never
// do this) but we can handle it gracefully.
if ptrMap != nil && ptrMap[uintptr(v.Pointer())] {
depth = f.opts.MaxLogDepth + 1 // force a depth error
}
const maxDepthFactor = 4 // arbitrary, but we want it large enough to not false-alert
if ptrDepth > f.opts.MaxLogDepth*maxDepthFactor && ptrMap == nil {
ptrMap = map[uintptr]bool{}
}
if ptrMap != nil {
ptrMap[(uintptr)(v.Pointer())] = true
}
return f.prettyWithFlags(v.Elem().Interface(), 0, depth, ptrDepth+1, ptrMap)
}
return fmt.Sprintf(`"<unhandled-%s>"`, t.Kind().String())
}
@@ -697,7 +722,7 @@ func isEmpty(v reflect.Value) bool {
return v.Float() == 0
case reflect.Complex64, reflect.Complex128:
return v.Complex() == 0
case reflect.Interface, reflect.Ptr:
case reflect.Interface, reflect.Pointer:
return v.IsNil()
}
return false
+16 -6
View File
@@ -1,5 +1,4 @@
//go:build go1.21
// +build go1.21
/*
Copyright 2023 The logr Authors.
@@ -33,7 +32,7 @@ const extraSlogSinkDepth = 3 // 2 for slog, 1 for SlogSink
func (l fnlogger) Handle(_ context.Context, record slog.Record) error {
kvList := make([]any, 0, 2*record.NumAttrs())
record.Attrs(func(attr slog.Attr) bool {
kvList = attrToKVs(attr, kvList)
kvList = attrToKVs(attr, kvList, l.opts.MaxLogDepth)
return true
})
@@ -49,7 +48,7 @@ func (l fnlogger) Handle(_ context.Context, record slog.Record) error {
func (l fnlogger) WithAttrs(attrs []slog.Attr) logr.SlogSink {
kvList := make([]any, 0, 2*len(attrs))
for _, attr := range attrs {
kvList = attrToKVs(attr, kvList)
kvList = attrToKVs(attr, kvList, l.opts.MaxLogDepth)
}
l.AddValues(kvList)
return &l
@@ -61,14 +60,25 @@ func (l fnlogger) WithGroup(name string) logr.SlogSink {
}
// attrToKVs appends a slog.Attr to a logr-style kvList. It handle slog Groups
// and other details of slog.
func attrToKVs(attr slog.Attr, kvList []any) []any {
// and other details of slog. maxDepth bounds recursion into nested groups so a
// deeply-nested slog.Group cannot exhaust the stack; it is decremented per group
// level and starts at the Formatter's MaxLogDepth (past which the formatter would
// truncate the rendering anyway).
func attrToKVs(attr slog.Attr, kvList []any, maxDepth int) []any {
attrVal := attr.Value.Resolve()
if attrVal.Kind() == slog.KindGroup {
if maxDepth <= 0 {
// Nesting is too deep to build without risking a stack overflow.
// Stop here; the formatter truncates below MaxLogDepth regardless.
if attr.Key != "" {
kvList = append(kvList, attr.Key, "<max-log-depth-exceeded>")
}
return kvList
}
groupVal := attrVal.Group()
grpKVs := make([]any, 0, 2*len(groupVal))
for _, attr := range groupVal {
grpKVs = attrToKVs(attr, grpKVs)
grpKVs = attrToKVs(attr, grpKVs, maxDepth-1)
}
if attr.Key == "" {
// slog says we have to inline these
-1
View File
@@ -1,5 +1,4 @@
//go:build go1.21
// +build go1.21
/*
Copyright 2023 The logr Authors.
-1
View File
@@ -1,5 +1,4 @@
//go:build go1.21
// +build go1.21
/*
Copyright 2023 The logr Authors.
-1
View File
@@ -1,5 +1,4 @@
//go:build go1.21
// +build go1.21
/*
Copyright 2023 The logr Authors.
+12
View File
@@ -27,6 +27,18 @@ Use the links above for more information on each.
# changelog
* Jul 1st, 2026 [1.19.0](https://github.com/klauspost/compress/releases/tag/v1.19.0)
* zstd: Add true concurrent stream encodingin https://github.com/klauspost/compress/pull/1136
* zstd: arm64 decoder asm by @lizthegrey in https://github.com/klauspost/compress/pull/1160
* flate: Add inflate checkpoints in https://github.com/klauspost/compress/pull/1154
* zstd: avoid unused BuildDict encoder allocation by @snissn in https://github.com/klauspost/compress/pull/1147
* snappy/s2: Limit length of varint in `decodedLen` by @eustas in https://github.com/klauspost/compress/pull/1148
* gzhttp: match qvalue parameter case-insensitively (RFC 7231) by @z9z in https://github.com/klauspost/compress/pull/1149
* zip: add NameDecoder callback for legacy encoding rewrite by @SAY-5 in https://github.com/klauspost/compress/pull/1150
* huff0: Allow building tables from histogram in https://github.com/klauspost/compress/pull/1155
* huff0: Allow building table from oversized histogram in https://github.com/klauspost/compress/pull/1156
* s2sx: Clean symlink targets in https://github.com/klauspost/compress/pull/1163
* Feb 9th, 2026 [1.18.4](https://github.com/klauspost/compress/releases/tag/v1.18.4)
* gzhttp: Add zstandard to server handler wrapper https://github.com/klauspost/compress/pull/1121
* zstd: Add ResetWithOptions to encoder/decoder https://github.com/klauspost/compress/pull/1122
+21 -3
View File
@@ -28,9 +28,10 @@ type dictDecoder struct {
hist []byte // Sliding window history
// Invariant: 0 <= rdPos <= wrPos <= len(hist)
wrPos int // Current output position in buffer
rdPos int // Have emitted hist[:rdPos] already
full bool // Has a full window length been written yet?
wrPos int // Current output position in buffer
rdPos int // Have emitted hist[:rdPos] already
flushed int64 // Total bytes returned by readFlush since init
full bool // Has a full window length been written yet?
}
// init initializes dictDecoder to have a sliding window dictionary of the given
@@ -167,11 +168,22 @@ loop:
return dstPos - dstBase
}
// appendWindow appends the current sliding window (up to len(hist) most recent
// bytes, oldest first) to dst.
func (dd *dictDecoder) appendWindow(dst []byte) []byte {
if dd.full {
dst = append(dst, dd.hist[dd.wrPos:]...)
return append(dst, dd.hist[:dd.wrPos]...)
}
return append(dst, dd.hist[:dd.wrPos]...)
}
// readFlush returns a slice of the historical buffer that is ready to be
// emitted to the user. The data returned by readFlush must be fully consumed
// before calling any other dictDecoder methods.
func (dd *dictDecoder) readFlush() []byte {
toRead := dd.hist[dd.rdPos:dd.wrPos]
dd.flushed += int64(len(toRead))
dd.rdPos = dd.wrPos
if dd.wrPos == len(dd.hist) {
dd.wrPos, dd.rdPos = 0, 0
@@ -179,3 +191,9 @@ func (dd *dictDecoder) readFlush() []byte {
}
return toRead
}
// decoded reports the total number of bytes written into the dictionary since
// init (i.e. excluding any preset dict bytes).
func (dd *dictDecoder) decoded() int64 {
return dd.flushed + int64(dd.wrPos-dd.rdPos)
}
+92
View File
@@ -342,6 +342,11 @@ type decompressor struct {
final bool
flushMode flushMode
cb func(InflateCheckpoint)
cp InflateCheckpoint
hasCP bool // WithResumeFrom was supplied
uncOffset int64 // baseline uncompressed offset (from a resume checkpoint)
cpBuf []byte
}
func (f *decompressor) nextBlock() {
@@ -676,6 +681,18 @@ func (f *decompressor) finishBlock() {
f.toRead = f.dict.readFlush()
}
if f.cb != nil {
bitPos := f.roffset*8 - int64(f.nb)
f.cpBuf = f.dict.appendWindow(f.cpBuf[:0])
f.cb(InflateCheckpoint{
UncompressedOffset: f.uncOffset + f.dict.decoded(),
CompressedOffset: bitPos / 8,
Final: f.final,
BitOffset: uint8(bitPos & 7),
Window: f.cpBuf,
})
}
f.step = nextBlock
}
@@ -806,6 +823,45 @@ func (f *decompressor) Reset(r io.Reader, dict []byte) error {
return nil
}
// ResetCP will adjust the input to the provided checkpoint.
// It is assumed the input stream is forwarded to cp.CompressedOffset.
func (f *decompressor) ResetCP(r io.Reader, cp InflateCheckpoint) error {
*f = decompressor{
r: makeReader(r),
bits: f.bits,
codebits: f.codebits,
h1: f.h1,
h2: f.h2,
dict: f.dict,
step: nextBlock,
cpBuf: f.cpBuf,
}
return f.applyCP(cp)
}
// applyCP seeds the decompressor state from a resume checkpoint:
// loads the sliding window, sets the absolute compressed/uncompressed
// offsets, and skips cp.BitOffset bits into the first input byte so
// the next decode aligns with the start of a deflate block.
func (f *decompressor) applyCP(cp InflateCheckpoint) error {
f.dict.init(maxMatchOffset, cp.Window)
f.roffset = cp.CompressedOffset
f.uncOffset = cp.UncompressedOffset
f.final = cp.Final
f.b = 0
f.nb = 0
if cp.BitOffset > 0 {
c, err := f.r.ReadByte()
if err != nil {
return noEOF(err)
}
f.roffset++
f.b = uint32(c) >> cp.BitOffset
f.nb = 8 - uint(cp.BitOffset)
}
return nil
}
type ReaderOpt func(*decompressor)
// WithPartialBlock tells decompressor to return after each block,
@@ -823,6 +879,36 @@ func WithDict(dict []byte) ReaderOpt {
}
}
// InflateCheckpoint provides a resumable checkpoint for inflate.
type InflateCheckpoint struct {
UncompressedOffset int64 // Byte offset in the decompressed stream
CompressedOffset int64 // Byte offset in the compressed stream
Final bool // True if this is the final block
BitOffset uint8 // 0-7 bits
Window []byte // 32KB sliding window dictionary
}
// WithEobCallback will call the provided function after each block
// with the current gzip checkpoint.
// After returning the provided window can no longer be referenced.
// The callback will not be triggered after a block is marked "final".
// The callback is not retained after Reset.
func WithEobCallback(cb func(InflateCheckpoint)) ReaderOpt {
return func(f *decompressor) {
f.cb = cb
}
}
// WithResumeFrom will adjust the input to the provided checkpoint.
// It is assumed the input stream is forwarded to the provided offset.
// The checkpoint is removed when Reset is called.
func WithResumeFrom(cp InflateCheckpoint) ReaderOpt {
return func(f *decompressor) {
f.cp = cp
f.hasCP = true
}
}
// NewReaderOpts returns new reader with provided options
func NewReaderOpts(r io.Reader, opts ...ReaderOpt) io.ReadCloser {
fixedHuffmanDecoderInit()
@@ -838,6 +924,12 @@ func NewReaderOpts(r io.Reader, opts ...ReaderOpt) io.ReadCloser {
opt(&f)
}
if f.hasCP {
if err := f.applyCP(f.cp); err != nil {
f.err = err
}
}
return &f
}
+85 -31
View File
@@ -10,6 +10,15 @@ import (
"strings"
)
func peekBufio(fr *bufio.Reader) ([]byte, error) {
if fr.Buffered() == 0 {
if _, err := fr.Peek(1); err != nil && fr.Buffered() == 0 {
return nil, err
}
}
return fr.Peek(fr.Buffered())
}
// Decode a single Huffman block from f.
// hl and hd are the Huffman states for the lit/length values
// and the distance values, respectively. If hd == nil, using the
@@ -527,6 +536,8 @@ func (f *decompressor) huffmanBufioReader() {
// but is smart enough to keep local variables in registers, so use nb and b,
// inline call to moreBits and reassign b,nb back to f on return.
fnb, fb, dict := f.nb, f.b, &f.dict
pbuf, _ := fr.Peek(fr.Buffered())
pos := 0
switch f.stepState {
case stateInit:
@@ -548,12 +559,19 @@ readLiteral:
n := uint(f.hl.maxRead)
for {
for fnb < n {
c, err := fr.ReadByte()
if err != nil {
f.b, f.nb = fb, fnb
f.err = noEOF(err)
return
if pos >= len(pbuf) {
fr.Discard(pos)
var err error
pbuf, err = peekBufio(fr)
pos = 0
if len(pbuf) == 0 {
f.b, f.nb = fb, fnb
f.err = noEOF(err)
return
}
}
c := pbuf[pos]
pos++
f.roffset++
fb |= uint32(c) << (fnb & regSizeMaskUint32)
fnb += 8
@@ -566,6 +584,7 @@ readLiteral:
}
if n <= fnb {
if n == 0 {
fr.Discard(pos)
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("huffsym: n==0")
@@ -586,6 +605,7 @@ readLiteral:
case v < 256:
dict.writeByte(byte(v))
if dict.availWrite() == 0 {
fr.Discard(pos)
f.toRead = dict.readFlush()
f.step = huffmanBufioReader
f.stepState = stateInit
@@ -594,6 +614,7 @@ readLiteral:
}
goto readLiteral
case v == 256:
fr.Discard(pos)
f.b, f.nb = fb, fnb
f.finishBlock()
return
@@ -605,15 +626,22 @@ readLiteral:
length = int(val.length) + 3
n := uint(val.extra)
for fnb < n {
c, err := fr.ReadByte()
if err != nil {
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("morebits n>0:", err)
if pos >= len(pbuf) {
fr.Discard(pos)
var err error
pbuf, err = peekBufio(fr)
pos = 0
if len(pbuf) == 0 {
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("morebits n>0:", err)
}
f.err = err
return
}
f.err = err
return
}
c := pbuf[pos]
pos++
f.roffset++
fb |= uint32(c) << (fnb & regSizeMaskUint32)
fnb += 8
@@ -622,6 +650,7 @@ readLiteral:
fb >>= n & regSizeMaskUint32
fnb -= n
default:
fr.Discard(pos)
if debugDecode {
fmt.Println(v, ">= maxNumLit")
}
@@ -633,15 +662,22 @@ readLiteral:
var dist uint32
if f.hd == nil {
for fnb < 5 {
c, err := fr.ReadByte()
if err != nil {
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("morebits f.nb<5:", err)
if pos >= len(pbuf) {
fr.Discard(pos)
var err error
pbuf, err = peekBufio(fr)
pos = 0
if len(pbuf) == 0 {
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("morebits f.nb<5:", err)
}
f.err = err
return
}
f.err = err
return
}
c := pbuf[pos]
pos++
f.roffset++
fb |= uint32(c) << (fnb & regSizeMaskUint32)
fnb += 8
@@ -660,12 +696,19 @@ readLiteral:
// inline call to moreBits and reassign b,nb back to f on return.
for {
for fnb < n {
c, err := fr.ReadByte()
if err != nil {
f.b, f.nb = fb, fnb
f.err = noEOF(err)
return
if pos >= len(pbuf) {
fr.Discard(pos)
var err error
pbuf, err = peekBufio(fr)
pos = 0
if len(pbuf) == 0 {
f.b, f.nb = fb, fnb
f.err = noEOF(err)
return
}
}
c := pbuf[pos]
pos++
f.roffset++
fb |= uint32(c) << (fnb & regSizeMaskUint32)
fnb += 8
@@ -678,6 +721,7 @@ readLiteral:
}
if n <= fnb {
if n == 0 {
fr.Discard(pos)
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("huffsym: n==0")
@@ -701,15 +745,22 @@ readLiteral:
// have 1 bit in bottom of dist, need nb more.
extra := (dist & 1) << (nb & regSizeMaskUint32)
for fnb < nb {
c, err := fr.ReadByte()
if err != nil {
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("morebits f.nb<nb:", err)
if pos >= len(pbuf) {
fr.Discard(pos)
var err error
pbuf, err = peekBufio(fr)
pos = 0
if len(pbuf) == 0 {
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("morebits f.nb<nb:", err)
}
f.err = err
return
}
f.err = err
return
}
c := pbuf[pos]
pos++
f.roffset++
fb |= uint32(c) << (fnb & regSizeMaskUint32)
fnb += 8
@@ -720,6 +771,7 @@ readLiteral:
dist = 1<<((nb+1)&regSizeMaskUint32) + 1 + extra
// slower: dist = bitMask32[nb+1] + 2 + extra
default:
fr.Discard(pos)
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("dist too big:", dist, maxNumDist)
@@ -730,6 +782,7 @@ readLiteral:
// No check on length; encoding can be prescient.
if dist > uint32(dict.histSize()) {
fr.Discard(pos)
f.b, f.nb = fb, fnb
if debugDecode {
fmt.Println("dist > dict.histSize():", dist, dict.histSize())
@@ -752,6 +805,7 @@ copyHistory:
f.copyLen -= cnt
if dict.availWrite() == 0 || f.copyLen > 0 {
fr.Discard(pos)
f.toRead = dict.readFlush()
f.step = huffmanBufioReader // We need to continue this work
f.stepState = stateDict
+168
View File
@@ -0,0 +1,168 @@
package huff0
import "errors"
// BuildCTable builds a Huffman compression table from a precomputed symbol
// histogram and installs it as the previous (reuse) table on s.
//
// After this call:
// - EstimateSize/CanUseTable can probe the table against other histograms.
// - Compress1X/Compress4X with Reuse = ReusePolicyMust will encode without
// emitting a new table header.
// - TransferCTable can hand the table to a sibling Scratch.
//
// count[i] is the number of occurrences of symbol i. The histogram must have
// at least 2 distinct non-zero symbols; ErrUseRLE is returned for a single
// symbol and an error is returned for an empty histogram.
func (s *Scratch) BuildCTable(count *[256]uint32) error {
if s == nil {
return errors.New("huff0: BuildCTable on nil Scratch")
}
if count == nil {
return errors.New("huff0: nil count passed to BuildCTable")
}
var err error
s, err = s.prepare(nil)
if err != nil {
return err
}
s.count = *count
var total, maxCount int
var symLen uint16
for i, v := range s.count {
total += int(v)
if int(v) > maxCount {
maxCount = int(v)
}
if v != 0 {
symLen = uint16(i) + 1
}
}
if total == 0 {
return errors.New("huff0: empty histogram")
}
if symLen < 2 || maxCount == total {
return ErrUseRLE
}
// huff0's internal rank table assumes total ≤ BlockSizeMax (it uses
// highBit32(count+1) + 1 as a rank index into a fixed-size array).
// Histograms summed across multiple blocks can exceed that; scale the
// counts down preserving the distribution. Non-zero entries round up so
// rare symbols stay representable.
if total > BlockSizeMax {
shift := uint(0)
for total>>shift > BlockSizeMax {
shift++
}
round := uint32(1<<shift) - 1
var newTotal, newMax int
for i, v := range s.count {
if v == 0 {
continue
}
scaled := (v + round) >> shift
if scaled == 0 {
scaled = 1
}
s.count[i] = scaled
newTotal += int(scaled)
if int(scaled) > newMax {
newMax = int(scaled)
}
}
total = newTotal
maxCount = newMax
if maxCount == total {
return ErrUseRLE
}
}
s.symbolLen = symLen
s.maxCount = maxCount
s.srcLen = total
if err := s.buildCTable(); err != nil {
return err
}
if cap(s.prevTable) < len(s.cTable) {
s.prevTable = make(cTable, 0, maxSymbolValue+1)
}
s.prevTable = s.prevTable[:len(s.cTable)]
copy(s.prevTable, s.cTable)
s.prevTableLog = s.actualTableLog
// Force the next Compress* to recount from real input.
s.clearCount = true
s.maxCount = 0
return nil
}
// EstimateSize returns an estimated compressed payload size in bytes for the
// supplied histogram using the table currently stored in prevTable. It returns
// -1 when the table cannot encode every non-zero symbol of hist (i.e. when
// CanUseTable would return false). The estimate excludes the table header.
func (s *Scratch) EstimateSize(hist *[256]uint32) int {
if s == nil || hist == nil || len(s.prevTable) == 0 {
return -1
}
pt := s.prevTable
nbBits := uint32(7)
for i, v := range hist {
if v == 0 {
continue
}
if i >= len(pt) || pt[i].nBits == 0 {
return -1
}
nbBits += uint32(pt[i].nBits) * v
}
return int(nbBits >> 3)
}
// CanUseTable reports whether the table in prevTable can encode every
// non-zero symbol present in hist.
func (s *Scratch) CanUseTable(hist *[256]uint32) bool {
if s == nil || hist == nil || len(s.prevTable) == 0 {
return false
}
pt := s.prevTable
for i, v := range hist {
if v == 0 {
continue
}
if i >= len(pt) || pt[i].nBits == 0 {
return false
}
}
return true
}
// AppendTable serializes the table currently stored in prevTable (e.g. as
// installed by BuildCTable or carried over from a previous Compress call)
// into a self-delimiting zstd-style header and appends it to dst. The
// returned slice can be parsed back by ReadTable.
func (s *Scratch) AppendTable(dst []byte) ([]byte, error) {
if s == nil || len(s.prevTable) == 0 {
return dst, errors.New("huff0: AppendTable with empty table")
}
// cTable.write reads s.actualTableLog, s.symbolLen, s.huffWeight, s.fse
// and writes into s.Out. Save/restore Out so we don't disturb in-flight
// compression buffers.
saveOut := s.Out
saveTL := s.actualTableLog
saveSL := s.symbolLen
if s.fse == nil {
// Lazily init in case AppendTable is called on a fresh Scratch.
if _, err := s.prepare(nil); err != nil {
return dst, err
}
saveOut = s.Out
}
s.Out = s.Out[:0]
s.actualTableLog = s.prevTableLog
s.symbolLen = uint16(len(s.prevTable))
if err := s.prevTable.write(s); err != nil {
s.Out, s.actualTableLog, s.symbolLen = saveOut, saveTL, saveSL
return dst, err
}
dst = append(dst, s.Out...)
s.Out, s.actualTableLog, s.symbolLen = saveOut, saveTL, saveSL
return dst, nil
}
+1 -1
View File
@@ -31,7 +31,7 @@ func DecodedLen(src []byte) (int, error) {
// that the length header occupied.
func decodedLen(src []byte) (blockLen, headerLen int, err error) {
v, n := binary.Uvarint(src)
if n <= 0 || v > 0xffffffff {
if n <= 0 || n > 5 || v > 0xffffffff {
return 0, 0, ErrCorrupt
}
+1 -1
View File
@@ -35,7 +35,7 @@ func DecodedLen(src []byte) (int, error) {
// that the length header occupied.
func decodedLen(src []byte) (blockLen, headerLen int, err error) {
v, n := binary.Uvarint(src)
if n <= 0 || v > 0xffffffff {
if n <= 0 || n > 5 || v > 0xffffffff {
return 0, 0, ErrCorrupt
}
+4 -2
View File
@@ -56,10 +56,12 @@ func NewDict(dict []byte) *Dict {
if len(dict) < MinDictSize || len(dict) > MaxDictSize {
return nil
}
d.repeat = int(r)
if d.repeat > len(dict) {
// Compare as uint64: int(r) would wrap negative for r > MaxInt64,
// slipping past the bounds check and causing an OOB read in encode.
if r > uint64(len(dict)) {
return nil
}
d.repeat = int(r)
return &d
}
+1 -1
View File
@@ -981,7 +981,7 @@ searchDict:
cv = load64(src, s)
continue
}
} else if uint32(cv>>(checkRep*8)) == load32(src, s-repeat+checkRep) {
} else if repeat > 0 && uint32(cv>>(checkRep*8)) == load32(src, s-repeat+checkRep) {
base := s + checkRep
// Extend back
for i := base - repeat; base > nextEmit && i > 0 && src[i-1] == src[base-1]; {
+3 -3
View File
@@ -25,7 +25,7 @@ type betterTables struct {
sTable [betterShortTableSize]uint32
}
var betterTablePool = sync.Pool{New: func() interface{} { return &betterTables{} }}
var betterTablePool = sync.Pool{New: func() any { return &betterTables{} }}
// betterSnappyTables holds better-snappy compression hash tables.
type betterSnappyTables struct {
@@ -33,7 +33,7 @@ type betterSnappyTables struct {
sTable [betterShortTableSize]uint32
}
var betterSnappyTablePool = sync.Pool{New: func() interface{} { return &betterSnappyTables{} }}
var betterSnappyTablePool = sync.Pool{New: func() any { return &betterSnappyTables{} }}
// bestTables holds best compression hash tables.
type bestTables struct {
@@ -41,7 +41,7 @@ type bestTables struct {
sTable [bestShortTableSize]uint64
}
var bestTablePool = sync.Pool{New: func() interface{} { return &bestTables{} }}
var bestTablePool = sync.Pool{New: func() any { return &bestTables{} }}
// getBetterTables gets a zeroed betterTables from the pool.
func getBetterTables() *betterTables {
+12 -7
View File
@@ -216,13 +216,18 @@ func (r *Reader) skippable(tmp []byte, n int, allowEOF bool, id uint8) (ok bool)
return r.err == nil
}
if rs, ok := r.r.(io.ReadSeeker); ok {
_, err := rs.Seek(int64(n), io.SeekCurrent)
if err == nil {
return true
}
if err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) {
r.err = ErrCorrupt
return false
if cur, err := rs.Seek(0, io.SeekCurrent); err == nil {
if end, err := rs.Seek(0, io.SeekEnd); err == nil {
if cur+int64(n) <= end {
if _, err := rs.Seek(cur+int64(n), io.SeekStart); err == nil {
return true
}
}
if _, err := rs.Seek(cur, io.SeekStart); err != nil {
r.err = ErrCorrupt
return false
}
}
}
}
for n > 0 {
+130
View File
@@ -0,0 +1,130 @@
// Copyright 2011 The Snappy-Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package snappy
import "encoding/binary"
// DecodeStrict returns the decoded form of src, like Decode.
//
// Unlike Decode, which delegates to the s2 decoder and accepts the s2
// "repeat last offset" extension (a copy whose encoded offset is 0),
// DecodeStrict uses a strict standard-Snappy block decoder. Offset 0 is not
// valid in the standard Snappy block format, so such a copy is rejected with
// ErrCorrupt. This makes DecodeStrict match github.com/golang/snappy and the
// C++ reference decoder, at the cost of being slower than Decode.
//
// The returned slice may be a sub-slice of dst if dst was large enough to
// hold the entire decoded block. Otherwise, a newly allocated slice will be
// returned.
//
// The dst and src must not overlap. It is valid to pass a nil dst.
//
// DecodeStrict handles the Snappy block format, not the Snappy stream format.
func DecodeStrict(dst, src []byte) ([]byte, error) {
v, n := binary.Uvarint(src)
if n <= 0 || n > 5 || v > 0xffffffff {
return nil, ErrCorrupt
}
const wordSize = 32 << (^uint(0) >> 32 & 1)
if wordSize == 32 && v > 0x7fffffff {
return nil, ErrTooLarge
}
dLen := int(v)
if dLen <= cap(dst) {
dst = dst[:dLen]
} else {
dst = make([]byte, dLen)
}
if decodeStrict(dst, src[n:]) != 0 {
return nil, ErrCorrupt
}
return dst, nil
}
func decodeStrict(dst, src []byte) int {
var d, s, offset, length int
for s < len(src) {
switch src[s] & 0x03 {
case 0x00:
x := uint32(src[s] >> 2)
switch {
case x < 60:
s++
case x == 60:
s += 2
if uint(s) > uint(len(src)) {
return 1
}
x = uint32(src[s-1])
case x == 61:
s += 3
if uint(s) > uint(len(src)) {
return 1
}
x = uint32(src[s-2]) | uint32(src[s-1])<<8
case x == 62:
s += 4
if uint(s) > uint(len(src)) {
return 1
}
x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16
case x == 63:
s += 5
if uint(s) > uint(len(src)) {
return 1
}
x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24
}
length = int(x) + 1
if length <= 0 || length > len(dst)-d || length > len(src)-s {
return 1
}
copy(dst[d:], src[s:s+length])
d += length
s += length
continue
case 0x01:
s += 2
if uint(s) > uint(len(src)) {
return 1
}
length = 4 + int(src[s-2])>>2&0x7
offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1]))
case 0x02:
s += 3
if uint(s) > uint(len(src)) {
return 1
}
length = 1 + int(src[s-3])>>2
offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8)
case 0x03:
s += 5
if uint(s) > uint(len(src)) {
return 1
}
length = 1 + int(src[s-5])>>2
offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24)
}
if offset <= 0 || d < offset || length > len(dst)-d {
return 1
}
if offset >= length {
copy(dst[d:d+length], dst[d-offset:])
d += length
continue
}
a := dst[d : d+length]
b := dst[d-offset:]
b = b[:len(a)]
for i := range a {
a[i] = b[i]
}
d += length
}
if d != len(dst) {
return 1
}
return 0
}
+35 -2
View File
@@ -75,14 +75,47 @@ The above is fine for big encodes. However, whenever possible try to *reuse* the
To reuse the encoder, you can use the `Reset(io.Writer)` function to change to another output.
This will allow the encoder to reuse all resources and avoid wasteful allocations.
Currently stream encoding has 'light' concurrency, meaning up to 2 goroutines can be working on part
of a stream. This is independent of the `WithEncoderConcurrency(n)`, but that is likely to change
By default, stream encoding has 'light' concurrency, meaning up to 2 goroutines can be working on part
of a stream. This is independent of the `WithEncoderConcurrency(n)`, but that is likely to change
in the future. So if you want to limit concurrency for future updates, specify the concurrency
you would like.
If you would like stream encoding to be done without spawning async goroutines, use `WithEncoderConcurrency(1)`
which will compress input as each block is completed, blocking on writes until each has completed.
#### Parallel Stream Compression
For maximum throughput on large streams, use `WithConcurrentBlocks(true)` together with
`WithEncoderConcurrency(n)` where n is the number of CPU cores you want to use.
This splits the input into large sections (jobs) that are compressed simultaneously by multiple goroutines,
similar to how the C zstd library does multithreaded compression.
```Go
enc, err := zstd.NewWriter(out,
zstd.WithEncoderLevel(zstd.SpeedDefault),
zstd.WithEncoderConcurrency(runtime.GOMAXPROCS(0)),
zstd.WithConcurrentBlocks(true),
)
```
Each non-first job receives an overlap prefix from the previous job for match context,
so compression ratio is only marginally affected. Output is flushed in order,
producing a valid single-frame zstd stream.
Benchmark on 1.8GB GOB stream (AMD Ryzen 9 9950X):
| Level | 1 thread | 4 threads | 16 threads | 1T ratio | 16T ratio |
|---------|:----------:|:------------------:|:-------------------:|:--------:|:---------:|
| fastest | 783 MB/s | 2950 MB/s (3.8×) | 6939 MB/s (8.9×) | 12.24% | 12.26% |
| default | 728 MB/s | 2533 MB/s (3.5×) | 5340 MB/s (7.3×) | 10.67% | 10.68% |
| better | 434 MB/s | 1105 MB/s (2.5×) | 2206 MB/s (5.1×) | 9.14% | 9.21% |
| best | 129 MB/s | 367 MB/s (2.8×) | 884 MB/s (6.8×) | 8.48% | 8.63% |
Notes:
* Not compatible with dictionary encoding.
* `Flush()` dispatches the current partial job, so latency-sensitive callers can force output.
* `EncodeAll` is unaffected — it uses its own concurrency via the encoder pool.
You can specify your desired compression level using `WithEncoderLevel()` option. Currently only pre-defined
compression settings can be specified.
+2 -1
View File
@@ -230,7 +230,7 @@ func BuildDict(o BuildDictOptions) ([]byte, error) {
}
block := blockEnc{lowMem: false}
block.init()
enc := encoder(&bestFastEncoder{fastBase: fastBase{maxMatchOff: int32(maxMatchLen), bufferReset: math.MaxInt32 - int32(maxMatchLen*2), lowMem: false}})
var enc encoder
if o.Level != 0 {
eOpts := encoderOptions{
level: o.Level,
@@ -242,6 +242,7 @@ func BuildDict(o BuildDictOptions) ([]byte, error) {
enc = eOpts.encoder()
} else {
o.Level = SpeedBestCompression
enc = encoder(&bestFastEncoder{fastBase: fastBase{maxMatchOff: int32(maxMatchLen), bufferReset: math.MaxInt32 - int32(maxMatchLen*2), lowMem: false}})
}
var (
remain [256]int
+28
View File
@@ -128,6 +128,34 @@ func (e *fastBase) matchlen(s, t int32, src []byte) int32 {
return int32(matchLen(src[s:], src[t:]))
}
// resetBasePrefix resets the encoder state and loads prefix as initial history.
// This is used for parallel job encoding where non-first jobs need overlap context.
// Rep offsets are set to defaults [1,4,8] (invalidated, matching C behavior).
func (e *fastBase) resetBasePrefix(prefix []byte) {
if e.blk == nil {
e.blk = &blockEnc{lowMem: e.lowMem}
e.blk.init()
} else {
e.blk.reset(nil)
}
e.blk.initNewEncode()
if e.crc == nil {
e.crc = xxhash.New()
} else {
e.crc.Reset()
}
e.blk.dictLitEnc = nil
e.ensureHist(len(prefix) + maxCompressedBlockSize)
// Bump cur so old table entries fall outside the window.
// When cur >= bufferReset, leave it; the first Encode call
// will shift/clear tables, preserving valid prefix entries.
if e.cur < e.bufferReset {
e.cur += e.maxMatchOff + int32(len(e.hist))
}
e.hist = e.hist[:0]
e.hist = append(e.hist, prefix...)
}
// Reset the encoding table.
func (e *fastBase) resetBase(d *dict, singleBlock bool) {
if e.blk == nil {
+15
View File
@@ -551,3 +551,18 @@ func (e *bestFastEncoder) Reset(d *dict, singleBlock bool) {
// Reset table to initial state
copy(e.table[:], e.dictTable)
}
func (e *bestFastEncoder) ResetPrefix(prefix []byte) {
e.resetBasePrefix(prefix)
if len(prefix) < 8 {
return
}
end := e.cur + int32(len(prefix)) - 8
for i := e.cur; i < end; i++ {
cv := load6432(prefix, i-e.cur)
h := hashLen(cv, bestLongTableBits, bestLongLen)
e.longTable[h] = prevEntry{offset: i, prev: e.longTable[h].offset}
h0 := hashLen(cv, bestShortTableBits, bestShortLen)
e.table[h0] = prevEntry{offset: i, prev: e.table[h0].offset}
}
}
+18
View File
@@ -1096,6 +1096,20 @@ func (e *betterFastEncoder) Reset(d *dict, singleBlock bool) {
}
}
func (e *betterFastEncoder) ResetPrefix(prefix []byte) {
e.resetBasePrefix(prefix)
if len(prefix) < 8 {
return
}
end := e.cur + int32(len(prefix)) - 8
for i := e.cur; i < end; i += 2 {
cv := load6432(prefix, i-e.cur)
h := hashLen(cv, betterLongTableBits, betterLongLen)
e.longTable[h] = prevEntry{offset: i, prev: e.longTable[h].offset}
e.table[hashLen(cv>>8, betterShortTableBits, betterShortLen)] = tableEntry{val: uint32(cv >> 8), offset: i + 1}
}
}
// ResetDict will reset and set a dictionary if not nil
func (e *betterFastEncoderDict) Reset(d *dict, singleBlock bool) {
e.resetBase(d, singleBlock)
@@ -1229,6 +1243,10 @@ func (e *betterFastEncoderDict) Reset(d *dict, singleBlock bool) {
e.allDirty = false
}
func (e *betterFastEncoderDict) ResetPrefix([]byte) {
panic("ResetPrefix not supported for dict encoders")
}
func (e *betterFastEncoderDict) markLongShardDirty(entryNum uint32) {
e.longTableShardDirty[entryNum/betterLongTableShardSize] = true
}
+16
View File
@@ -1037,6 +1037,18 @@ func (e *doubleFastEncoder) Reset(d *dict, singleBlock bool) {
}
}
func (e *doubleFastEncoder) ResetPrefix(prefix []byte) {
e.fastEncoder.ResetPrefix(prefix)
if len(prefix) < 8 {
return
}
end := e.cur + int32(len(prefix)) - 8
for i := e.cur + 1; i < end; i += 2 {
cv := load6432(prefix, i-e.cur)
e.longTable[hashLen(cv, dFastLongTableBits, dFastLongLen)] = tableEntry{val: uint32(cv), offset: i}
}
}
// ResetDict will reset and set a dictionary if not nil
func (e *doubleFastEncoderDict) Reset(d *dict, singleBlock bool) {
allDirty := e.allDirty
@@ -1102,6 +1114,10 @@ func (e *doubleFastEncoderDict) Reset(d *dict, singleBlock bool) {
}
}
func (e *doubleFastEncoderDict) ResetPrefix([]byte) {
panic("ResetPrefix not supported for dict encoders")
}
func (e *doubleFastEncoderDict) markLongShardDirty(entryNum uint32) {
e.longTableShardDirty[entryNum/dLongTableShardSize] = true
}
+17
View File
@@ -797,6 +797,19 @@ func (e *fastEncoder) Reset(d *dict, singleBlock bool) {
}
}
func (e *fastEncoder) ResetPrefix(prefix []byte) {
e.resetBasePrefix(prefix)
if len(prefix) < 8 {
return
}
end := e.cur + int32(len(prefix)) - 8
// Index every 4th
for i := e.cur + 1; i < end; i += 4 {
cv := load6432(prefix, i-e.cur)
e.table[hashLen(cv, tableBits, tableFastHashLen)] = tableEntry{val: uint32(cv), offset: i}
}
}
// ResetDict will reset and set a dictionary if not nil
func (e *fastEncoderDict) Reset(d *dict, singleBlock bool) {
e.resetBase(d, singleBlock)
@@ -866,6 +879,10 @@ func (e *fastEncoderDict) Reset(d *dict, singleBlock bool) {
e.allDirty = false
}
func (e *fastEncoderDict) ResetPrefix([]byte) {
panic("ResetPrefix not supported for dict encoders")
}
func (e *fastEncoderDict) markAllShardsDirty() {
e.allDirty = true
}
+352
View File
@@ -0,0 +1,352 @@
// Copyright 2019+ Klaus Post. All rights reserved.
// License information can be found in the LICENSE file.
// Based on work by Yann Collet, released under BSD License.
package zstd
import (
"fmt"
rdebug "runtime/debug"
"sync"
)
type encJob struct {
prefix []byte // overlap from previous job (nil for first)
input []byte // job's own input data (swapped from filling)
last bool // last block of last job gets last=true
output []byte // compressed blocks (filled by worker)
err error // encoding error
done chan struct{} // closed when complete
}
type jobState struct {
jobSize int
overlapSize int
filling []byte // accumulates input up to jobSize
nextPrefix []byte // overlap prefix prepared for the next dispatched job
jobSeq int // next job sequence number
jobCh chan *encJob // dispatch to workers
resultCh chan *encJob // ordered results to flusher
workerWg sync.WaitGroup
flusherWg sync.WaitGroup
mu sync.Mutex
flushedSeq int // last flushed sequence number
cond *sync.Cond
flusherErr error
started bool
inputPool sync.Pool // *[]byte buffers of jobSize cap
outputPool sync.Pool // *[]byte buffers for compressed output
overlapPool sync.Pool // *[]byte buffers for overlap prefixes
}
func (e *Encoder) startJobWorkers() {
js := &e.state.jobs
n := e.o.concurrent
js.jobCh = make(chan *encJob, n)
js.resultCh = make(chan *encJob, n)
js.flushedSeq = 0
js.cond = sync.NewCond(&js.mu)
// Workers borrow encoders from the shared e.encoders pool per-job.
// Ensure the pool is initialized before any worker tries to borrow.
e.init.Do(e.initialize)
for range n {
js.workerWg.Add(1)
go e.jobWorker()
}
js.flusherWg.Add(1)
go e.jobFlusher()
js.started = true
}
func (e *Encoder) jobWorker() {
js := &e.state.jobs
defer js.workerWg.Done()
for job := range js.jobCh {
enc := <-e.encoders
e.compressJob(enc, job)
e.encoders <- enc
close(job.done)
}
}
func (e *Encoder) compressJob(enc encoder, job *encJob) {
defer func() {
if r := recover(); r != nil {
job.err = fmt.Errorf("panic in parallel job: %v", r)
rdebug.PrintStack()
}
}()
if len(job.prefix) > 0 {
enc.ResetPrefix(job.prefix)
} else {
enc.Reset(nil, false)
}
data := job.input
if len(data) == 0 && job.last {
blk := enc.Block()
blk.reset(nil)
blk.last = true
blk.encodeRaw(nil)
job.output = append(job.output, blk.output...)
return
}
blk := enc.Block()
for len(data) > 0 {
todo := data
if len(todo) > e.o.blockSize {
todo = todo[:e.o.blockSize]
}
data = data[len(todo):]
blk.pushOffsets()
enc.Encode(blk, todo)
blk.last = len(data) == 0 && job.last
err := blk.encode(todo, e.o.noEntropy, !e.o.allLitEntropy)
if err != nil {
job.err = err
return
}
job.output = append(job.output, blk.output...)
blk.reset(nil)
}
}
func (js *jobState) getInputBuf(size int) []byte {
if v := js.inputPool.Get(); v != nil {
bp := v.(*[]byte)
b := *bp
if cap(b) >= size {
return b[:0]
}
}
return make([]byte, 0, size)
}
func (js *jobState) putInputBuf(b []byte) {
if cap(b) > 0 {
b = b[:0]
js.inputPool.Put(&b)
}
}
func (js *jobState) getOutputBuf(size int) []byte {
if v := js.outputPool.Get(); v != nil {
bp := v.(*[]byte)
b := *bp
if cap(b) >= size {
return b[:0]
}
}
return make([]byte, 0, size)
}
func (js *jobState) putOutputBuf(b []byte) {
if cap(b) > 0 {
b = b[:0]
js.outputPool.Put(&b)
}
}
func (js *jobState) getOverlapBuf(size int) []byte {
if v := js.overlapPool.Get(); v != nil {
bp := v.(*[]byte)
b := *bp
if cap(b) >= size {
return b[:size]
}
}
return make([]byte, size)
}
func (js *jobState) putOverlapBuf(b []byte) {
if cap(b) > 0 {
b = b[:0]
js.overlapPool.Put(&b)
}
}
func (e *Encoder) jobFlusher() {
js := &e.state.jobs
defer js.flusherWg.Done()
for job := range js.resultCh {
<-job.done
// Worker has fully exited compressJob, so the prefix is no longer
// in use. Return it to the pool regardless of outcome.
if job.prefix != nil {
js.putOverlapBuf(job.prefix)
job.prefix = nil
}
if job.err != nil {
js.mu.Lock()
js.flusherErr = job.err
js.cond.Broadcast()
js.mu.Unlock()
for range js.resultCh {
}
return
}
if len(job.output) > 0 {
_, err := e.state.w.Write(job.output)
if err != nil {
js.mu.Lock()
js.flusherErr = err
js.cond.Broadcast()
js.mu.Unlock()
for range js.resultCh {
}
return
}
e.state.nWritten += int64(len(job.output))
}
// Return buffers to pools.
js.putInputBuf(job.input)
js.putOutputBuf(job.output)
job.input = nil
job.output = nil
js.mu.Lock()
js.flushedSeq++
js.cond.Broadcast()
js.mu.Unlock()
}
}
func (e *Encoder) shutdownJobWorkers() {
js := &e.state.jobs
if !js.started {
return
}
close(js.jobCh)
js.workerWg.Wait()
close(js.resultCh)
js.flusherWg.Wait()
js.started = false
}
// waitAllJobs blocks until all dispatched jobs have been flushed.
func (e *Encoder) waitAllJobs() {
js := &e.state.jobs
if !js.started {
return
}
js.mu.Lock()
for js.flushedSeq < js.jobSeq && js.flusherErr == nil {
js.cond.Wait()
}
js.mu.Unlock()
}
func (e *Encoder) dispatchJob(final bool) error {
s := &e.state
js := &s.jobs
js.mu.Lock()
fErr := js.flusherErr
js.mu.Unlock()
if fErr != nil {
return fErr
}
if !s.headerWritten {
// Single-block optimization: fall through to encodeAll path.
if final && len(js.filling) > 0 && len(js.filling) <= e.o.blockSize {
s.current = e.encodeAll(s.encoder, js.filling, s.current[:0])
var n2 int
n2, s.err = s.w.Write(s.current)
if s.err != nil {
return s.err
}
s.nWritten += int64(n2)
s.nInput += int64(len(js.filling))
s.current = s.current[:0]
js.filling = js.filling[:0]
s.headerWritten = true
s.fullFrameWritten = true
s.eofWritten = true
return nil
}
if final && len(js.filling) == 0 && !e.o.fullZero {
s.headerWritten = true
s.fullFrameWritten = true
s.eofWritten = true
return nil
}
var tmp [maxHeaderSize]byte
fh := frameHeader{
ContentSize: uint64(s.frameContentSize),
WindowSize: uint32(s.encoder.WindowSize(s.frameContentSize)),
SingleSegment: false,
Checksum: e.o.crc,
DictID: 0,
}
dst := fh.appendTo(tmp[:0])
var n2 int
n2, s.err = s.w.Write(dst)
if s.err != nil {
return s.err
}
s.nWritten += int64(n2)
s.headerWritten = true
}
if len(js.filling) == 0 && !final {
return nil
}
if !js.started {
e.startJobWorkers()
}
// Estimate output size for pooled buffer.
outputEst := max(len(js.filling)/2, 512)
job := &encJob{
last: final,
done: make(chan struct{}),
output: js.getOutputBuf(outputEst),
}
// Each job owns its prefix slice; the flusher returns it to the pool
// after <-job.done, so workers and dispatch never share a buffer.
if js.nextPrefix != nil {
job.prefix = js.nextPrefix
js.nextPrefix = nil
}
// Build the next job's prefix from the tail of this job's input.
if !final && len(js.filling) > 0 {
overlapLen := min(js.overlapSize, len(js.filling))
np := js.getOverlapBuf(overlapLen)
copy(np, js.filling[len(js.filling)-overlapLen:])
js.nextPrefix = np
}
// Swap filling buffer into job — zero-copy for the input data.
job.input = js.filling
js.filling = js.getInputBuf(js.jobSize)
s.nInput += int64(len(job.input))
js.jobSeq++
if final {
s.eofWritten = true
}
js.resultCh <- job
js.jobCh <- job
return nil
}
+206 -4
View File
@@ -38,6 +38,7 @@ type encoder interface {
WindowSize(size int64) int32
UseBlock(*blockEnc)
Reset(d *dict, singleBlock bool)
ResetPrefix(prefix []byte)
}
type encoderState struct {
@@ -60,6 +61,9 @@ type encoderState struct {
wg sync.WaitGroup
// This waitgroup indicates we have a block encoding/writing.
wWg sync.WaitGroup
// Parallel job state (used when concurrentBlocks is enabled).
jobs jobState
}
// NewWriter will create a new Zstandard encoder.
@@ -74,6 +78,9 @@ func NewWriter(w io.Writer, opts ...EOption) (*Encoder, error) {
return nil, err
}
}
if e.o.concurrentBlocks && (e.o.dict != nil || e.o.concurrent <= 1) {
e.o.concurrentBlocks = false
}
if w != nil {
e.Reset(w)
}
@@ -95,12 +102,31 @@ func (e *Encoder) initialize() {
// as a new, independent stream.
func (e *Encoder) Reset(w io.Writer) {
s := &e.state
if e.o.concurrentBlocks {
e.shutdownJobWorkers()
js := &s.jobs
js.jobSize = e.o.jobSize()
js.overlapSize = e.o.overlapSize()
// js.filling is allocated lazily on first Write/ReadFrom so callers
// that only use EncodeAll don't pay the (up to ~32 MB) jobSize cost.
js.filling = js.filling[:0]
if js.nextPrefix != nil {
js.putOverlapBuf(js.nextPrefix)
js.nextPrefix = nil
}
js.jobSeq = 0
js.flushedSeq = 0
js.flusherErr = nil
js.started = false
}
s.wg.Wait()
s.wWg.Wait()
if cap(s.filling) == 0 {
s.filling = make([]byte, 0, e.o.blockSize)
}
if e.o.concurrent > 1 {
if e.o.concurrent > 1 && !e.o.concurrentBlocks {
if cap(s.current) == 0 {
s.current = make([]byte, 0, e.o.blockSize)
}
@@ -145,6 +171,9 @@ func (e *Encoder) ResetWithOptions(w io.Writer, opts ...EOption) error {
}
}
hasDict := e.o.dict != nil
if e.o.concurrentBlocks && hasDict {
e.o.concurrentBlocks = false
}
if hadDict != hasDict {
// Dict presence changed — encoder type must be recreated.
e.state.encoder = nil
@@ -176,6 +205,49 @@ func (e *Encoder) Write(p []byte) (n int, err error) {
if s.eofWritten {
return 0, ErrEncoderClosed
}
if e.o.concurrentBlocks {
return e.writeJobs(p)
}
return e.writeBlocks(p)
}
func (e *Encoder) writeJobs(p []byte) (n int, err error) {
s := &e.state
js := &s.jobs
jobSize := js.jobSize
if cap(js.filling) == 0 && len(p) > 0 {
js.filling = make([]byte, 0, jobSize)
}
for len(p) > 0 {
if len(p)+len(js.filling) < jobSize {
if e.o.crc {
_, _ = s.encoder.CRC().Write(p)
}
js.filling = append(js.filling, p...)
return n + len(p), nil
}
add := p
if len(p)+len(js.filling) > jobSize {
add = add[:jobSize-len(js.filling)]
}
if e.o.crc {
_, _ = s.encoder.CRC().Write(add)
}
js.filling = append(js.filling, add...)
p = p[len(add):]
n += len(add)
if len(js.filling) < jobSize {
return n, nil
}
if err := e.dispatchJob(false); err != nil {
return n, err
}
}
return n, nil
}
func (e *Encoder) writeBlocks(p []byte) (n int, err error) {
s := &e.state
for len(p) > 0 {
if len(p)+len(s.filling) < e.o.blockSize {
if e.o.crc {
@@ -374,6 +446,10 @@ func (e *Encoder) ReadFrom(r io.Reader) (n int64, err error) {
println("Using ReadFrom")
}
if e.o.concurrentBlocks {
return e.readFromJobs(r)
}
// Flush any current writes.
if len(e.state.filling) > 0 {
if err := e.nextBlock(false); err != nil {
@@ -387,7 +463,6 @@ func (e *Encoder) ReadFrom(r io.Reader) (n int64, err error) {
if e.o.crc {
_, _ = e.state.encoder.CRC().Write(src[:n2])
}
// src is now the unfilled part...
src = src[n2:]
n += int64(n2)
switch err {
@@ -420,15 +495,63 @@ func (e *Encoder) ReadFrom(r io.Reader) (n int64, err error) {
}
}
func (e *Encoder) readFromJobs(r io.Reader) (n int64, err error) {
js := &e.state.jobs
jobSize := js.jobSize
// Flush any current filling.
if len(js.filling) > 0 {
if err := e.dispatchJob(false); err != nil {
return 0, err
}
}
if cap(js.filling) < jobSize {
js.filling = make([]byte, 0, jobSize)
}
js.filling = js.filling[:jobSize]
src := js.filling
for {
n2, err := r.Read(src)
if e.o.crc {
_, _ = e.state.encoder.CRC().Write(src[:n2])
}
src = src[n2:]
n += int64(n2)
switch err {
case io.EOF:
js.filling = js.filling[:len(js.filling)-len(src)]
return n, nil
case nil:
default:
e.state.err = err
return n, err
}
if len(src) > 0 {
continue
}
if err = e.dispatchJob(false); err != nil {
return n, err
}
if cap(js.filling) < jobSize {
js.filling = make([]byte, 0, jobSize)
}
js.filling = js.filling[:jobSize]
src = js.filling
}
}
// Flush will send the currently written data to output
// and block until everything has been written.
// This should only be used on rare occasions where pushing the currently queued data is critical.
func (e *Encoder) Flush() error {
s := &e.state
if e.o.concurrentBlocks {
return e.flushJobs()
}
if len(s.filling) > 0 {
err := e.nextBlock(false)
if err != nil {
// Ignore Flush after Close.
if errors.Is(s.err, ErrEncoderClosed) {
return nil
}
@@ -438,7 +561,6 @@ func (e *Encoder) Flush() error {
s.wg.Wait()
s.wWg.Wait()
if s.err != nil {
// Ignore Flush after Close.
if errors.Is(s.err, ErrEncoderClosed) {
return nil
}
@@ -447,6 +569,20 @@ func (e *Encoder) Flush() error {
return s.writeErr
}
func (e *Encoder) flushJobs() error {
js := &e.state.jobs
if len(js.filling) > 0 {
if err := e.dispatchJob(false); err != nil {
return err
}
}
e.waitAllJobs()
js.mu.Lock()
fErr := js.flusherErr
js.mu.Unlock()
return fErr
}
// Close will flush the final output and close the stream.
// The function will block until everything has been written.
// The Encoder can still be re-used after calling this.
@@ -455,12 +591,16 @@ func (e *Encoder) Close() error {
if s.encoder == nil {
return nil
}
if e.o.concurrentBlocks {
return e.closeJobs()
}
if s.w == nil {
if len(s.filling) == 0 && !s.headerWritten && !s.eofWritten && s.nInput == 0 {
return nil
}
return errors.New("zstd: encoder has no writer")
}
err := e.nextBlock(true)
if err != nil {
if errors.Is(s.err, ErrEncoderClosed) {
@@ -511,6 +651,68 @@ func (e *Encoder) Close() error {
return s.err
}
func (e *Encoder) closeJobs() error {
s := &e.state
js := &s.jobs
if errors.Is(s.err, ErrEncoderClosed) {
return nil
}
if s.w == nil {
if len(js.filling) == 0 && !s.headerWritten && !s.eofWritten && s.nInput == 0 {
return nil
}
return errors.New("zstd: encoder has no writer")
}
if err := e.dispatchJob(true); err != nil {
e.shutdownJobWorkers()
if errors.Is(s.err, ErrEncoderClosed) {
return nil
}
return err
}
if s.frameContentSize > 0 && s.nInput != s.frameContentSize {
e.shutdownJobWorkers()
return fmt.Errorf("frame content size %d given, but %d bytes was written", s.frameContentSize, s.nInput)
}
if s.fullFrameWritten {
e.shutdownJobWorkers()
s.err = ErrEncoderClosed
return nil
}
e.shutdownJobWorkers()
if js.flusherErr != nil {
return js.flusherErr
}
// Write CRC
if e.o.crc {
var tmp [4]byte
_, s.err = s.w.Write(s.encoder.AppendCRC(tmp[:0]))
s.nWritten += 4
}
// Add padding
if s.err == nil && e.o.pad > 0 {
add := calcSkippableFrame(s.nWritten, int64(e.o.pad))
frame, err := skippableFrame(js.filling[:0], add, rand.Reader)
if err != nil {
return err
}
_, s.err = s.w.Write(frame)
}
if s.err == nil {
s.err = ErrEncoderClosed
return nil
}
return s.err
}
// EncodeAll will encode all input in src and append it to dst.
// This function can be called concurrently, but each call will only run on a single goroutine.
// If empty input is given, nothing is returned, unless WithZeroFrames is specified.
+53 -16
View File
@@ -14,22 +14,23 @@ type EOption func(*encoderOptions) error
// options retains accumulated state of multiple options.
type encoderOptions struct {
resetOpt bool
concurrent int
level EncoderLevel
single *bool
pad int
blockSize int
windowSize int
crc bool
fullZero bool
noEntropy bool
allLitEntropy bool
customWindow bool
customALEntropy bool
customBlockSize bool
lowMem bool
dict *dict
resetOpt bool
concurrent int
level EncoderLevel
single *bool
pad int
blockSize int
windowSize int
crc bool
fullZero bool
noEntropy bool
allLitEntropy bool
customWindow bool
customALEntropy bool
customBlockSize bool
lowMem bool
dict *dict
concurrentBlocks bool
}
func (o *encoderOptions) setDefault() {
@@ -333,6 +334,42 @@ func WithLowerEncoderMem(b bool) EOption {
}
}
// WithConcurrentBlocks enables job-based parallel compression for streams.
// When enabled and concurrent > 1, input is split into large sections (jobs)
// that are compressed simultaneously by multiple goroutines.
// Each non-first job receives an overlap prefix from the previous job for match context.
// Output is flushed in order, producing a valid single-frame zstd stream.
//
// Currently disabled when used with dictionary encoding.
// Cannot be changed with ResetWithOptions.
func WithConcurrentBlocks(b bool) EOption {
return func(o *encoderOptions) error {
if o.resetOpt && b != o.concurrentBlocks {
return errors.New("WithConcurrentBlocks cannot be changed on Reset")
}
o.concurrentBlocks = b
return nil
}
}
// jobSize returns the input section size per parallel job.
func (o *encoderOptions) jobSize() int {
s := max(o.windowSize*4, 512<<10)
return s
}
// overlapSize returns the overlap prefix size for parallel jobs.
func (o *encoderOptions) overlapSize() int {
switch o.level {
case SpeedBestCompression:
return o.windowSize / 2
case SpeedBetterCompression:
return o.windowSize / 4
default:
return o.windowSize / 8
}
}
// WithEncoderDict allows to register a dictionary that will be used for the encode.
//
// The slice dict must be in the [dictionary format] produced by
+1 -1
View File
@@ -1,4 +1,4 @@
// Code generated by command: go run gen_fse.go -out ../fse_decoder_amd64.s -pkg=zstd. DO NOT EDIT.
// Code generated by command: go run gen_fse.go -out ../fse_decoder.s -arch amd64,arm64 -pkg=zstd. DO NOT EDIT.
//go:build !appengine && !noasm && gc && !noasm
+153
View File
@@ -0,0 +1,153 @@
// Code generated by command: go run gen_fse.go -out ../fse_decoder.s -arch amd64,arm64 -pkg=zstd. DO NOT EDIT.
// EXPERIMENTAL arm64 output lowered from an amd64 avo program.
//go:build arm64 && !appengine && !noasm && gc && !noasm
// func buildDtable_asm(s *fseDecoder, ctx *buildDtableAsmContext) int
TEXT ·buildDtable_asm(SB), $0-24
MOVD ctx+8(FP), R1
MOVD s+0(FP), R6
// Load values
MOVBU 4098(R6), R2
MOVD $0, R0
MOVD $1, R16
LSL R2, R16, R16
ORR R16, R0, R0
MOVD (R1), R3
MOVD 16(R1), R5
SUB $1, R0, R7
MOVD 8(R1), R1
MOVHU 4096(R6), R6
// End load values
// Init, lay down lowprob symbols
MOVD $0, R8
JMP init_main_loop_condition
init_main_loop:
ADD R8<<1, R1, R15
MOVH (R15), R9
AND $0xffff, R9, R15
MOVD $-1, R16
AND $0xffff, R16, R16
CMP R16, R15
BNE do_not_update_high_threshold
ADD R7<<3, R5, R15
MOVB R8, 1(R15)
SUB $1, R7, R7
MOVD $0x0000000000000001, R9
do_not_update_high_threshold:
ADD R8<<1, R3, R15
MOVH R9, (R15)
ADD $1, R8, R8
init_main_loop_condition:
CMP R6, R8
BLT init_main_loop
// 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
// Fill add bits values
SUB $1, R0, R9
MOVD $0, R10
MOVD $0, R11
JMP spread_main_loop_condition
spread_main_loop:
MOVD $0, R12
ADD R11<<1, R1, R15
MOVH (R15), R13
JMP spread_inner_loop_condition
spread_inner_loop:
ADD R10<<3, R5, R15
MOVB R11, 1(R15)
adjust_position:
ADD R8, R10, R10
AND R9, R10, R10
CMP R7, R10
BGT adjust_position
ADD $1, R12, R12
spread_inner_loop_condition:
CMP R13, R12
BLT spread_inner_loop
ADD $1, R11, R11
spread_main_loop_condition:
CMP R6, R11
BLT spread_main_loop
TST R10, R10
BEQ spread_check_ok
MOVD ctx+8(FP), R0
MOVD R10, 24(R0)
MOVD $+1, R16
MOVD R16, ret+16(FP)
RET
spread_check_ok:
// Build Decoding table
MOVD $0, R6
build_table_main_table:
ADD R6<<3, R5, R15
MOVBU 1(R15), R1
ADD R1<<1, R3, R15
MOVHU (R15), R7
ADD $1, R7, R8
ADD R1<<1, R3, R15
MOVH R8, (R15)
MOVD R7, R8
CLZ R8, R16
MOVD $63, R8
SUB R16, R8, R8
MOVD R2, R1
SUB R8, R1, R1
LSL R1, R7, R7
SUB R0, R7, R7
ADD R6<<3, R5, R15
MOVB R1, (R15)
ADD R6<<3, R5, R15
MOVH R7, 2(R15)
CMP R0, R7
BLE build_table_check1_ok
MOVD ctx+8(FP), R1
MOVD R7, 24(R1)
MOVD R0, 32(R1)
MOVD $+2, R16
MOVD R16, ret+16(FP)
RET
build_table_check1_ok:
AND $0xff, R1, R15
AND $0xff, R1, R16
TST R16, R15
BNE build_table_check2_ok
AND $0xffff, R7, R15
AND $0xffff, R6, R16
CMP R16, R15
BNE build_table_check2_ok
MOVD ctx+8(FP), R0
MOVD R7, 24(R0)
MOVD R6, 32(R0)
MOVD $+3, R16
MOVD R16, ret+16(FP)
RET
build_table_check2_ok:
ADD $1, R6, R6
CMP R0, R6
BLT build_table_main_table
MOVD $+0, R16
MOVD R16, ret+16(FP)
RET
@@ -1,4 +1,4 @@
//go:build amd64 && !appengine && !noasm && gc
//go:build (amd64 || arm64) && !appengine && !noasm && gc
package zstd
@@ -6,6 +6,10 @@ import (
"fmt"
)
// buildDtable_asm is generated by _generate/gen_fse.go and lowered to each
// architecture (amd64 by goasm, arm64 by the avo arm64 lowering printer). The
// Go side is identical across architectures, so it lives here.
type buildDtableAsmContext struct {
// inputs
stateTable *uint16
@@ -18,7 +22,7 @@ type buildDtableAsmContext struct {
errParam2 uint64
}
// buildDtable_asm is an x86 assembly implementation of fseDecoder.buildDtable.
// buildDtable_asm is an assembly implementation of fseDecoder.buildDtable.
// Function returns non-zero exit code on error.
//
//go:noescape
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !amd64 || appengine || !gc || noasm
//go:build (!amd64 && !arm64) || appengine || !gc || noasm
package zstd
+51 -333
View File
@@ -3,30 +3,47 @@
package zstd
import (
"fmt"
"io"
"github.com/klauspost/compress/internal/cpuinfo"
)
type decodeSyncAsmContext struct {
llTable []decSymbol
mlTable []decSymbol
ofTable []decSymbol
llState uint64
mlState uint64
ofState uint64
iteration int
litRemain int
out []byte
outPosition int
literals []byte
litPosition int
history []byte
windowSize int
ll int // set on error (not for all errors, please refer to _generate/gen.go)
ml int // set on error (not for all errors, please refer to _generate/gen.go)
mo int // set on error (not for all errors, please refer to _generate/gen.go)
// The shared decode/decodeSync/executeSimple wrappers and context structs live
// in seqdec_asm.go; this file only declares the amd64 asm routines and the
// dispatch helpers that pick the BMI2 / non-BMI2 (and 56-bit / safe) variant.
// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm.
//
// Please refer to seqdec_generic.go for the reference implementation.
//
//go:noescape
func sequenceDecs_decode_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// sequenceDecs_decode_56_amd64 implements the main loop of sequenceDecs in x86 asm.
//
//go:noescape
func sequenceDecs_decode_56_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// sequenceDecs_decode_bmi2 implements the main loop of sequenceDecs in x86 asm with BMI2 extensions.
//
//go:noescape
func sequenceDecs_decode_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// sequenceDecs_decode_56_bmi2 implements the main loop of sequenceDecs in x86 asm with BMI2 extensions.
//
//go:noescape
func sequenceDecs_decode_56_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// decodeAsm runs the sequenceDecs decode loop, choosing the BMI2 / 56-bit variant.
func decodeAsm(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext, lte56bits bool) int {
if cpuinfo.HasBMI2() {
if lte56bits {
return sequenceDecs_decode_56_bmi2(s, br, ctx)
}
return sequenceDecs_decode_bmi2(s, br, ctx)
}
if lte56bits {
return sequenceDecs_decode_56_amd64(s, br, ctx)
}
return sequenceDecs_decode_amd64(s, br, ctx)
}
// sequenceDecs_decodeSync_amd64 implements the main loop of sequenceDecs.decodeSync in x86 asm.
@@ -51,273 +68,18 @@ func sequenceDecs_decodeSync_safe_amd64(s *sequenceDecs, br *bitReader, ctx *dec
//go:noescape
func sequenceDecs_decodeSync_safe_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int
// decode sequences from the stream with the provided history but without a dictionary.
func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) {
if len(s.dict) > 0 {
return false, nil
}
if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSize {
return false, nil
}
// FIXME: Using unsafe memory copies leads to rare, random crashes
// with fuzz testing. It is therefore disabled for now.
const useSafe = true
/*
useSafe := false
if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSizeAlloc {
useSafe = true
}
if s.maxSyncLen > 0 && cap(s.out)-len(s.out)-compressedBlockOverAlloc < int(s.maxSyncLen) {
useSafe = true
}
if cap(s.literals) < len(s.literals)+compressedBlockOverAlloc {
useSafe = true
}
*/
br := s.br
maxBlockSize := min(s.windowSize, maxCompressedBlockSize)
ctx := decodeSyncAsmContext{
llTable: s.litLengths.fse.dt[:maxTablesize],
mlTable: s.matchLengths.fse.dt[:maxTablesize],
ofTable: s.offsets.fse.dt[:maxTablesize],
llState: uint64(s.litLengths.state.state),
mlState: uint64(s.matchLengths.state.state),
ofState: uint64(s.offsets.state.state),
iteration: s.nSeqs - 1,
litRemain: len(s.literals),
out: s.out,
outPosition: len(s.out),
literals: s.literals,
windowSize: s.windowSize,
history: hist,
}
s.seqSize = 0
startSize := len(s.out)
var errCode int
// decodeSyncAsm runs the decodeSync loop, choosing the BMI2 / safe variant.
func decodeSyncAsm(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext, safe bool) int {
if cpuinfo.HasBMI2() {
if useSafe {
errCode = sequenceDecs_decodeSync_safe_bmi2(s, br, &ctx)
} else {
errCode = sequenceDecs_decodeSync_bmi2(s, br, &ctx)
}
} else {
if useSafe {
errCode = sequenceDecs_decodeSync_safe_amd64(s, br, &ctx)
} else {
errCode = sequenceDecs_decodeSync_amd64(s, br, &ctx)
if safe {
return sequenceDecs_decodeSync_safe_bmi2(s, br, ctx)
}
return sequenceDecs_decodeSync_bmi2(s, br, ctx)
}
switch errCode {
case noError:
break
case errorMatchLenOfsMismatch:
return true, fmt.Errorf("zero matchoff and matchlen (%d) > 0", ctx.ml)
case errorMatchLenTooBig:
return true, fmt.Errorf("match len (%d) bigger than max allowed length", ctx.ml)
case errorMatchOffTooBig:
return true, fmt.Errorf("match offset (%d) bigger than current history (%d)",
ctx.mo, ctx.outPosition+len(hist)-startSize)
case errorNotEnoughLiterals:
return true, fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available",
ctx.ll, ctx.litRemain+ctx.ll)
case errorOverread:
return true, io.ErrUnexpectedEOF
case errorNotEnoughSpace:
size := ctx.outPosition + ctx.ll + ctx.ml
if debugDecoder {
println("msl:", s.maxSyncLen, "cap", cap(s.out), "bef:", startSize, "sz:", size-startSize, "mbs:", maxBlockSize, "outsz:", cap(s.out)-startSize)
}
return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize)
default:
return true, fmt.Errorf("sequenceDecs_decode returned erroneous code %d", errCode)
if safe {
return sequenceDecs_decodeSync_safe_amd64(s, br, ctx)
}
s.seqSize += ctx.litRemain
if s.seqSize > maxBlockSize {
return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize)
}
err := br.close()
if err != nil {
printf("Closing sequences: %v, %+v\n", err, *br)
return true, err
}
s.literals = s.literals[ctx.litPosition:]
t := ctx.outPosition
s.out = s.out[:t]
// Add final literals
s.out = append(s.out, s.literals...)
if debugDecoder {
t += len(s.literals)
if t != len(s.out) {
panic(fmt.Errorf("length mismatch, want %d, got %d", len(s.out), t))
}
}
return true, nil
}
// --------------------------------------------------------------------------------
type decodeAsmContext struct {
llTable []decSymbol
mlTable []decSymbol
ofTable []decSymbol
llState uint64
mlState uint64
ofState uint64
iteration int
seqs []seqVals
litRemain int
}
const noError = 0
// error reported when mo == 0 && ml > 0
const errorMatchLenOfsMismatch = 1
// error reported when ml > maxMatchLen
const errorMatchLenTooBig = 2
// error reported when mo > available history or mo > s.windowSize
const errorMatchOffTooBig = 3
// error reported when the sum of literal lengths exeeceds the literal buffer size
const errorNotEnoughLiterals = 4
// error reported when capacity of `out` is too small
const errorNotEnoughSpace = 5
// error reported when bits are overread.
const errorOverread = 6
// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm.
//
// Please refer to seqdec_generic.go for the reference implementation.
//
//go:noescape
func sequenceDecs_decode_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm.
//
// Please refer to seqdec_generic.go for the reference implementation.
//
//go:noescape
func sequenceDecs_decode_56_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm with BMI2 extensions.
//
//go:noescape
func sequenceDecs_decode_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// sequenceDecs_decode implements the main loop of sequenceDecs in x86 asm with BMI2 extensions.
//
//go:noescape
func sequenceDecs_decode_56_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// decode sequences from the stream without the provided history.
func (s *sequenceDecs) decode(seqs []seqVals) error {
br := s.br
maxBlockSize := min(s.windowSize, maxCompressedBlockSize)
ctx := decodeAsmContext{
llTable: s.litLengths.fse.dt[:maxTablesize],
mlTable: s.matchLengths.fse.dt[:maxTablesize],
ofTable: s.offsets.fse.dt[:maxTablesize],
llState: uint64(s.litLengths.state.state),
mlState: uint64(s.matchLengths.state.state),
ofState: uint64(s.offsets.state.state),
seqs: seqs,
iteration: len(seqs) - 1,
litRemain: len(s.literals),
}
if debugDecoder {
println("decode: decoding", len(seqs), "sequences", br.remain(), "bits remain on stream")
}
s.seqSize = 0
lte56bits := s.maxBits+s.offsets.fse.actualTableLog+s.matchLengths.fse.actualTableLog+s.litLengths.fse.actualTableLog <= 56
var errCode int
if cpuinfo.HasBMI2() {
if lte56bits {
errCode = sequenceDecs_decode_56_bmi2(s, br, &ctx)
} else {
errCode = sequenceDecs_decode_bmi2(s, br, &ctx)
}
} else {
if lte56bits {
errCode = sequenceDecs_decode_56_amd64(s, br, &ctx)
} else {
errCode = sequenceDecs_decode_amd64(s, br, &ctx)
}
}
if errCode != 0 {
i := len(seqs) - ctx.iteration - 1
switch errCode {
case errorMatchLenOfsMismatch:
ml := ctx.seqs[i].ml
return fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml)
case errorMatchLenTooBig:
ml := ctx.seqs[i].ml
return fmt.Errorf("match len (%d) bigger than max allowed length", ml)
case errorNotEnoughLiterals:
ll := ctx.seqs[i].ll
return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", ll, ctx.litRemain+ll)
case errorOverread:
return io.ErrUnexpectedEOF
}
return fmt.Errorf("sequenceDecs_decode_amd64 returned erroneous code %d", errCode)
}
if ctx.litRemain < 0 {
return fmt.Errorf("literal count is too big: total available %d, total requested %d",
len(s.literals), len(s.literals)-ctx.litRemain)
}
s.seqSize += ctx.litRemain
if s.seqSize > maxBlockSize {
return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize)
}
if debugDecoder {
println("decode: ", br.remain(), "bits remain on stream. code:", errCode)
}
err := br.close()
if err != nil {
printf("Closing sequences: %v, %+v\n", err, *br)
}
return err
}
// --------------------------------------------------------------------------------
type executeAsmContext struct {
seqs []seqVals
seqIndex int
out []byte
history []byte
literals []byte
outPosition int
litPosition int
windowSize int
return sequenceDecs_decodeSync_amd64(s, br, ctx)
}
// sequenceDecs_executeSimple_amd64 implements the main loop of sequenceDecs.executeSimple in x86 asm.
@@ -334,54 +96,10 @@ func sequenceDecs_executeSimple_amd64(ctx *executeAsmContext) bool
//go:noescape
func sequenceDecs_executeSimple_safe_amd64(ctx *executeAsmContext) bool
// executeSimple handles cases when dictionary is not used.
func (s *sequenceDecs) executeSimple(seqs []seqVals, hist []byte) error {
// Ensure we have enough output size...
if len(s.out)+s.seqSize+compressedBlockOverAlloc > cap(s.out) {
addBytes := s.seqSize + len(s.out) + compressedBlockOverAlloc
s.out = append(s.out, make([]byte, addBytes)...)
s.out = s.out[:len(s.out)-addBytes]
// executeSimpleAsm runs the executeSimple loop, choosing the safe variant.
func executeSimpleAsm(ctx *executeAsmContext, safe bool) bool {
if safe {
return sequenceDecs_executeSimple_safe_amd64(ctx)
}
if debugDecoder {
printf("Execute %d seqs with literals: %d into %d bytes\n", len(seqs), len(s.literals), s.seqSize)
}
var t = len(s.out)
out := s.out[:t+s.seqSize]
ctx := executeAsmContext{
seqs: seqs,
seqIndex: 0,
out: out,
history: hist,
outPosition: t,
litPosition: 0,
literals: s.literals,
windowSize: s.windowSize,
}
var ok bool
if cap(s.literals) < len(s.literals)+compressedBlockOverAlloc {
ok = sequenceDecs_executeSimple_safe_amd64(&ctx)
} else {
ok = sequenceDecs_executeSimple_amd64(&ctx)
}
if !ok {
return fmt.Errorf("match offset (%d) bigger than current history (%d)",
seqs[ctx.seqIndex].mo, ctx.outPosition+len(hist))
}
s.literals = s.literals[ctx.litPosition:]
t = ctx.outPosition
// Add final literals
copy(out[t:], s.literals)
if debugDecoder {
t += len(s.literals)
if t != len(out) {
panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(out), t, s.seqSize))
}
}
s.out = out
return nil
return sequenceDecs_executeSimple_amd64(ctx)
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Code generated by command: go run gen.go -out ../seqdec_amd64.s -pkg=zstd. DO NOT EDIT.
// Code generated by command: go run gen.go -out ../seqdec.s -arch amd64,arm64 -pkg=zstd. DO NOT EDIT.
//go:build !appengine && !noasm && gc && !noasm
+70
View File
@@ -0,0 +1,70 @@
//go:build arm64 && !appengine && !noasm && gc
package zstd
// The shared decode/decodeSync/executeSimple wrappers and context structs live
// in seqdec_asm.go; this file only declares the arm64 asm routines (generated
// by the avo arm64 lowering printer) and the dispatch helpers. arm64 has no
// BMI2, so each helper selects only between the 56-bit / safe variants.
// sequenceDecs_decode_arm64 implements the main loop of sequenceDecs in arm64 asm.
//
// Please refer to seqdec_generic.go for the reference implementation.
//
//go:noescape
func sequenceDecs_decode_arm64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// sequenceDecs_decode_56_arm64 implements the main loop of sequenceDecs in arm64 asm.
//
//go:noescape
func sequenceDecs_decode_56_arm64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int
// decodeAsm runs the sequenceDecs decode loop, choosing the 56-bit variant.
func decodeAsm(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext, lte56bits bool) int {
if lte56bits {
return sequenceDecs_decode_56_arm64(s, br, ctx)
}
return sequenceDecs_decode_arm64(s, br, ctx)
}
// sequenceDecs_decodeSync_arm64 implements the main loop of sequenceDecs.decodeSync in arm64 asm.
//
// Please refer to seqdec_generic.go for the reference implementation.
//
//go:noescape
func sequenceDecs_decodeSync_arm64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int
// sequenceDecs_decodeSync_safe_arm64 does the same as above, but does not write more than output buffer.
//
//go:noescape
func sequenceDecs_decodeSync_safe_arm64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int
// decodeSyncAsm runs the decodeSync loop, choosing the safe variant.
func decodeSyncAsm(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext, safe bool) int {
if safe {
return sequenceDecs_decodeSync_safe_arm64(s, br, ctx)
}
return sequenceDecs_decodeSync_arm64(s, br, ctx)
}
// sequenceDecs_executeSimple_arm64 implements the main loop of sequenceDecs.executeSimple in arm64 asm.
//
// Returns false if a match offset is too big.
//
// Please refer to seqdec_generic.go for the reference implementation.
//
//go:noescape
func sequenceDecs_executeSimple_arm64(ctx *executeAsmContext) bool
// Same as above, but with safe memcopies
//
//go:noescape
func sequenceDecs_executeSimple_safe_arm64(ctx *executeAsmContext) bool
// executeSimpleAsm runs the executeSimple loop, choosing the safe variant.
func executeSimpleAsm(ctx *executeAsmContext, safe bool) bool {
if safe {
return sequenceDecs_executeSimple_safe_arm64(ctx)
}
return sequenceDecs_executeSimple_arm64(ctx)
}
File diff suppressed because it is too large. Load diff
+289
View File
@@ -0,0 +1,289 @@
//go:build (amd64 || arm64) && !appengine && !noasm && gc
package zstd
import (
"fmt"
"io"
)
// This file holds the parts of the assembly sequence decoder that are identical
// across architectures: the context structs exchanged with the asm, the error
// codes, and the decode/decodeSync/executeSimple wrappers. Each architecture
// supplies the small dispatch helpers (decodeAsm, decodeSyncAsm,
// executeSimpleAsm) that select the concrete asm routine — amd64 also chooses a
// BMI2 variant, arm64 has a single implementation.
type decodeSyncAsmContext struct {
llTable []decSymbol
mlTable []decSymbol
ofTable []decSymbol
llState uint64
mlState uint64
ofState uint64
iteration int
litRemain int
out []byte
outPosition int
literals []byte
litPosition int
history []byte
windowSize int
ll int // set on error (not for all errors, please refer to _generate/gen.go)
ml int // set on error (not for all errors, please refer to _generate/gen.go)
mo int // set on error (not for all errors, please refer to _generate/gen.go)
}
type decodeAsmContext struct {
llTable []decSymbol
mlTable []decSymbol
ofTable []decSymbol
llState uint64
mlState uint64
ofState uint64
iteration int
seqs []seqVals
litRemain int
}
type executeAsmContext struct {
seqs []seqVals
seqIndex int
out []byte
history []byte
literals []byte
outPosition int
litPosition int
windowSize int
}
const noError = 0
// error reported when mo == 0 && ml > 0
const errorMatchLenOfsMismatch = 1
// error reported when ml > maxMatchLen
const errorMatchLenTooBig = 2
// error reported when mo > available history or mo > s.windowSize
const errorMatchOffTooBig = 3
// error reported when the sum of literal lengths exeeceds the literal buffer size
const errorNotEnoughLiterals = 4
// error reported when capacity of `out` is too small
const errorNotEnoughSpace = 5
// error reported when bits are overread.
const errorOverread = 6
// decode sequences from the stream with the provided history but without a dictionary.
func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) {
if len(s.dict) > 0 {
return false, nil
}
if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSize {
return false, nil
}
// FIXME: Using unsafe memory copies leads to rare, random crashes
// with fuzz testing. It is therefore disabled for now.
const useSafe = true
br := s.br
maxBlockSize := min(s.windowSize, maxCompressedBlockSize)
ctx := decodeSyncAsmContext{
llTable: s.litLengths.fse.dt[:maxTablesize],
mlTable: s.matchLengths.fse.dt[:maxTablesize],
ofTable: s.offsets.fse.dt[:maxTablesize],
llState: uint64(s.litLengths.state.state),
mlState: uint64(s.matchLengths.state.state),
ofState: uint64(s.offsets.state.state),
iteration: s.nSeqs - 1,
litRemain: len(s.literals),
out: s.out,
outPosition: len(s.out),
literals: s.literals,
windowSize: s.windowSize,
history: hist,
}
s.seqSize = 0
startSize := len(s.out)
errCode := decodeSyncAsm(s, br, &ctx, useSafe)
switch errCode {
case noError:
break
case errorMatchLenOfsMismatch:
return true, fmt.Errorf("zero matchoff and matchlen (%d) > 0", ctx.ml)
case errorMatchLenTooBig:
return true, fmt.Errorf("match len (%d) bigger than max allowed length", ctx.ml)
case errorMatchOffTooBig:
return true, fmt.Errorf("match offset (%d) bigger than current history (%d)",
ctx.mo, ctx.outPosition+len(hist)-startSize)
case errorNotEnoughLiterals:
return true, fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available",
ctx.ll, ctx.litRemain+ctx.ll)
case errorOverread:
return true, io.ErrUnexpectedEOF
case errorNotEnoughSpace:
size := ctx.outPosition + ctx.ll + ctx.ml
if debugDecoder {
println("msl:", s.maxSyncLen, "cap", cap(s.out), "bef:", startSize, "sz:", size-startSize, "mbs:", maxBlockSize, "outsz:", cap(s.out)-startSize)
}
return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize)
default:
return true, fmt.Errorf("sequenceDecs_decode returned erroneous code %d", errCode)
}
s.seqSize += ctx.litRemain
if s.seqSize > maxBlockSize {
return true, fmt.Errorf("output bigger than max block size (%d)", maxBlockSize)
}
err := br.close()
if err != nil {
printf("Closing sequences: %v, %+v\n", err, *br)
return true, err
}
s.literals = s.literals[ctx.litPosition:]
t := ctx.outPosition
s.out = s.out[:t]
// Add final literals
s.out = append(s.out, s.literals...)
if debugDecoder {
t += len(s.literals)
if t != len(s.out) {
panic(fmt.Errorf("length mismatch, want %d, got %d", len(s.out), t))
}
}
return true, nil
}
// decode sequences from the stream without the provided history.
func (s *sequenceDecs) decode(seqs []seqVals) error {
br := s.br
maxBlockSize := min(s.windowSize, maxCompressedBlockSize)
ctx := decodeAsmContext{
llTable: s.litLengths.fse.dt[:maxTablesize],
mlTable: s.matchLengths.fse.dt[:maxTablesize],
ofTable: s.offsets.fse.dt[:maxTablesize],
llState: uint64(s.litLengths.state.state),
mlState: uint64(s.matchLengths.state.state),
ofState: uint64(s.offsets.state.state),
seqs: seqs,
iteration: len(seqs) - 1,
litRemain: len(s.literals),
}
if debugDecoder {
println("decode: decoding", len(seqs), "sequences", br.remain(), "bits remain on stream")
}
s.seqSize = 0
lte56bits := s.maxBits+s.offsets.fse.actualTableLog+s.matchLengths.fse.actualTableLog+s.litLengths.fse.actualTableLog <= 56
errCode := decodeAsm(s, br, &ctx, lte56bits)
if errCode != 0 {
i := len(seqs) - ctx.iteration - 1
switch errCode {
case errorMatchLenOfsMismatch:
ml := ctx.seqs[i].ml
return fmt.Errorf("zero matchoff and matchlen (%d) > 0", ml)
case errorMatchLenTooBig:
ml := ctx.seqs[i].ml
return fmt.Errorf("match len (%d) bigger than max allowed length", ml)
case errorNotEnoughLiterals:
ll := ctx.seqs[i].ll
return fmt.Errorf("unexpected literal count, want %d bytes, but only %d is available", ll, ctx.litRemain+ll)
case errorOverread:
return io.ErrUnexpectedEOF
}
return fmt.Errorf("sequenceDecs_decode_amd64 returned erroneous code %d", errCode)
}
if ctx.litRemain < 0 {
return fmt.Errorf("literal count is too big: total available %d, total requested %d",
len(s.literals), len(s.literals)-ctx.litRemain)
}
s.seqSize += ctx.litRemain
if s.seqSize > maxBlockSize {
return fmt.Errorf("output bigger than max block size (%d)", maxBlockSize)
}
if debugDecoder {
println("decode: ", br.remain(), "bits remain on stream. code:", errCode)
}
err := br.close()
if err != nil {
printf("Closing sequences: %v, %+v\n", err, *br)
}
return err
}
// executeSimple handles cases when dictionary is not used.
func (s *sequenceDecs) executeSimple(seqs []seqVals, hist []byte) error {
// Ensure we have enough output size...
if len(s.out)+s.seqSize+compressedBlockOverAlloc > cap(s.out) {
addBytes := s.seqSize + len(s.out) + compressedBlockOverAlloc
s.out = append(s.out, make([]byte, addBytes)...)
s.out = s.out[:len(s.out)-addBytes]
}
if debugDecoder {
printf("Execute %d seqs with literals: %d into %d bytes\n", len(seqs), len(s.literals), s.seqSize)
}
var t = len(s.out)
out := s.out[:t+s.seqSize]
ctx := executeAsmContext{
seqs: seqs,
seqIndex: 0,
out: out,
history: hist,
outPosition: t,
litPosition: 0,
literals: s.literals,
windowSize: s.windowSize,
}
// useSafe avoids overwriting the output buffer when the literals slice has
// not been allocated with the required over-allocation slack.
useSafe := cap(s.literals) < len(s.literals)+compressedBlockOverAlloc
ok := executeSimpleAsm(&ctx, useSafe)
if !ok {
return fmt.Errorf("match offset (%d) bigger than current history (%d)",
seqs[ctx.seqIndex].mo, ctx.outPosition+len(hist))
}
s.literals = s.literals[ctx.litPosition:]
t = ctx.outPosition
// Add final literals
copy(out[t:], s.literals)
if debugDecoder {
t += len(s.literals)
if t != len(out) {
panic(fmt.Errorf("length mismatch, want %d, got %d, ss: %d", len(out), t, s.seqSize))
}
}
s.out = out
return nil
}
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !amd64 || appengine || !gc || noasm
//go:build (!amd64 && !arm64) || appengine || !gc || noasm
package zstd
+4 -3
View File
@@ -334,9 +334,10 @@ func decodeSnappy(blk *blockEnc, src []byte) error {
return errUnsupportedLiteralLength
}
//if length > snappyMaxBlockSize-d || uint32(length) > len(src)-s {
// return ErrSnappyCorrupt
//}
if length > len(src)-s {
println("length > len(src)-s", length, len(src)-s)
return ErrSnappyCorrupt
}
blk.literals = append(blk.literals, src[s:s+length]...)
//println(length, "litLen")
+15
View File
@@ -0,0 +1,15 @@
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
language: en-US
reviews:
# Skip the vendored SQLite amalgamation. These files are copied verbatim from
# upstream SQLite (see the License section in README.md) and are not code that
# this project authors or reviews.
path_filters:
- "!sqlite3-binding.c"
- "!sqlite3-binding.h"
- "!sqlite3ext.h"
auto_review:
enabled: true
drafts: false
chat:
auto_reply: true
+11
View File
@@ -7,6 +7,17 @@ go-sqlite3
[![codecov](https://codecov.io/gh/mattn/go-sqlite3/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-sqlite3)
[![Go Report Card](https://goreportcard.com/badge/github.com/mattn/go-sqlite3)](https://goreportcard.com/report/github.com/mattn/go-sqlite3)
## Sponsors
This project is proudly sponsored by:
<a href="https://coderabbit.link/mattn">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://victorious-bubble-f69a016683.media.strapiapp.com/White_Typemark_79b9189d19.svg">
<img src="https://victorious-bubble-f69a016683.media.strapiapp.com/Orange_Typemark_43bf516c9d.svg" alt="CodeRabbit" width="320">
</picture>
</a>
Latest stable version is v1.14 or later, not v2.
# Description
+52 -23
View File
@@ -34,8 +34,8 @@ import (
)
//export callbackTrampoline
func callbackTrampoline(ctx *C.sqlite3_context, argc int, argv **C.sqlite3_value) {
args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:argc:argc]
func callbackTrampoline(ctx *C.sqlite3_context, argc C.int, argv **C.sqlite3_value) {
args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:int(argc):int(argc)]
fi := lookupHandle(C.sqlite3_user_data(ctx)).(*functionInfo)
fi.Call(ctx, args)
}
@@ -60,9 +60,9 @@ func compareTrampoline(handlePtr unsafe.Pointer, la C.int, a *C.char, lb C.int,
}
//export commitHookTrampoline
func commitHookTrampoline(handle unsafe.Pointer) int {
func commitHookTrampoline(handle unsafe.Pointer) C.int {
callback := lookupHandle(handle).(func() int)
return callback()
return C.int(callback())
}
//export rollbackHookTrampoline
@@ -72,23 +72,23 @@ func rollbackHookTrampoline(handle unsafe.Pointer) {
}
//export updateHookTrampoline
func updateHookTrampoline(handle unsafe.Pointer, op int, db *C.char, table *C.char, rowid int64) {
func updateHookTrampoline(handle unsafe.Pointer, op C.int, db *C.char, table *C.char, rowid int64) {
callback := lookupHandle(handle).(func(int, string, string, int64))
callback(op, C.GoString(db), C.GoString(table), rowid)
callback(int(op), C.GoString(db), C.GoString(table), rowid)
}
//export authorizerTrampoline
func authorizerTrampoline(handle unsafe.Pointer, op int, arg1 *C.char, arg2 *C.char, arg3 *C.char) int {
func authorizerTrampoline(handle unsafe.Pointer, op C.int, arg1 *C.char, arg2 *C.char, arg3 *C.char) C.int {
callback := lookupHandle(handle).(func(int, string, string, string) int)
return callback(op, C.GoString(arg1), C.GoString(arg2), C.GoString(arg3))
return C.int(callback(int(op), C.GoString(arg1), C.GoString(arg2), C.GoString(arg3)))
}
//export preUpdateHookTrampoline
func preUpdateHookTrampoline(handle unsafe.Pointer, dbHandle uintptr, op int, db *C.char, table *C.char, oldrowid int64, newrowid int64) {
func preUpdateHookTrampoline(handle unsafe.Pointer, dbHandle uintptr, op C.int, db *C.char, table *C.char, oldrowid int64, newrowid int64) {
hval := lookupHandleVal(handle)
data := SQLitePreUpdateData{
Conn: hval.db,
Op: op,
Op: int(op),
DatabaseName: C.GoString(db),
TableName: C.GoString(table),
OldRowID: oldrowid,
@@ -131,6 +131,27 @@ func lookupHandle(handle unsafe.Pointer) any {
return lookupHandleVal(handle).val
}
// deleteHandle releases a single handle created by newHandle. It is a no-op
// if the handle is unknown (e.g. already released).
func deleteHandle(handle unsafe.Pointer) {
handleLock.Lock()
defer handleLock.Unlock()
current := loadHandleVals()
if _, ok := current[handle]; !ok {
return
}
next := make(map[unsafe.Pointer]handleVal, len(current)-1)
for h, v := range current {
if h == handle {
continue
}
next[h] = v
}
handleVals.Store(next)
C.free(handle)
}
func deleteHandles(db *SQLiteConn) {
handleLock.Lock()
defer handleLock.Unlock()
@@ -260,6 +281,16 @@ func callbackArgGeneric(v *C.sqlite3_value) (reflect.Value, error) {
}
}
// callbackArgConvert returns conv as-is when the parameter type is the
// canonical type conv produces, and wraps it with a cast for named types
// (e.g. time.Duration), which reflect.Call would otherwise panic on.
func callbackArgConvert(conv callbackArgConverter, typ, canonical reflect.Type) callbackArgConverter {
if typ == canonical {
return conv
}
return callbackArgCast{conv, typ}.Run
}
func callbackArg(typ reflect.Type) (callbackArgConverter, error) {
switch typ.Kind() {
case reflect.Interface:
@@ -271,18 +302,18 @@ func callbackArg(typ reflect.Type) (callbackArgConverter, error) {
if typ.Elem().Kind() != reflect.Uint8 {
return nil, errors.New("the only supported slice type is []byte")
}
return callbackArgBytes, nil
return callbackArgConvert(callbackArgBytes, typ, reflect.TypeOf([]byte(nil))), nil
case reflect.String:
return callbackArgString, nil
return callbackArgConvert(callbackArgString, typ, reflect.TypeOf("")), nil
case reflect.Bool:
return callbackArgBool, nil
return callbackArgConvert(callbackArgBool, typ, reflect.TypeOf(false)), nil
case reflect.Int64:
return callbackArgInt64, nil
return callbackArgConvert(callbackArgInt64, typ, reflect.TypeOf(int64(0))), nil
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint:
c := callbackArgCast{callbackArgInt64, typ}
return c.Run, nil
case reflect.Float64:
return callbackArgFloat64, nil
return callbackArgConvert(callbackArgFloat64, typ, reflect.TypeOf(float64(0))), nil
case reflect.Float32:
c := callbackArgCast{callbackArgFloat64, typ}
return c.Run, nil
@@ -326,8 +357,7 @@ func callbackRetInteger(ctx *C.sqlite3_context, v reflect.Value) error {
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint:
v = v.Convert(reflect.TypeOf(int64(0)))
case reflect.Bool:
b := v.Interface().(bool)
if b {
if v.Bool() {
v = reflect.ValueOf(int64(1))
} else {
v = reflect.ValueOf(int64(0))
@@ -336,7 +366,7 @@ func callbackRetInteger(ctx *C.sqlite3_context, v reflect.Value) error {
return fmt.Errorf("cannot convert %s to INTEGER", v.Type())
}
C.sqlite3_result_int64(ctx, C.sqlite3_int64(v.Interface().(int64)))
C.sqlite3_result_int64(ctx, C.sqlite3_int64(v.Int()))
return nil
}
@@ -349,7 +379,7 @@ func callbackRetFloat(ctx *C.sqlite3_context, v reflect.Value) error {
return fmt.Errorf("cannot convert %s to FLOAT", v.Type())
}
C.sqlite3_result_double(ctx, C.double(v.Interface().(float64)))
C.sqlite3_result_double(ctx, C.double(v.Float()))
return nil
}
@@ -357,11 +387,10 @@ func callbackRetBlob(ctx *C.sqlite3_context, v reflect.Value) error {
if v.Type().Kind() != reflect.Slice || v.Type().Elem().Kind() != reflect.Uint8 {
return fmt.Errorf("cannot convert %s to BLOB", v.Type())
}
i := v.Interface()
if i == nil || len(i.([]byte)) == 0 {
bs := v.Bytes()
if len(bs) == 0 {
C.sqlite3_result_null(ctx)
} else {
bs := i.([]byte)
if i64 && len(bs) > math.MaxInt32 {
C.sqlite3_result_error_toobig(ctx)
return nil
@@ -375,7 +404,7 @@ func callbackRetText(ctx *C.sqlite3_context, v reflect.Value) error {
if v.Type().Kind() != reflect.String {
return fmt.Errorf("cannot convert %s to TEXT", v.Type())
}
s := v.Interface().(string)
s := v.String()
if i64 && len(s) > math.MaxInt32 {
C.sqlite3_result_error_toobig(ctx)
return nil
+590 -317
View File
File diff suppressed because it is too large. Load diff
+9 -7
View File
@@ -147,12 +147,12 @@ extern "C" {
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
*/
#define SQLITE_VERSION "3.53.2"
#define SQLITE_VERSION_NUMBER 3053002
#define SQLITE_SOURCE_ID "2026-06-03 19:12:13 d6e03d8c777cfa2d35e3b60d8ec3e0187f3e9f99d8e2ee9cac695fd6fcdf1a24"
#define SQLITE_VERSION "3.53.4"
#define SQLITE_VERSION_NUMBER 3053004
#define SQLITE_SOURCE_ID "2026-07-24 19:02:57 bf7c7f30031888f4e796e429ab3978879485813aaca6f641c7b33e4e09459bcc"
#define SQLITE_SCM_BRANCH "branch-3.53"
#define SQLITE_SCM_TAGS "release version-3.53.2"
#define SQLITE_SCM_DATETIME "2026-06-03T19:12:13.350Z"
#define SQLITE_SCM_TAGS "release version-3.53.4"
#define SQLITE_SCM_DATETIME "2026-07-24T19:02:57.525Z"
/*
** CAPI3REF: Run-Time Library Version Numbers
@@ -4367,7 +4367,8 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
** or in an ORDER BY or GROUP BY clause.</dd>)^
**
** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
** <dd>The maximum depth of the parse tree on any expression.</dd>)^
** <dd>The maximum depth of the parse tree on any expression and
** the maximum nesting depth for subqueries and VIEWs</dd>)^
**
** [[SQLITE_LIMIT_PARSER_DEPTH]] ^(<dt>SQLITE_LIMIT_PARSER_DEPTH</dt>
** <dd>The maximum depth of the LALR(1) parser stack used to analyze
@@ -4398,7 +4399,8 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
** <dd>The maximum index number of any [parameter] in an SQL statement.)^
**
** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
** <dd>The maximum depth of recursion for triggers.</dd>)^
** <dd>The maximum depth of recursion for triggers, and the maximum
** nesting depth for separate triggers.</dd>)^
**
** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
** <dd>The maximum number of auxiliary worker threads that a single
+87 -73
View File
@@ -445,12 +445,12 @@ type SQLiteDriver struct {
// SQLiteConn implements driver.Conn.
type SQLiteConn struct {
mu sync.Mutex
db *C.sqlite3
loc *time.Location
txlock string
funcs []*functionInfo
aggregators []*aggInfo
mu sync.Mutex
db *C.sqlite3
loc *time.Location
txlock string
funcs []*functionInfo
aggregators []*aggInfo
// Prepared-statement cache. The slice is allocated at Open with a
// fixed capacity equal to the configured cache size; cap bounds the
// cache, len is the live count, and entries are ordered LRU-first
@@ -1595,6 +1595,20 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
return nil, errors.New("sqlite succeeded without returning a database")
}
// Create connection to SQLite
conn := &SQLiteConn{db: db, loc: loc, txlock: txlock}
if stmtCacheSize > 0 {
conn.stmtCache = make([]*SQLiteStmt, 0, stmtCacheSize)
conn.stmtCacheEnabled = true
}
// fail closes the connection so no error path leaks the database
// handle or any callback handles registered on it.
fail := func(err error) (driver.Conn, error) {
conn.Close()
return nil, err
}
exec := func(s string) error {
cs := C.CString(s)
rv := C.sqlite3_exec(db, cs, nil, nil, nil)
@@ -1607,8 +1621,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// Busy timeout
if err := exec(fmt.Sprintf("PRAGMA busy_timeout = %d;", busyTimeout)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
// USER AUTHENTICATION
@@ -1633,66 +1646,59 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// NO => Continue
//
// Create connection to SQLite
conn := &SQLiteConn{db: db, loc: loc, txlock: txlock}
if stmtCacheSize > 0 {
conn.stmtCache = make([]*SQLiteStmt, 0, stmtCacheSize)
conn.stmtCacheEnabled = true
}
// Password Cipher has to be registered before authentication
if len(authCrypt) > 0 {
switch strings.ToUpper(authCrypt) {
case "SHA1":
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA1, true); err != nil {
return nil, fmt.Errorf("CryptEncoderSHA1: %s", err)
return fail(fmt.Errorf("CryptEncoderSHA1: %s", err))
}
case "SSHA1":
if len(authSalt) == 0 {
return nil, fmt.Errorf("_auth_crypt=ssha1, requires _auth_salt")
return fail(fmt.Errorf("_auth_crypt=ssha1, requires _auth_salt"))
}
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA1(authSalt), true); err != nil {
return nil, fmt.Errorf("CryptEncoderSSHA1: %s", err)
return fail(fmt.Errorf("CryptEncoderSSHA1: %s", err))
}
case "SHA256":
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA256, true); err != nil {
return nil, fmt.Errorf("CryptEncoderSHA256: %s", err)
return fail(fmt.Errorf("CryptEncoderSHA256: %s", err))
}
case "SSHA256":
if len(authSalt) == 0 {
return nil, fmt.Errorf("_auth_crypt=ssha256, requires _auth_salt")
return fail(fmt.Errorf("_auth_crypt=ssha256, requires _auth_salt"))
}
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA256(authSalt), true); err != nil {
return nil, fmt.Errorf("CryptEncoderSSHA256: %s", err)
return fail(fmt.Errorf("CryptEncoderSSHA256: %s", err))
}
case "SHA384":
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA384, true); err != nil {
return nil, fmt.Errorf("CryptEncoderSHA384: %s", err)
return fail(fmt.Errorf("CryptEncoderSHA384: %s", err))
}
case "SSHA384":
if len(authSalt) == 0 {
return nil, fmt.Errorf("_auth_crypt=ssha384, requires _auth_salt")
return fail(fmt.Errorf("_auth_crypt=ssha384, requires _auth_salt"))
}
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA384(authSalt), true); err != nil {
return nil, fmt.Errorf("CryptEncoderSSHA384: %s", err)
return fail(fmt.Errorf("CryptEncoderSSHA384: %s", err))
}
case "SHA512":
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA512, true); err != nil {
return nil, fmt.Errorf("CryptEncoderSHA512: %s", err)
return fail(fmt.Errorf("CryptEncoderSHA512: %s", err))
}
case "SSHA512":
if len(authSalt) == 0 {
return nil, fmt.Errorf("_auth_crypt=ssha512, requires _auth_salt")
return fail(fmt.Errorf("_auth_crypt=ssha512, requires _auth_salt"))
}
if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA512(authSalt), true); err != nil {
return nil, fmt.Errorf("CryptEncoderSSHA512: %s", err)
return fail(fmt.Errorf("CryptEncoderSSHA512: %s", err))
}
}
}
// Preform Authentication
if err := conn.Authenticate(authUser, authPass); err != nil {
return nil, err
return fail(err)
}
// Register: authenticate
@@ -1710,7 +1716,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// If the SQLITE_USER table is not present in the database file, then
// this interface is a harmless no-op returnning SQLITE_OK.
if err := conn.RegisterFunc("authenticate", conn.authenticate, true); err != nil {
return nil, err
return fail(err)
}
//
// Register: auth_user_add
@@ -1723,7 +1729,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// for any ATTACH-ed databases. Any call to AuthUserAdd by a
// non-admin user results in an error.
if err := conn.RegisterFunc("auth_user_add", conn.authUserAdd, true); err != nil {
return nil, err
return fail(err)
}
//
// Register: auth_user_change
@@ -1733,7 +1739,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// credentials or admin privilege setting. No user may change their own
// admin privilege setting.
if err := conn.RegisterFunc("auth_user_change", conn.authUserChange, true); err != nil {
return nil, err
return fail(err)
}
//
// Register: auth_user_delete
@@ -1743,13 +1749,13 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// the database cannot be converted into a no-authentication-required
// database.
if err := conn.RegisterFunc("auth_user_delete", conn.authUserDelete, true); err != nil {
return nil, err
return fail(err)
}
// Register: auth_enabled
// auth_enabled can be used to check if user authentication is enabled
if err := conn.RegisterFunc("auth_enabled", conn.authEnabled, true); err != nil {
return nil, err
return fail(err)
}
// Auto Vacuum
@@ -1760,8 +1766,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// and activating user authentication creates the internal table `sqlite_user`.
if autoVacuum > -1 {
if err := exec(fmt.Sprintf("PRAGMA auto_vacuum = %d;", autoVacuum)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
@@ -1771,17 +1776,17 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// has provided an username and password within the DSN.
// We are not allowed to continue.
if len(authUser) == 0 {
return nil, fmt.Errorf("Missing '_auth_user' while user authentication was requested with '_auth'")
return fail(fmt.Errorf("Missing '_auth_user' while user authentication was requested with '_auth'"))
}
if len(authPass) == 0 {
return nil, fmt.Errorf("Missing '_auth_pass' while user authentication was requested with '_auth'")
return fail(fmt.Errorf("Missing '_auth_pass' while user authentication was requested with '_auth'"))
}
// Check if User Authentication is Enabled
authExists := conn.AuthEnabled()
if !authExists {
if err := conn.AuthUserAdd(authUser, authPass, true); err != nil {
return nil, err
return fail(err)
}
}
}
@@ -1789,40 +1794,35 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// Case Sensitive LIKE
if caseSensitiveLike > -1 {
if err := exec(fmt.Sprintf("PRAGMA case_sensitive_like = %d;", caseSensitiveLike)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
// Defer Foreign Keys
if deferForeignKeys > -1 {
if err := exec(fmt.Sprintf("PRAGMA defer_foreign_keys = %d;", deferForeignKeys)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
// Foreign Keys
if foreignKeys > -1 {
if err := exec(fmt.Sprintf("PRAGMA foreign_keys = %d;", foreignKeys)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
// Ignore CHECK Constraints
if ignoreCheckConstraints > -1 {
if err := exec(fmt.Sprintf("PRAGMA ignore_check_constraints = %d;", ignoreCheckConstraints)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
// Journal Mode
if journalMode != "" {
if err := exec(fmt.Sprintf("PRAGMA journal_mode = %s;", journalMode)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
@@ -1830,23 +1830,20 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// Because the default is NORMAL and this is not changed in this package
// by using the compile time SQLITE_DEFAULT_LOCKING_MODE this PRAGMA can always be executed
if err := exec(fmt.Sprintf("PRAGMA locking_mode = %s;", lockingMode)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
// Query Only
if queryOnly > -1 {
if err := exec(fmt.Sprintf("PRAGMA query_only = %d;", queryOnly)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
// Recursive Triggers
if recursiveTriggers > -1 {
if err := exec(fmt.Sprintf("PRAGMA recursive_triggers = %d;", recursiveTriggers)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
@@ -1857,8 +1854,7 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
// you can compile with secure_delete 'ON' and disable it for a specific database connection.
if secureDelete != "DEFAULT" {
if err := exec(fmt.Sprintf("PRAGMA secure_delete = %s;", secureDelete)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
@@ -1866,37 +1862,32 @@ func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
//
// Because default is NORMAL this statement is always executed
if err := exec(fmt.Sprintf("PRAGMA synchronous = %s;", synchronousMode)); err != nil {
conn.Close()
return nil, err
return fail(err)
}
// Writable Schema
if writableSchema > -1 {
if err := exec(fmt.Sprintf("PRAGMA writable_schema = %d;", writableSchema)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
// Cache Size
if cacheSize != nil {
if err := exec(fmt.Sprintf("PRAGMA cache_size = %d;", *cacheSize)); err != nil {
C.sqlite3_close_v2(db)
return nil, err
return fail(err)
}
}
if len(d.Extensions) > 0 {
if err := conn.loadExtensions(d.Extensions); err != nil {
conn.Close()
return nil, err
return fail(err)
}
}
if d.ConnectHook != nil {
if err := d.ConnectHook(conn); err != nil {
conn.Close()
return nil, err
return fail(err)
}
}
runtime.SetFinalizer(conn, (*SQLiteConn).Close)
@@ -1970,6 +1961,10 @@ func (c *SQLiteConn) putCachedStmt(s *SQLiteStmt) bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.putCachedStmtLocked(s)
}
func (c *SQLiteConn) putCachedStmtLocked(s *SQLiteStmt) bool {
if c.db == nil {
return false
}
@@ -2164,12 +2159,20 @@ func (s *SQLiteStmt) Close() error {
s.c = nil
return nil
}
if !conn.dbConnOpen() {
if s.cacheKey != "" {
conn.mu.Lock()
if conn.db == nil {
conn.mu.Unlock()
return errors.New("sqlite statement with already closed database connection")
}
if conn.putCachedStmtLocked(s) {
conn.mu.Unlock()
return nil
}
conn.mu.Unlock()
} else if !conn.dbConnOpen() {
return errors.New("sqlite statement with already closed database connection")
}
if s.cacheKey != "" && conn.putCachedStmt(s) {
return nil
}
s.s = nil
s.c = nil
rv := C.sqlite3_finalize(stmt)
@@ -2282,6 +2285,17 @@ func stmtArgs(args []driver.NamedValue, start, na int) []driver.NamedValue {
return stmtArgs
}
// bindError converts a non-OK return code from bindValue into an error.
// The synthetic SQLITE_MISUSE returned for unsupported Go types is never
// recorded in the database handle, so lastError may report no error; fall
// back to an explicit message instead of silently ignoring the failure.
func (s *SQLiteStmt) bindError(v driver.Value) error {
if err := s.c.lastError(); err != nil {
return err
}
return fmt.Errorf("sqlite3: unsupported bind type %T", v)
}
func (s *SQLiteStmt) bind(args []driver.NamedValue) error {
rv := C._sqlite3_reset_clear(s.s)
if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
@@ -2301,7 +2315,7 @@ func (s *SQLiteStmt) bind(args []driver.NamedValue) error {
n := C.int(arg.Ordinal)
rv = bindValue(s.s, n, arg.Value)
if rv != C.SQLITE_OK {
return s.c.lastError()
return s.bindError(arg.Value)
}
}
return nil
@@ -2311,7 +2325,7 @@ func (s *SQLiteStmt) bind(args []driver.NamedValue) error {
if arg.Name == "" {
rv = bindValue(s.s, C.int(arg.Ordinal), arg.Value)
if rv != C.SQLITE_OK {
return s.c.lastError()
return s.bindError(arg.Value)
}
continue
}
@@ -2322,7 +2336,7 @@ func (s *SQLiteStmt) bind(args []driver.NamedValue) error {
}
rv = bindValue(s.s, C.int(idx), arg.Value)
if rv != C.SQLITE_OK {
return s.c.lastError()
return s.bindError(arg.Value)
}
}
}
+3 -3
View File
@@ -74,11 +74,11 @@ func (c *SQLiteConn) loadExtension(lib string, entry *string) error {
}
var errMsg *C.char
defer C.sqlite3_free(unsafe.Pointer(errMsg))
rv := C.sqlite3_load_extension(c.db, clib, centry, &errMsg)
if rv != C.SQLITE_OK {
return errors.New(C.GoString(errMsg))
err := errors.New(C.GoString(errMsg))
C.sqlite3_free(unsafe.Pointer(errMsg))
return err
}
return nil
+6 -2
View File
@@ -59,13 +59,17 @@ func (d *SQLitePreUpdateData) row(dest []any, new bool) error {
for i := 0; i < d.Count() && i < len(dest); i++ {
var val *C.sqlite3_value
var src any
var rc C.int
// Initially I tried making this just a function pointer argument, but
// it's absurdly complicated to pass C function pointers.
if new {
C.sqlite3_preupdate_new(d.Conn.db, C.int(i), &val)
rc = C.sqlite3_preupdate_new(d.Conn.db, C.int(i), &val)
} else {
C.sqlite3_preupdate_old(d.Conn.db, C.int(i), &val)
rc = C.sqlite3_preupdate_old(d.Conn.db, C.int(i), &val)
}
if rc != C.SQLITE_OK {
return Error{Code: ErrNo(rc)}
}
switch C.sqlite3_value_type(val) {
+3
View File
@@ -60,6 +60,9 @@ func (c *SQLiteConn) Deserialize(b []byte, schema string) error {
defer C.free(unsafe.Pointer(zSchema))
tmpBuf := (*C.uchar)(C.sqlite3_malloc64(C.sqlite3_uint64(len(b))))
if tmpBuf == nil && len(b) > 0 {
return fmt.Errorf("deserialize failed: out of memory")
}
copy(unsafe.Slice((*byte)(unsafe.Pointer(tmpBuf)), len(b)), b)
rc := C.sqlite3_deserialize(c.db, zSchema, tmpBuf, C.sqlite3_int64(len(b)),
+53 -6
View File
@@ -113,6 +113,9 @@ uintptr_t goVOpen(void *pVTab, char **pzErr);
static int cXOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor) {
void *vTabCursor = (void *)goVOpen(((goVTab*)pVTab)->vTab, &(pVTab->zErrMsg));
if (!vTabCursor) {
return SQLITE_ERROR;
}
goVTabCursor *pCursor = (goVTabCursor *)sqlite3_malloc(sizeof(goVTabCursor));
if (!pCursor) {
return SQLITE_NOMEM;
@@ -420,6 +423,9 @@ func goVRelease(pVTab unsafe.Pointer, isDestroy C.int) *C.char {
} else {
err = vt.vTab.Disconnect()
}
// The vtab is gone as far as SQLite is concerned regardless of the
// callback result, so release the handle either way.
deleteHandle(pVTab)
if err != nil {
return mPrintf("%s", err.Error())
}
@@ -448,6 +454,9 @@ func goVBestIndex(pVTab unsafe.Pointer, icp unsafe.Pointer) *C.char {
if err != nil {
return mPrintf("%s", err.Error())
}
if res == nil {
return mPrintf("%s", "BestIndex returned a nil IndexResult")
}
if len(res.Used) != len(csts) {
return mPrintf("Result.Used != expected value", "")
}
@@ -457,7 +466,11 @@ func goVBestIndex(pVTab unsafe.Pointer, icp unsafe.Pointer) *C.char {
slice := unsafe.Slice(info.aConstraintUsage, int(info.nConstraint))
index := 1
for i := range slice {
if res.Used[i] {
// SQLite returns "xBestIndex malfunction" when an argvIndex is
// assigned to a constraint it marked as not usable, so ignore
// Used for those; they may become usable on a later xBestIndex
// invocation for a different plan.
if res.Used[i] && csts[i].Usable {
slice[i].argvIndex = C.int(index)
slice[i].omit = C.uchar(1)
index++
@@ -479,8 +492,23 @@ func goVBestIndex(pVTab unsafe.Pointer, icp unsafe.Pointer) *C.char {
if res.AlreadyOrdered {
info.orderByConsumed = C.int(1)
}
info.estimatedCost = C.double(res.EstimatedCost)
info.estimatedRows = C.sqlite3_int64(res.EstimatedRows)
// SQLite pre-initializes estimatedCost and estimatedRows with sensible
// defaults; overwriting them with the Go zero value would make every
// candidate plan look free and break query planning, so only pass
// values the implementation actually set.
if res.EstimatedCost > 0 {
info.estimatedCost = C.double(res.EstimatedCost)
}
if res.EstimatedRows > 0 {
var rows int64
if res.EstimatedRows >= float64(math.MaxInt64) {
rows = math.MaxInt64
} else if rows = int64(res.EstimatedRows); rows < 1 {
// A positive fractional estimate must not truncate to 0.
rows = 1
}
info.estimatedRows = C.sqlite3_int64(rows)
}
return nil
}
@@ -489,6 +517,9 @@ func goVBestIndex(pVTab unsafe.Pointer, icp unsafe.Pointer) *C.char {
func goVClose(pCursor unsafe.Pointer) *C.char {
vtc := lookupHandle(pCursor).(*sqliteVTabCursor)
err := vtc.vTabCursor.Close()
// The cursor is gone as far as SQLite is concerned regardless of the
// callback result, so release the handle either way.
deleteHandle(pCursor)
if err != nil {
return mPrintf("%s", err.Error())
}
@@ -499,6 +530,7 @@ func goVClose(pCursor unsafe.Pointer) *C.char {
func goMDestroy(pClientData unsafe.Pointer) {
m := lookupHandle(pClientData).(*sqliteModule)
m.module.DestroyModule()
deleteHandle(pClientData)
}
//export goVFilter
@@ -511,7 +543,14 @@ func goVFilter(pCursor unsafe.Pointer, idxNum C.int, idxName *C.char, argc C.int
if err != nil {
return mPrintf("%s", err.Error())
}
vals = append(vals, conv.Interface())
// work around for SQLITE_NULL
x := conv.Interface()
if z, ok := x.([]byte); ok && z == nil {
x = nil
}
vals = append(vals, x)
}
err := vtc.vTabCursor.Filter(int(idxNum), C.GoString(idxName), vals)
if err != nil {
@@ -605,7 +644,15 @@ func goVUpdate(pVTab unsafe.Pointer, argc C.int, argv **C.sqlite3_value, pRowid
}
case argc > 1:
err = v.Update(vals[1], vals[2:])
// Per the xUpdate contract argv[0] identifies the row being
// updated while argv[1] is its new rowid. VTabUpdater has no
// way to convey a rowid change, so reject it instead of
// silently updating values under the old rowid.
if vals[0] != vals[1] {
err = fmt.Errorf("virtual %s table %sdoes not support changing the rowid", vt.module.name, tname)
} else {
err = v.Update(vals[0], vals[2:])
}
}
}
@@ -705,5 +752,5 @@ func (c *SQLiteConn) CreateModule(moduleName string, module Module) error {
}
return nil
}
return nil
return fmt.Errorf("sqlite3: CreateModule requires a non-nil module")
}
+84 -1
View File
@@ -194,6 +194,53 @@ func (p *Permissions) clone() *Permissions {
return clone
}
// wsCanMapCerts returns true if the websocket listener collects client
// certificates, which mqtt and leafnode connections over it need to be mapped.
func (o *Options) wsCanMapCerts() bool {
return o.Websocket.Port != 0 && o.Websocket.TLSConfig != nil &&
o.Websocket.TLSConfig.ClientAuth >= tls.RequestClientCert
}
// canTLSMap returns true if verify_and_map on any listener that uses the users
// table could select this user, which makes it a certificate identity. Cluster
// and gateway map onto their own configured user, so they do not count.
func (o *Options) canTLSMap(u *User) bool {
// The mapping lookup skips users not allowed on the connection type.
allowed := func(cts ...string) bool {
if len(u.AllowedConnectionTypes) == 0 {
return true
}
for _, ct := range cts {
if _, ok := u.AllowedConnectionTypes[ct]; ok {
return true
}
}
return false
}
// Only a listener that is started can map, and in-process connections have
// no TLS state, so they never do.
if o.TLSMap && !o.DontListen && allowed(jwt.ConnectionTypeStandard) {
return true
}
if o.Websocket.TLSMap && o.Websocket.Port != 0 && allowed(jwt.ConnectionTypeWebsocket) {
return true
}
// Mqtt over websocket maps with the mqtt listener, not the websocket one,
// but takes its certificate from the websocket transport.
if o.MQTT.TLSMap && o.MQTT.Port != 0 &&
(allowed(jwt.ConnectionTypeMqtt) ||
o.wsCanMapCerts() && allowed(jwt.ConnectionTypeMqttWS)) {
return true
}
// Leafnodes only use the users table when the leafnode block sets no
// credentials of its own, see isLeafNodeAuthorized.
return o.LeafNode.TLSMap && o.LeafNode.Port != 0 &&
o.LeafNode.Username == _EMPTY_ && o.LeafNode.Nkey == _EMPTY_ &&
len(o.LeafNode.Users) == 0 &&
(allowed(jwt.ConnectionTypeLeafnode) ||
o.wsCanMapCerts() && allowed(jwt.ConnectionTypeLeafnodeWS))
}
// checkAuthforWarnings will look for insecure settings and log concerns.
// Lock is assumed held.
func (s *Server) checkAuthforWarnings() {
@@ -205,7 +252,7 @@ func (s *Server) checkAuthforWarnings() {
for _, u := range s.users {
// Skip warn if using TLS certs based auth
// unless a password has been left in the config.
if u.Password == _EMPTY_ && opts.TLSMap {
if u.Password == _EMPTY_ && opts.canTLSMap(u) {
continue
}
// Check if this is our internal sys client created on the fly.
@@ -1164,6 +1211,13 @@ func (s *Server) processClientOrLeafAuthentication(c *client, opts *Options) (au
if proxyRequired = user.ProxyRequired; proxyRequired && !trustedProxy {
return setProxyAuthError(ErrAuthProxyRequired)
}
// A user with no password is a certificate only identity when mapping is
// enabled on another listener, so do not let comparePasswords match two
// empty passwords. The no_auth_user needs no credentials either way.
if !tlsMap && user.Password == _EMPTY_ && user.Username != noAuthUser && opts.canTLSMap(user) {
c.Debugf("User %q requires a client certificate", user.Username)
return false
}
ok = comparePasswords(user.Password, c.opts.Password)
// If we are authorized, register the user which will properly setup any permissions
// for pub/sub authorizations.
@@ -1657,15 +1711,44 @@ func validateAuth(o *Options) error {
if err := validateAllowedConnectionTypes(u.AllowedConnectionTypes); err != nil {
return err
}
if err := validatePermissionSubjects(u.Permissions); err != nil {
return fmt.Errorf("invalid permissions for user %q: %w", u.Username, err)
}
}
for _, u := range o.Nkeys {
if err := validateAllowedConnectionTypes(u.AllowedConnectionTypes); err != nil {
return err
}
if err := validatePermissionSubjects(u.Permissions); err != nil {
return fmt.Errorf("invalid permissions for nkey %q: %w", u.Nkey, err)
}
}
return validateNoAuthUser(o, o.NoAuthUser)
}
func validatePermissionSubjects(p *Permissions) error {
if p == nil {
return nil
}
if p.Publish != nil {
if err := checkPermSubjectArray(p.Publish.Allow, false); err != nil {
return fmt.Errorf("publish allow: %w", err)
}
if err := checkPermSubjectArray(p.Publish.Deny, false); err != nil {
return fmt.Errorf("publish deny: %w", err)
}
}
if p.Subscribe != nil {
if err := checkPermSubjectArray(p.Subscribe.Allow, true); err != nil {
return fmt.Errorf("subscribe allow: %w", err)
}
if err := checkPermSubjectArray(p.Subscribe.Deny, true); err != nil {
return fmt.Errorf("subscribe deny: %w", err)
}
}
return nil
}
func validateAllowedConnectionTypes(m map[string]struct{}) error {
for ct := range m {
ctuc := strings.ToUpper(ct)
+59 -22
View File
@@ -42,6 +42,22 @@ type SequenceSet struct {
// Insert will insert the sequence into the set.
// The tree will be balanced inline.
func (ss *SequenceSet) Insert(seq uint64) {
// If a node covering seq already exists, setting a bit can not change the
// tree shape, so skip the recursive descent and rebalance checks.
for n := ss.root; n != nil; {
if seq < n.base {
n = n.l
} else if seq >= n.base+numEntries {
n = n.r
} else {
n.set(seq, &ss.changed)
if ss.changed {
ss.changed = false
ss.size++
}
return
}
}
if ss.root = ss.root.insert(seq, &ss.changed, &ss.nodes); ss.changed {
ss.changed = false
ss.size++
@@ -187,17 +203,32 @@ func (ss *SequenceSet) Clone() *SequenceSet {
return css
}
// Equal returns whether the two sets contain exactly the same sequences.
func (ss *SequenceSet) Equal(other *SequenceSet) bool {
if ss.IsEmpty() || other.IsEmpty() {
return ss.IsEmpty() && other.IsEmpty()
}
if ss.size != other.size {
return false
}
// Sizes are equal, so a one-way membership check suffices.
equal := true
ss.Range(func(seq uint64) bool {
equal = other.Exists(seq)
return equal
})
return equal
}
// Union will union this SequenceSet with ssa.
func (ss *SequenceSet) Union(ssa ...*SequenceSet) {
for _, sa := range ssa {
sa.root.nodeIter(func(n *node) {
for nb, b := range n.bits {
for pos := uint64(0); b != 0; pos++ {
if b&1 == 1 {
seq := n.base + (uint64(nb) * uint64(bitsPerBucket)) + pos
ss.Insert(seq)
}
b >>= 1
base := n.base + uint64(nb)*bitsPerBucket
for b != 0 {
ss.Insert(base + uint64(bits.TrailingZeros64(b)))
b &= b - 1
}
}
})
@@ -302,8 +333,11 @@ func decodev2(buf []byte) (*SequenceSet, int, error) {
sz := int(le.Uint32(buf[index+4:]))
index += 8
expectedLen := minLen + (nn * ((numBuckets+1)*8 + 2))
if len(buf) < expectedLen {
// nn is decoded as a uint32 but held in an int. On 32-bit builds a value
// above MaxInt32 turns negative and nn*perNode below overflows, so the
// length check would pass for a short buffer and the following make/reads
// run off the end. Compare with division so the bound holds on every arch.
if nn < 0 || nn > (len(buf)-minLen)/((numBuckets+1)*8+2) {
return nil, -1, ErrBadEncoding
}
@@ -335,8 +369,9 @@ func decodev1(buf []byte) (*SequenceSet, int, error) {
const v1NumBuckets = 64
expectedLen := minLen + (nn * ((v1NumBuckets+1)*8 + 2))
if len(buf) < expectedLen {
// See decodev2: guard the node count without overflowing the multiply so
// the bound stays correct on 32-bit builds too.
if nn < 0 || nn > (len(buf)-minLen)/((v1NumBuckets+1)*8+2) {
return nil, -1, ErrBadEncoding
}
@@ -347,12 +382,9 @@ func decodev1(buf []byte) (*SequenceSet, int, error) {
for nb := uint64(0); nb < v1NumBuckets; nb++ {
n := le.Uint64(buf[index:])
// Walk all set bits and insert sequences manually for this decode from v1.
for pos := uint64(0); n != 0; pos++ {
if n&1 == 1 {
seq := base + (nb * uint64(bitsPerBucket)) + pos
ss.Insert(seq)
}
n >>= 1
for n != 0 {
ss.Insert(base + (nb * uint64(bitsPerBucket)) + uint64(bits.TrailingZeros64(n)))
n &= n - 1
}
index += 8
}
@@ -527,10 +559,13 @@ func (n *node) clear(seq uint64, deleted *bool) bool {
seq -= n.base
i := seq / bitsPerBucket
mask := uint64(1) << (seq % bitsPerBucket)
if (n.bits[i] & mask) != 0 {
n.bits[i] &^= mask
*deleted = true
if (n.bits[i] & mask) == 0 {
// Nothing cleared, and nodes in the tree are never empty,
// so no need to scan the buckets.
return false
}
n.bits[i] &^= mask
*deleted = true
for _, b := range n.bits {
if b != 0 {
return false
@@ -663,11 +698,13 @@ func (n *node) iter(f func(uint64) bool) bool {
if ok := n.l.iter(f); !ok {
return false
}
for num := n.base; num < n.base+numEntries; num++ {
if n.exists(num) {
if ok := f(num); !ok {
for i, b := range n.bits {
base := n.base + uint64(i)*bitsPerBucket
for b != 0 {
if ok := f(base + uint64(bits.TrailingZeros64(b))); !ok {
return false
}
b &= b - 1
}
}
if ok := n.r.iter(f); !ok {
+168 -49
View File
@@ -287,7 +287,7 @@ type client struct {
subs map[string]*subscription
replies map[string]*resp
mperms *msgDeny
darray []string
darray []*subscription // Parsed subscribe deny entries used to build the delivery-time filter.
pcd map[*client]struct{}
atmr *time.Timer
expires time.Time
@@ -450,15 +450,22 @@ type resp struct {
// succeed but no message sent on foo should be delivered.
type msgDeny struct {
deny *Sublist
dcache map[string]bool
dcache map[msgDenyKey]bool
}
type msgDenyKey struct {
subject string
queue string
}
// routeTarget collects information regarding routes and queue groups for
// sending information to a remote.
type routeTarget struct {
sub *subscription
qs []byte
_qs [32]byte
sub *subscription
qs []byte
qsubs []*subscription
_qs [32]byte
_qsubs [4]*subscription
}
const (
@@ -1072,6 +1079,9 @@ func (c *client) updateDefaultPermissions(perms *Permissions) bool {
func splitSubjectQueue(sq string) ([]byte, []byte, error) {
vals := strings.Fields(strings.TrimSpace(sq))
if len(vals) == 0 {
return nil, nil, fmt.Errorf("invalid subject-queue %q", sq)
}
s := []byte(vals[0])
var q []byte
if len(vals) == 2 {
@@ -1079,6 +1089,9 @@ func splitSubjectQueue(sq string) ([]byte, []byte, error) {
} else if len(vals) > 2 {
return nil, nil, fmt.Errorf("invalid subject-queue %q", sq)
}
if !IsValidSubject(vals[0]) || (len(q) > 0 && !IsValidSubject(vals[1])) {
return nil, nil, fmt.Errorf("invalid subject-queue %q", sq)
}
return s, q, nil
}
@@ -1099,15 +1112,35 @@ func (c *client) setPermissions(perms *Permissions) {
c.perms.pub.allow = NewSublist(slcache)
}
for _, pubSubject := range perms.Publish.Allow {
if !IsValidSubject(pubSubject) {
c.Errorf("invalid publish subject %q", pubSubject)
continue
}
sub := &subscription{subject: []byte(pubSubject)}
c.perms.pub.allow.Insert(sub)
if err := c.perms.pub.allow.Insert(sub); err != nil {
c.Errorf("invalid publish subject %q", pubSubject)
}
}
if len(perms.Publish.Deny) > 0 {
c.perms.pub.deny = NewSublist(slcache)
}
for _, pubSubject := range perms.Publish.Deny {
sub := &subscription{subject: []byte(pubSubject)}
c.perms.pub.deny.Insert(sub)
subject := []byte(pubSubject)
if !IsValidSubject(pubSubject) {
var err error
subject, _, err = splitSubjectQueue(pubSubject)
if err != nil {
c.Errorf("invalid publish deny subject %q", pubSubject)
continue
}
// Queue qualifiers have no meaning for publish permissions. If
// one reaches this defensive path, retain the deny's subject
// scope instead of silently creating an unreachable trie node.
c.Errorf("queue qualifier is not valid for publish deny subject %q", pubSubject)
}
if err := c.perms.pub.deny.Insert(&subscription{subject: subject}); err != nil {
c.Errorf("invalid publish deny subject %q", pubSubject)
}
}
}
@@ -1131,12 +1164,12 @@ func (c *client) setPermissions(perms *Permissions) {
c.Errorf("%s", err.Error())
continue
}
c.perms.sub.allow.Insert(sub)
if err := c.perms.sub.allow.Insert(sub); err != nil {
c.Errorf("invalid subscribe allow subject %q", subSubject)
}
}
if len(perms.Subscribe.Deny) > 0 {
c.perms.sub.deny = NewSublistNoCache()
// Also hold onto this array for later.
c.darray = perms.Subscribe.Deny
}
for _, subSubject := range perms.Subscribe.Deny {
sub := &subscription{}
@@ -1145,7 +1178,12 @@ func (c *client) setPermissions(perms *Permissions) {
c.Errorf("%s", err.Error())
continue
}
c.perms.sub.deny.Insert(sub)
if err := c.perms.sub.deny.Insert(sub); err != nil {
c.Errorf("invalid subscribe deny subject %q", subSubject)
continue
}
// Retain the parsed representation for delivery-time filtering.
c.darray = append(c.darray, sub)
}
}
@@ -1195,14 +1233,14 @@ func (c *client) publicPermissions() *Permissions {
subs := _subs[:0]
c.perms.sub.allow.All(&subs)
for _, sub := range subs {
perms.Subscribe.Allow = append(perms.Subscribe.Allow, string(sub.subject))
perms.Subscribe.Allow = append(perms.Subscribe.Allow, subjectQueueString(sub))
}
}
if c.perms.sub.deny != nil {
subs := _subs[:0]
c.perms.sub.deny.All(&subs)
for _, sub := range subs {
perms.Subscribe.Deny = append(perms.Subscribe.Deny, string(sub.subject))
perms.Subscribe.Deny = append(perms.Subscribe.Deny, subjectQueueString(sub))
}
}
// Responses.
@@ -1214,6 +1252,13 @@ func (c *client) publicPermissions() *Permissions {
return perms
}
func subjectQueueString(sub *subscription) string {
if len(sub.queue) == 0 {
return string(sub.subject)
}
return string(sub.subject) + " " + string(sub.queue)
}
type denyType int
const (
@@ -1235,37 +1280,48 @@ func (c *client) mergeDenyPermissions(what denyType, denyPubs []string) {
if c.perms.pub.deny == nil {
c.perms.pub.deny = NewSublistForServer(c.srv)
}
mergeDenyPerm(&c.perms.pub, denyPubs)
mergeDenyPerm(&c.perms.pub, denyPubs, false)
}
if what == sub || what == both {
if c.perms.sub.deny == nil {
// Avoid sublist cache contention in canSubscribe.
c.perms.sub.deny = NewSublistNoCache()
}
mergeDenyPerm(&c.perms.sub, denyPubs)
c.darray = append(c.darray, mergeDenyPerm(&c.perms.sub, denyPubs, true)...)
}
}
// mergeDenyPerm inserts new deny permissions, skipping subjects that already exist.
func mergeDenyPerm(p *perm, denyPubs []string) {
func mergeDenyPerm(p *perm, denyPubs []string, allowQueue bool) []*subscription {
var inserted []*subscription
FOR_DENY:
for _, subj := range denyPubs {
r := p.deny.Match(subj)
for _, deny := range denyPubs {
subject, queue, err := splitSubjectQueue(deny)
if err != nil {
continue
}
if !allowQueue {
queue = nil
}
r := p.deny.Match(string(subject))
for _, v := range r.qsubs {
for _, s := range v {
if string(s.subject) == subj {
if bytes.Equal(s.subject, subject) && bytes.Equal(s.queue, queue) {
continue FOR_DENY
}
}
}
for _, s := range r.psubs {
if string(s.subject) == subj {
if bytes.Equal(s.subject, subject) && len(queue) == 0 {
continue FOR_DENY
}
}
sub := &subscription{subject: []byte(subj)}
p.deny.Insert(sub)
sub := &subscription{subject: subject, queue: queue}
if p.deny.Insert(sub) == nil {
inserted = append(inserted, sub)
}
}
return inserted
}
// Merge client.perms structure with additional pub deny permissions
@@ -1301,9 +1357,9 @@ func (c *client) setExpiration(claims *jwt.ClaimsData, validFor time.Duration) {
// messages based on a deny clause for subscriptions.
// Lock should be held.
func (c *client) loadMsgDenyFilter() {
c.mperms = &msgDeny{NewSublistWithCache(), make(map[string]bool)}
c.mperms = &msgDeny{NewSublistWithCache(), make(map[msgDenyKey]bool)}
for _, sub := range c.darray {
c.mperms.deny.Insert(&subscription{subject: []byte(sub)})
c.mperms.deny.Insert(&subscription{subject: sub.subject, queue: sub.queue})
}
}
@@ -3339,21 +3395,28 @@ func (c *client) canSubscribe(subject string, optQueue ...string) bool {
if !c.canSubscribeInternal(subject, optQueue...) {
return false
}
c.loadMsgDenyFilterIfNeeded(subject, len(optQueue) > 0 && optQueue[0] != _EMPTY_)
return true
}
// Initializes the delivery-time deny filter when a wildcard subscription, or
// an exact queue subscription, can overlap a deny entry. Assumes caller is
// holding the write lock.
func (c *client) loadMsgDenyFilterIfNeeded(subject string, hasQueue bool) {
// We use the actual subscription to signal us to spin up the deny mperms
// and cache. We check if the subject is a wildcard that intersects any of
// the deny clauses.
// FIXME(dlc) - We could be smarter and track when these go away and remove.
if c.mperms == nil && subjectHasWildcard(subject) {
if c.mperms == nil && (hasQueue || subjectHasWildcard(subject)) {
// Whip through the deny array and check if this wildcard subject can
// overlap with any denied deliveries.
for _, sub := range c.darray {
if SubjectsCollide(sub, subject) {
if SubjectsCollide(bytesToString(sub.subject), subject) {
c.loadMsgDenyFilter()
break
}
}
}
return true
}
func queueMatches(queue string, qsubs [][]*subscription) bool {
@@ -3496,19 +3559,21 @@ func (c *client) processUnsub(arg []byte) error {
// presence of deny clauses for subscriptions. Deny clauses will not prevent
// larger scoped wildcard subscriptions, so we need to check at delivery time.
// Lock should be held.
func (c *client) checkDenySub(subject string) bool {
if denied, ok := c.mperms.dcache[subject]; ok {
func (c *client) checkDenySub(subject, queue string) bool {
key := msgDenyKey{subject, queue}
if denied, ok := c.mperms.dcache[key]; ok {
return denied
} else if np, _ := c.mperms.deny.NumInterest(subject); np != 0 {
c.mperms.dcache[subject] = true
return true
} else {
c.mperms.dcache[subject] = false
}
r := c.mperms.deny.Match(subject)
denied := len(r.psubs) != 0
if !denied && queue != _EMPTY_ && len(r.qsubs) != 0 {
denied = queueMatches(queue, r.qsubs)
}
c.mperms.dcache[key] = denied
if len(c.mperms.dcache) > maxDenyPermCacheSize {
c.pruneDenyCache()
}
return false
return denied
}
// Create a message header for routes or leafnodes. Header and origin cluster aware.
@@ -3691,7 +3756,7 @@ func (c *client) deliverMsg(prodIsMQTT bool, sub *subscription, acc *Account, su
client := sub.client
// Check sub client and check echo. Only do this if not a service import.
if client == nil || (c == client && !client.echo && !sub.si) {
if client == nil || (c == client && !client.echo && !sub.si && !sub.rsi) {
if client != nil && mt != nil {
client.mu.Lock()
mt.addEgressEvent(client, sub, errMsgTraceNoEcho)
@@ -3704,7 +3769,7 @@ func (c *client) deliverMsg(prodIsMQTT bool, sub *subscription, acc *Account, su
// Check if we have a subscribe deny clause. This will trigger us to check the subject
// for a match against the denied subjects.
if client.mperms != nil && client.checkDenySub(string(subject)) {
if client.mperms != nil && client.checkDenySub(string(subject), bytesToString(sub.queue)) {
mt.addEgressEvent(client, sub, errMsgTraceSubDeny)
client.mu.Unlock()
return false
@@ -4067,8 +4132,8 @@ func (c *client) pruneReplyPerms() {
// deliverMsg.
func (c *client) pruneDenyCache() {
r := 0
for subject := range c.mperms.dcache {
delete(c.mperms.dcache, subject)
for key := range c.mperms.dcache {
delete(c.mperms.dcache, key)
if r++; r > pruneSize {
break
}
@@ -5083,6 +5148,7 @@ func (c *client) addSubToRouteTargets(sub *subscription) {
if sub.queue != nil {
rt.qs = append(rt.qs, sub.queue...)
rt.qs = append(rt.qs, ' ')
rt.qsubs = append(rt.qsubs, sub)
}
return
}
@@ -5101,12 +5167,51 @@ func (c *client) addSubToRouteTargets(sub *subscription) {
rt = &c.in.rts[lrts]
rt.sub = sub
rt.qs = rt._qs[:0]
rt.qsubs = rt._qsubs[:0]
if sub.queue != nil {
rt.qs = append(rt.qs, sub.queue...)
rt.qs = append(rt.qs, ' ')
rt.qsubs = append(rt.qsubs, sub)
}
}
// Filters queue groups in a coalesced route or leaf target against the
// destination connection's delivery-time subscription denies.
func filterRouteTargetDeny(subject []byte, rt *routeTarget) bool {
dc := rt.sub.client
dc.mu.Lock()
defer dc.mu.Unlock()
if dc.mperms == nil {
return true
}
dsubject := string(subject)
if len(rt.sub.queue) == 0 {
if dc.checkDenySub(dsubject, _EMPTY_) {
return false
}
} else {
rt.sub = nil
}
qs := rt.qs[:0]
qsubs := rt.qsubs[:0]
for _, qsub := range rt.qsubs {
if dc.checkDenySub(dsubject, bytesToString(qsub.queue)) {
continue
}
if rt.sub == nil {
rt.sub = qsub
}
qs = append(qs, qsub.queue...)
qs = append(qs, ' ')
qsubs = append(qsubs, qsub)
}
rt.qs = qs
rt.qsubs = qsubs
return rt.sub != nil
}
// This processes the sublist results for a given message.
// Returns if the message was delivered to at least target and queue filters.
func (c *client) processMsgResults(acc *Account, r *SublistResult, msg, deliver, subject, reply []byte, flags int) (bool, [][]byte) {
@@ -5553,9 +5658,6 @@ func (c *client) processMsgResults(acc *Account, r *SublistResult, msg, deliver,
// We are here if we have selected a leaf or route as the destination,
// or if we tried to deliver to a local qsub but failed.
c.addSubToRouteTargets(rsub)
if flags&pmrCollectQueueNames != 0 {
queues = append(queues, rsub.queue)
}
}
}
@@ -5585,6 +5687,10 @@ sendToRoutesOrLeafs:
// We have inline structs for memory layout and cache coherency.
for i := range c.in.rts {
rt := &c.in.rts[i]
if (len(rt.qsubs) > 1 || (len(rt.sub.queue) == 0 && len(rt.qsubs) > 0)) &&
!filterRouteTargetDeny(subject, rt) {
continue
}
dc := rt.sub.client
dmsg, hset := msg, false
@@ -5617,6 +5723,11 @@ sendToRoutesOrLeafs:
mh := c.msgHeaderForRouteOrLeaf(subject, reply, rt, acc)
if c.deliverMsg(prodIsMQTT, rt.sub, acc, subject, reply, mh, dmsg, false) {
if flags&pmrCollectQueueNames != 0 {
for _, qsub := range rt.qsubs {
queues = append(queues, qsub.queue)
}
}
if rt.sub.icb == nil {
dlvMsgs++
switch dc.kind {
@@ -5999,10 +6110,13 @@ func (c *client) processSubsOnConfigReload(awcsti map[string]struct{}) {
for _, sub := range c.subs {
// Just checking to rebuild mperms under the lock, will collect removed though here.
// Only collect under subs array of canSubscribe and checkAcc true.
canSub := c.canSubscribe(string(sub.subject))
canQSub := sub.queue != nil && c.canSubscribe(string(sub.subject), string(sub.queue))
if !canSub && !canQSub {
var allowed bool
if len(sub.queue) > 0 {
allowed = c.canSubscribe(string(sub.subject), string(sub.queue))
} else {
allowed = c.canSubscribe(string(sub.subject))
}
if !allowed {
removed = append(removed, sub)
} else if checkAcc {
subs = append(subs, sub)
@@ -6025,8 +6139,13 @@ func (c *client) processSubsOnConfigReload(awcsti map[string]struct{}) {
// Unsubscribe all that need to be removed and report back to client and logs.
for _, sub := range removed {
c.unsubscribe(acc, sub, true, true)
c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q (sid %q)", sub.subject, sub.sid))
srv.Noticef("Removed sub %q (sid %q) for %s - not authorized", sub.subject, sub.sid, c.getAuthUser())
if len(sub.queue) > 0 {
c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q using queue %q (sid %q)", sub.subject, sub.queue, sub.sid))
srv.Noticef("Removed sub %q using queue %q (sid %q) for %s - not authorized", sub.subject, sub.queue, sub.sid, c.getAuthUser())
} else {
c.sendErr(fmt.Sprintf("Permissions Violation for Subscription to %q (sid %q)", sub.subject, sub.sid))
srv.Noticef("Removed sub %q (sid %q) for %s - not authorized", sub.subject, sub.sid, c.getAuthUser())
}
}
}
+1 -1
View File
@@ -66,7 +66,7 @@ func init() {
const (
// VERSION is the current version for the server.
VERSION = "2.14.3"
VERSION = "2.14.4"
// PROTO is the currently supported protocol.
// 0 was the original
+113 -104
View File
@@ -502,6 +502,7 @@ type consumer struct {
// Clustered.
ca *consumerAssignment
node RaftNode
term uint64 // Raft term, used to determine if we are still the leader for the current term (if applicable, 0 otherwise).
infoSub *subscription
lqsent time.Time
prm map[string]struct{}
@@ -1435,7 +1436,7 @@ func (mset *stream) addConsumerWithAssignment(config *ConsumerConfig, oname stri
o.resetStartingSeq(0, _EMPTY_, false)
}
if config.Direct || standalone {
o.setLeader(true)
o.setLeader(true, 0)
}
// This is always true in single server mode.
@@ -1602,18 +1603,112 @@ func (o *consumer) isLeader() bool {
return o.leader.Load()
}
func (o *consumer) setLeader(isLeader bool) error {
o.mu.RLock()
func (o *consumer) setLeader(isLeader bool, term uint64) error {
o.mu.Lock()
mset, closed := o.mset, o.closed
movingToClustered := o.node != nil && o.pch == nil
movingToNonClustered := o.node == nil && o.pch != nil
wasLeader := o.leader.Swap(isLeader)
// For clustered new consumers, starting seq selection was deferred from
// addConsumerWithAssignment so the scan wouldn't block the meta apply
// goroutine, run it here on leader-elect instead.
needsSelect := isLeader && !wasLeader && o.dseq == 0 && (o.store == nil || !o.store.HasState())
o.mu.RUnlock()
// We can skip the teardown if we were leader before and are still the leader now.
// But only at term 1, since that means scale up from or down to an unreplicated config.
// R1 assets have no raft node and use the coerced term 1.
if term < 1 {
term = 1
}
skipTeardown := wasLeader && isLeader && term == 1
o.term = term
if skipTeardown {
movingToClustered := o.node != nil && o.pch == nil
movingToNonClustered := o.node == nil && o.pch != nil
// If we detect we are scaling up, make sure to create clustered routines and channels.
if movingToClustered {
// We are moving from R1 to clustered.
o.pch = make(chan struct{}, 1)
go o.loopAndForwardProposals(o.node, o.qch, o.pch, term)
if o.phead != nil {
select {
case o.pch <- struct{}{}:
default:
}
}
} else if movingToNonClustered {
// We are moving from clustered to non-clustered now.
// Set pch to nil so if we scale back up we will recreate the loopAndForward from above.
pch := o.pch
o.pch = nil
select {
case pch <- struct{}{}:
default:
}
}
o.mu.Unlock()
return nil
}
// Shutdown the go routines and the subscriptions.
if o.qch != nil {
close(o.qch)
o.qch = nil
}
// Stop any inactivity timers. Should only be running on leaders.
stopAndClearTimer(&o.dtmr)
// Stop any unpause timers. Should only be running on leaders.
stopAndClearTimer(&o.uptmr)
// Make sure to clear out any re-deliver queues
o.stopAndClearPtmr()
o.rdc = nil
o.rdq = nil
o.rdqi.Empty()
o.pending = nil
o.rsm = nil
o.resetPendingDeliveries()
// Reset num pending, these are only authoritative on the leader.
o.npc, o.npf = 0, 0
// ok if they are nil, we protect inside unsubscribe()
o.unsubscribe(o.ackSubOld)
o.unsubscribe(o.ackSub)
o.unsubscribe(o.reqSub)
o.unsubscribe(o.resetSub)
o.unsubscribe(o.fcSubOld)
o.unsubscribe(o.fcSub)
o.ackSubOld, o.ackSub, o.reqSub, o.resetSub, o.fcSubOld, o.fcSub = nil, nil, nil, nil, nil, nil
if o.infoSub != nil {
o.srv.sysUnsubscribe(o.infoSub)
o.infoSub = nil
}
// Reset waiting if we are in pull mode.
if o.isPullMode() {
o.waiting = newWaitQueue(o.cfg.MaxWaiting)
o.nextMsgReqs.drain()
} else if o.srv.gateway.enabled {
stopAndClearTimer(&o.gwdtmr)
}
o.unassignPinId()
// Make sure to drain queued up acks.
o.ackMsgs.drain()
// Reset amount of acks that need to be processed.
atomic.StoreInt64(&o.awl, 0)
// Also remove any pending replies since we should not be the one to respond at this point.
o.replies = nil
// Set pch to nil, we will recreate the loopAndForwardProposals for the new term.
if pch := o.pch; pch != nil {
o.pch = nil
select {
case pch <- struct{}{}:
default:
}
}
// Clear proposals, none are valid anymore.
o.phead, o.ptail = nil, nil
o.mu.Unlock()
// If we are here we have a change in leader status.
if isLeader {
@@ -1637,35 +1732,6 @@ func (o *consumer) setLeader(isLeader bool) error {
o.mu.Unlock()
}
if wasLeader {
// If we detect we are scaling up, make sure to create clustered routines and channels.
if movingToClustered {
o.mu.Lock()
// We are moving from R1 to clustered.
o.pch = make(chan struct{}, 1)
go o.loopAndForwardProposals(o.qch)
if o.phead != nil {
select {
case o.pch <- struct{}{}:
default:
}
}
o.mu.Unlock()
} else if movingToNonClustered {
// We are moving from clustered to non-clustered now.
// Set pch to nil so if we scale back up we will recreate the loopAndForward from above.
o.mu.Lock()
pch := o.pch
o.pch = nil
select {
case pch <- struct{}{}:
default:
}
o.mu.Unlock()
}
return nil
}
mset.mu.RLock()
s, jsa, stream := mset.srv, mset.jsa, mset.getCfgName()
mset.mu.RUnlock()
@@ -1770,8 +1836,10 @@ func (o *consumer) setLeader(isLeader bool) error {
o.qch = make(chan struct{})
qch := o.qch
node := o.node
var pch chan struct{}
if node != nil && o.pch == nil {
o.pch = make(chan struct{}, 1)
pch = o.pch
}
pullMode := o.isPullMode()
o.mu.Unlock()
@@ -1811,67 +1879,16 @@ func (o *consumer) setLeader(isLeader bool) error {
}
// If we are R>1 spin up our proposal loop.
if node != nil {
if node != nil && pch != nil {
// Determine if we can send pending requests info to the group.
// They must be on server versions >= 2.7.1
o.checkAndSetPendingRequestsOk()
o.checkPendingRequests()
go func() {
setGoRoutineLabels(labels)
o.loopAndForwardProposals(qch)
o.loopAndForwardProposals(node, qch, pch, term)
}()
}
} else {
// Shutdown the go routines and the subscriptions.
o.mu.Lock()
if o.qch != nil {
close(o.qch)
o.qch = nil
}
// Stop any inactivity timers. Should only be running on leaders.
stopAndClearTimer(&o.dtmr)
// Stop any unpause timers. Should only be running on leaders.
stopAndClearTimer(&o.uptmr)
// Make sure to clear out any re-deliver queues
o.stopAndClearPtmr()
o.rdc = nil
o.rdq = nil
o.rdqi.Empty()
o.pending = nil
o.rsm = nil
o.resetPendingDeliveries()
// Reset num pending, these are only authoritative on the leader.
o.npc, o.npf = 0, 0
// ok if they are nil, we protect inside unsubscribe()
o.unsubscribe(o.ackSubOld)
o.unsubscribe(o.ackSub)
o.unsubscribe(o.reqSub)
o.unsubscribe(o.resetSub)
o.unsubscribe(o.fcSubOld)
o.unsubscribe(o.fcSub)
o.ackSubOld, o.ackSub, o.reqSub, o.resetSub, o.fcSubOld, o.fcSub = nil, nil, nil, nil, nil, nil
if o.infoSub != nil {
o.srv.sysUnsubscribe(o.infoSub)
o.infoSub = nil
}
// Reset waiting if we are in pull mode.
if o.isPullMode() {
o.waiting = newWaitQueue(o.cfg.MaxWaiting)
o.nextMsgReqs.drain()
} else if o.srv.gateway.enabled {
stopAndClearTimer(&o.gwdtmr)
}
o.unassignPinId()
// If we were the leader make sure to drain queued up acks.
if wasLeader {
o.ackMsgs.drain()
// Reset amount of acks that need to be processed.
atomic.StoreInt64(&o.awl, 0)
// Also remove any pending replies since we should not be the one to respond at this point.
o.replies = nil
}
o.mu.Unlock()
}
return nil
}
@@ -2454,6 +2471,9 @@ func (acc *Account) checkNewConsumerConfig(cfg, ncfg *ConsumerConfig) error {
if cfg.DeliverPolicy != ncfg.DeliverPolicy {
return errors.New("deliver policy can not be updated")
}
if cfg.MemoryStorage != ncfg.MemoryStorage {
return errors.New("storage type can not be updated")
}
if cfg.OptStartSeq != ncfg.OptStartSeq {
return errors.New("start sequence can not be updated")
}
@@ -2893,25 +2913,14 @@ func (o *consumer) resetLocalStartingSeq(seq uint64) {
o.ldt, o.lat = time.Time{}, time.Time{}
}
func (o *consumer) loopAndForwardProposals(qch chan struct{}) {
// On exit make sure we nil out pch.
defer func() {
o.mu.Lock()
o.pch = nil
o.mu.Unlock()
}()
o.mu.RLock()
node, pch := o.node, o.pch
o.mu.RUnlock()
if node == nil || pch == nil {
func (o *consumer) loopAndForwardProposals(node RaftNode, qch, pch chan struct{}, term uint64) {
if node == nil || qch == nil || pch == nil {
return
}
forwardProposals := func() error {
o.mu.Lock()
if o.node == nil || !o.node.Leader() {
if node == nil || !node.Leader() || o.term != term {
o.mu.Unlock()
return errors.New("no longer leader")
}
@@ -2925,14 +2934,14 @@ func (o *consumer) loopAndForwardProposals(qch chan struct{}) {
entries = append(entries, newEntry(EntryNormal, proposal.data))
sz += len(proposal.data)
if sz > maxBatch {
node.ProposeMulti(entries)
node.ProposeMulti(term, entries)
// We need to re-create `entries` because there is a reference
// to it in the node's pae map.
sz, entries = 0, nil
}
}
if len(entries) > 0 {
node.ProposeMulti(entries)
node.ProposeMulti(term, entries)
}
return nil
}
+85
View File
@@ -0,0 +1,85 @@
// Copyright 2026 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"sync/atomic"
"time"
)
const defaultConcurrentIOs = 4096
const minConcurrentIOs = 4
const maxConcurrentIOs = 8192
// Used to limit number of disk IO calls in flight since they could all be blocking an OS thread.
// https://github.com/nats-io/nats-server/issues/2742
type diskIOSemaphore struct {
ch chan struct{}
waiters atomic.Int64
waits atomic.Uint64
waitNanos atomic.Uint64
maxWaitNanos atomic.Uint64
}
func newDiskIOSemaphore(n int) *diskIOSemaphore {
n = max(minConcurrentIOs, min(n, maxConcurrentIOs))
d := &diskIOSemaphore{ch: make(chan struct{}, n)}
for range n {
d.ch <- struct{}{}
}
return d
}
func defaultDiskIOSemaphore() *diskIOSemaphore {
// The disk IO semaphore used to be sized based on the number
// of CPU cores. That policy led to poor use of devices that
// can handle many requests in parallel, so simply cap the
// number of concurrent IO requests handed to the Go runtime.
return newDiskIOSemaphore(defaultConcurrentIOs)
}
func (d *diskIOSemaphore) acquire() {
select {
case <-d.ch:
return
default:
// No slot available, count this
// waiter before blocking.
d.waiters.Add(1)
start := time.Now()
<-d.ch
waited := time.Since(start)
d.waiters.Add(-1)
d.countWait(uint64(waited.Nanoseconds()))
}
}
func (d *diskIOSemaphore) countWait(ns uint64) {
d.waits.Add(1)
d.waitNanos.Add(ns)
for {
cur := d.maxWaitNanos.Load()
if ns <= cur || d.maxWaitNanos.CompareAndSwap(cur, ns) {
return
}
}
}
func (d *diskIOSemaphore) release() {
d.ch <- struct{}{}
}
func (d *diskIOSemaphore) cap() int {
return cap(d.ch)
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -716,7 +716,7 @@ func (s *Server) disableJetStream(deleteState bool) error {
func (s *Server) enableJetStreamAccounts() error {
// Reuse the same task workers across all accounts, so that we don't explode
// with a large number of goroutines on multi-account systems.
tq := parallelTaskQueue(len(dios))
tq := parallelTaskQueue(min(64, s.diskIOSemaphore().cap()))
defer close(tq)
// If we have no configured accounts setup then setup imports on global account.
+13 -7
View File
@@ -2925,7 +2925,7 @@ func (s *Server) jsLeaderAccountPurgeRequest(sub *subscription, c *client, _ *Ac
for osa := range js.streamAssignmentsOrInflightSeq(accName) {
for oca := range js.consumerAssignmentsOrInflightSeq(accName, osa.Config.Name) {
ca := &consumerAssignment{Group: oca.Group, Stream: oca.Stream, Name: oca.Name, Config: oca.Config, Subject: subject, Client: oca.Client, Created: oca.Created}
if err = meta.Propose(encodeDeleteConsumerAssignment(ca)); err != nil {
if err = meta.Propose(cc.term, encodeDeleteConsumerAssignment(ca)); err != nil {
js.mu.Unlock()
resp.Error = NewJSStreamGeneralError(err)
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp))
@@ -2935,7 +2935,7 @@ func (s *Server) jsLeaderAccountPurgeRequest(sub *subscription, c *client, _ *Ac
nc++
}
sa := &streamAssignment{Group: osa.Group, Config: osa.Config, Subject: subject, Client: osa.Client, Created: osa.Created}
if err = meta.Propose(encodeDeleteStreamAssignment(sa)); err != nil {
if err = meta.Propose(cc.term, encodeDeleteStreamAssignment(sa)); err != nil {
js.mu.Unlock()
resp.Error = NewJSStreamGeneralError(err)
s.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp))
@@ -4186,7 +4186,7 @@ func (s *Server) jsStreamSnapshotRequest(sub *subscription, c *client, _ *Accoun
s.sendAPIErrResponse(ci, acc, subject, reply, smsg, s.jsonResponse(&resp))
return
}
if !IsValidSubject(req.DeliverSubject) {
if !IsValidPublishSubject(req.DeliverSubject) {
resp.Error = NewJSSnapshotDeliverSubjectInvalidError()
s.sendAPIErrResponse(ci, acc, subject, reply, smsg, s.jsonResponse(&resp))
return
@@ -4230,7 +4230,10 @@ func (s *Server) jsStreamSnapshotRequest(sub *subscription, c *client, _ *Accoun
})
// Now do the real streaming.
s.streamSnapshot(acc, mset, sr, &req)
if err := s.streamSnapshot(acc, mset, sr, &req); err != nil {
s.Warnf("Snapshot of stream '%s > %s' failed: %v", mset.jsa.account.Name, mset.name(), err)
return
}
end := time.Now().UTC()
@@ -4263,7 +4266,7 @@ const defaultSnapshotAckTimeout = 5 * time.Second
var snapshotAckTimeout = defaultSnapshotAckTimeout
// streamSnapshot will stream out our snapshot to the reply subject.
func (s *Server) streamSnapshot(acc *Account, mset *stream, sr *SnapshotResult, req *JSApiStreamSnapshotRequest) {
func (s *Server) streamSnapshot(acc *Account, mset *stream, sr *SnapshotResult, req *JSApiStreamSnapshotRequest) error {
chunkSize, wndSize := req.ChunkSize, req.WindowSize
if chunkSize == 0 {
chunkSize = defaultSnapshotChunkSize
@@ -4288,7 +4291,9 @@ func (s *Server) streamSnapshot(acc *Account, mset *stream, sr *SnapshotResult,
// Check interest for the snapshot deliver subject.
inch := make(chan bool, 1)
acc.sl.RegisterNotification(req.DeliverSubject, inch)
if err := acc.sl.RegisterNotification(req.DeliverSubject, inch); err != nil {
return fmt.Errorf("could not register snapshot delivery interest for %q: %w", req.DeliverSubject, err)
}
defer acc.sl.ClearNotification(req.DeliverSubject, inch)
hasInterest := <-inch
if !hasInterest {
@@ -4356,6 +4361,7 @@ func (s *Server) streamSnapshot(acc *Account, mset *stream, sr *SnapshotResult,
done:
mset.outq.send(newJSPubMsg(reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0))
return nil
}
// For determining consumer request type.
@@ -5287,7 +5293,7 @@ func (s *Server) jsConsumerPauseRequest(sub *subscription, c *client, _ *Account
setStaticConsumerMetadata(nca.Config)
eca := encodeAddConsumerAssignment(nca)
if err = meta.Propose(eca); err != nil {
if err = meta.Propose(cc.term, eca); err != nil {
js.mu.Unlock()
return
}
+11 -5
View File
@@ -130,8 +130,8 @@ func getBatchStoreDir(storeDir, streamName, batchId string) (string, string) {
func newBatchStore(mset *stream, batchId string, replicas int, storage StorageType, storeDir, streamName string) (StreamStore, error) {
if replicas == 1 && storage == FileStorage {
bname, storeDir := getBatchStoreDir(storeDir, streamName, batchId)
fcfg := FileStoreConfig{AsyncFlush: true, BlockSize: defaultLargeBlockSize, StoreDir: storeDir}
s := mset.srv
fcfg := FileStoreConfig{AsyncFlush: true, BlockSize: defaultLargeBlockSize, StoreDir: storeDir, srv: s}
prf := s.jsKeyGen(s.getOpts().JetStreamKey, mset.acc.Name)
if prf != nil {
// We are encrypted here, fill in correct cipher selection.
@@ -546,6 +546,12 @@ func checkMsgHeadersPreClusteredProposal(
var incr *big.Int
var hasSchedule bool
// Do this before staging any proposal state. All clustered publish paths,
// including atomic and fast batches, use this helper.
if mset.store.Type() == FileStorage && isFileStoreMsgTooLarge(fileStoreMsgSize(subject, hdr, msg)) {
return hdr, msg, 0, NewJSStreamStoreFailedError(ErrMsgTooLarge), ErrMsgTooLarge
}
// Some header checks must be checked pre proposal.
if len(hdr) > 0 {
// Since we encode header len as u16 make sure we do not exceed.
@@ -689,7 +695,7 @@ func checkMsgHeadersPreClusteredProposal(
if sources == nil {
sources = map[string]map[string]string{}
}
if _, ok = sources[origStream]; !ok {
if sources[origStream] == nil {
sources[origStream] = map[string]string{}
}
prevVal := sources[origStream][origSubj]
@@ -758,7 +764,7 @@ func checkMsgHeadersPreClusteredProposal(
// Allow override of the subject used for the check.
seqSubj := subject
if optSubj := getExpectedLastSeqPerSubjectForSubject(hdr); optSubj != _EMPTY_ {
seqSubj = optSubj
seqSubj = copyString(optSubj)
}
// The subject is already written to in this batch, we can't allow
@@ -1071,11 +1077,11 @@ func recalculateClusteredSeq(mset *stream, needStreamLock bool) (lseq uint64) {
// mset.clMu lock must be held.
func commitSingleMsg(
diff *batchStagedDiff, mset *stream, subject string, reply string, hdr []byte, msg []byte, name string,
jsa *jsAccount, mt *msgTrace, node RaftNode, replicas int, lseq uint64,
jsa *jsAccount, mt *msgTrace, node RaftNode, term uint64, replicas int, lseq uint64,
) error {
// Do proposal.
esm := encodeStreamMsgAllowCompress(subject, reply, hdr, msg, mset.clseq, time.Now().UnixNano(), false)
if err := node.Propose(esm); err != nil {
if err := node.Propose(term, esm); err != nil {
return err
}
+148 -84
View File
@@ -60,6 +60,8 @@ type jetStreamCluster struct {
// Holds a map of a peer ID to the reply subject, to only respond after gaining
// quorum on the peer-remove action.
peerRemoveReply map[string]peerRemoveInfo
// Raft term, used to determine if we are still the leader for the current term.
term uint64
// Signals meta-leader should check the stream assignments.
streamsCheck bool
// Server.
@@ -1038,7 +1040,7 @@ func (js *jetStream) setupMetaGroup() error {
cfg.Observer = s.canExtendOtherDomain() && s.getOpts().JetStreamExtHint != jsNoExtend
var bootstrap bool
if ps, err := readPeerState(storeDir); err != nil {
if ps, err := readPeerState(s.diskIOSemaphore(), storeDir); err != nil {
s.Noticef("JetStream cluster bootstrapping")
bootstrap = true
peers := s.ActivePeers()
@@ -1072,7 +1074,7 @@ func (js *jetStream) setupMetaGroup() error {
// To track possible configuration changes, responsible for an altered value of cfg.Observer,
// set extension state to undetermined.
ps.domainExt = extUndetermined
if err := writePeerState(storeDir, ps); err != nil {
if err := writePeerState(s.diskIOSemaphore(), storeDir, ps); err != nil {
return err
}
}
@@ -1916,9 +1918,10 @@ func (js *jetStream) monitorCluster() {
}
aq.recycle(&ces)
case isLeader = <-lch:
case lc := <-lch:
isLeader = lc.isLeader
// Process the change.
js.processLeaderChange(isLeader)
js.processLeaderChange(isLeader, lc.term)
if isLeader {
s.sendInternalMsgLocked(serverStatsPingReqSubj, _EMPTY_, nil, nil)
// Install a snapshot as we become leader.
@@ -2013,10 +2016,12 @@ type writeableStreamAssignment struct {
Consumers []*writeableConsumerAssignment
}
// Returns the stream config as registered in the meta layer, from an inflight
// proposal that has not been applied yet, or from an applied assignment otherwise.
func (js *jetStream) clusterStreamConfig(accName, streamName string) (StreamConfig, bool) {
js.mu.RLock()
defer js.mu.RUnlock()
if sa, ok := js.cluster.streams[accName][streamName]; ok {
if sa := js.streamAssignmentOrInflight(accName, streamName); sa != nil {
return *sa.Config, true
}
return StreamConfig{}, false
@@ -2044,7 +2049,12 @@ func (js *jetStream) applyMetaSnapshot(buf []byte, ru *recoveryUpdates, isRecove
nasa := streams[account]
for sn, sa := range asa {
if nsa := nasa[sn]; nsa == nil {
// Stream was removed.
saDel = append(saDel, sa)
} else if !nsa.Created.Equal(sa.Created) {
// Stream was recreated.
saDel = append(saDel, sa)
saAdd = append(saAdd, nsa)
} else {
saChk = append(saChk, nsa)
}
@@ -2069,10 +2079,10 @@ func (js *jetStream) applyMetaSnapshot(buf []byte, ru *recoveryUpdates, isRecove
}
if osa := js.streamAssignment(sa.Client.serviceAccount(), sa.Config.Name); osa != nil {
for _, ca := range osa.consumers {
// Consumer was either removed, or recreated with a different raft group.
// Consumer was either removed or recreated.
if nca := sa.consumers[ca.Name]; nca == nil {
caDel = append(caDel, ca)
} else if nca.Group != nil && ca.Group != nil && nca.Group.Name != ca.Group.Name {
} else if !nca.Created.Equal(ca.Created) {
caDel = append(caDel, ca)
}
}
@@ -2330,6 +2340,9 @@ func (js *jetStream) collectStreamAndConsumerChanges(c RaftNodeCheckpoint, strea
for _, e := range ae.entries {
if e.Type == EntryNormal {
buf := e.Data
if len(buf) == 0 {
return errBadEntryOp
}
op := entryOp(buf[0])
switch op {
case assignStreamOp, updateStreamOp, removeStreamOp:
@@ -2497,7 +2510,7 @@ func (js *jetStream) processAddPeer(peer string) {
csa := sa.copyGroup()
csa.Group.Peers = append(csa.Group.Peers, peer)
// Send our proposal for this csa. Also use same group definition for all the consumers as well.
if err := cc.meta.Propose(encodeAddStreamAssignment(csa)); err != nil {
if err := cc.meta.Propose(cc.term, encodeAddStreamAssignment(csa)); err != nil {
return
}
cc.trackInflightStreamProposal(accName, csa, false)
@@ -2509,7 +2522,7 @@ func (js *jetStream) processAddPeer(peer string) {
if ca.Config.Durable != _EMPTY_ || len(ca.Group.Peers) > 1 {
cca := ca.copyGroup()
cca.Group.Peers = csa.Group.Peers
if err := cc.meta.Propose(encodeAddConsumerAssignment(cca)); err != nil {
if err := cc.meta.Propose(cc.term, encodeAddConsumerAssignment(cca)); err != nil {
return
}
cc.trackInflightConsumerProposal(accName, csa.Config.Name, cca, false)
@@ -2596,7 +2609,7 @@ func (js *jetStream) removePeerFromStreamLocked(sa *streamAssignment, peer strin
}
// Send our proposal for this csa. Also use same group definition for all the consumers as well.
if err := cc.meta.Propose(encodeAddStreamAssignment(csa)); err != nil {
if err := cc.meta.Propose(cc.term, encodeAddStreamAssignment(csa)); err != nil {
return false
}
cc.trackInflightStreamProposal(accName, csa, false)
@@ -2609,13 +2622,13 @@ func (js *jetStream) removePeerFromStreamLocked(sa *streamAssignment, peer strin
if ca.Config.Durable != _EMPTY_ {
cca := ca.copyGroup()
cca.Group.Peers, cca.Group.Preferred = rg.Peers, _EMPTY_
if err := cc.meta.Propose(encodeAddConsumerAssignment(cca)); err != nil {
if err := cc.meta.Propose(cc.term, encodeAddConsumerAssignment(cca)); err != nil {
return false
}
cc.trackInflightConsumerProposal(accName, csa.Config.Name, cca, false)
} else if ca.Group.isMember(peer) {
// These are ephemerals. Check to see if we deleted this peer.
if err := cc.meta.Propose(encodeDeleteConsumerAssignment(ca)); err != nil {
if err := cc.meta.Propose(cc.term, encodeDeleteConsumerAssignment(ca)); err != nil {
return false
}
cc.trackInflightConsumerProposal(accName, csa.Config.Name, ca, true)
@@ -2715,6 +2728,9 @@ func (js *jetStream) applyMetaEntries(entries []*Entry, ru *recoveryUpdates) (bo
}
} else {
buf := e.Data
if len(buf) == 0 {
return isRecovering, didSnap, errBadEntryOp
}
switch entryOp(buf[0]) {
case assignStreamOp:
sa, err := decodeStreamAssignment(js.srv, buf[1:])
@@ -2986,7 +3002,7 @@ retry:
cfg := &RaftConfig{Name: rgName, Store: storeDir, Log: store, Track: true, Recovering: recovering, ScaleUp: rgScaleUp}
if _, err := readPeerState(storeDir); err != nil {
if _, err := readPeerState(s.diskIOSemaphore(), storeDir); err != nil {
s.bootstrapRaftNode(cfg, rgPeers, true)
}
@@ -3500,9 +3516,10 @@ func (js *jetStream) monitorStream(mset *stream, sa *streamAssignment, sendSnaps
doSnapshot(false)
}
case isLeader = <-lch:
case lc := <-lch:
isLeader = lc.isLeader
// Process our leader change.
js.processStreamLeaderChange(mset, isLeader)
js.processStreamLeaderChange(mset, isLeader, lc.term)
if isLeader {
if mset != nil && n != nil && sendSnapshot && !isRecovering {
@@ -3677,10 +3694,12 @@ func (js *jetStream) monitorStream(mset *stream, sa *streamAssignment, sendSnaps
return
}
// Trigger the stream followers to catchup.
var term uint64
if n = mset.raftNode(); n != nil {
n.SendSnapshot(mset.stateSnapshot())
term = n.Term()
}
js.processStreamLeaderChange(mset, isLeader)
js.processStreamLeaderChange(mset, isLeader, term)
// Check to see if we have restored consumers here.
// These are not currently assigned so we will need to do so here.
@@ -3695,7 +3714,12 @@ func (js *jetStream) monitorStream(mset *stream, sa *streamAssignment, sendSnaps
}
for _, o := range consumers {
name, cfg := o.String(), o.config()
rg := cc.createGroupForConsumer(&cfg, sa)
rg, err := cc.createGroupForConsumer(&cfg, sa)
if err != nil {
s.Warnf("Could not create group for consumer '%s > %s > %s': %v",
sa.Client.serviceAccount(), sa.Config.Name, name, err)
continue
}
// Pick a preferred leader.
rg.setPreferred(s)
@@ -3986,6 +4010,9 @@ func (js *jetStream) applyStreamEntries(mset *stream, ce *CommittedEntry, isReco
}
if e.Type == EntryNormal {
if len(e.Data) == 0 {
return 0, errBadEntryOp
}
buf, op := e.Data, entryOp(e.Data[0])
if op == batchMsgOp {
batchId, batchSeq, _, _, err := decodeBatchMsg(buf[1:])
@@ -4648,7 +4675,7 @@ func (s *Server) replicas(node RaftNode) []*PeerInfo {
}
// Process a leader change for the clustered stream.
func (js *jetStream) processStreamLeaderChange(mset *stream, isLeader bool) {
func (js *jetStream) processStreamLeaderChange(mset *stream, isLeader bool, term uint64) {
if mset == nil {
return
}
@@ -4719,7 +4746,7 @@ func (js *jetStream) processStreamLeaderChange(mset *stream, isLeader bool) {
}
// Tell stream to switch leader status.
mset.setLeader(isLeader)
mset.setLeader(isLeader, term)
if !isLeader || hasResponded {
return
@@ -5303,7 +5330,7 @@ func (js *jetStream) processClusterUpdateStream(acc *Account, osa, sa *streamAss
// If the stream is scaled down, there is a chance we weren't already the leader.
if isLeader && numReplicas == 1 && oldNumReplicas > 1 {
js.processStreamLeaderChange(mset, true)
js.processStreamLeaderChange(mset, true, 0)
}
// Check for missing syncSubject bug.
@@ -5564,7 +5591,7 @@ func (js *jetStream) processClusterCreateStream(acc *Account, sa *streamAssignme
s.sendInternalMsgLocked(streamAssignmentSubj, _EMPTY_, nil, b)
return
}
js.processStreamLeaderChange(mset, true)
js.processStreamLeaderChange(mset, true, 0)
// Check to see if we have restored consumers here.
// These are not currently assigned so we will need to do so here.
@@ -5581,7 +5608,12 @@ func (js *jetStream) processClusterCreateStream(acc *Account, sa *streamAssignme
for _, o := range consumers {
name, cfg := o.String(), o.config()
rg := cc.createGroupForConsumer(&cfg, sa)
rg, err := cc.createGroupForConsumer(&cfg, sa)
if err != nil {
s.Warnf("Could not create group for consumer '%s > %s > %s': %v",
sa.Client.serviceAccount(), sa.Config.Name, name, err)
continue
}
// Place our initial state here as well for assignment distribution.
ca := &consumerAssignment{
@@ -5623,7 +5655,7 @@ func (js *jetStream) processClusterCreateStream(acc *Account, sa *streamAssignme
}
})
} else {
js.processStreamLeaderChange(mset, true)
js.processStreamLeaderChange(mset, true, 0)
}
}
}
@@ -6220,7 +6252,7 @@ func (js *jetStream) processClusterCreateConsumer(oca, ca *consumerAssignment, s
func() {
defer s.grWG.Done()
defer o.clearMonitorRunning()
err = o.setLeader(true)
err = o.setLeader(true, 0)
var resp = JSApiConsumerCreateResponse{ApiResponse: ApiResponse{Type: JSApiConsumerCreateResponseType}}
if err != nil {
resp.Error = NewJSConsumerCreateError(err, Unless(err))
@@ -6260,7 +6292,7 @@ func (js *jetStream) processClusterCreateConsumer(oca, ca *consumerAssignment, s
func() {
defer s.grWG.Done()
defer o.clearMonitorRunning()
js.processConsumerLeaderChangeWithAssignment(o, cca, true)
js.processConsumerLeaderChangeWithAssignment(o, cca, true, 0)
},
pprofLabels{
"type": "consumer",
@@ -6695,13 +6727,14 @@ func (js *jetStream) monitorConsumer(o *consumer, ca *consumerAssignment) {
}
aq.recycle(&ces)
case isLeader = <-lch:
case lc := <-lch:
isLeader = lc.isLeader
if recovering && !isLeader {
js.setConsumerAssignmentRecovering(ca)
}
// Process the change.
if err := js.processConsumerLeaderChange(o, isLeader); err == nil {
if err := js.processConsumerLeaderChange(o, isLeader, lc.term); err == nil {
// Check our state if we are under an interest based stream.
if mset := o.getStream(); mset != nil {
var ss StreamState
@@ -6900,6 +6933,9 @@ func (js *jetStream) applyConsumerEntries(o *consumer, ce *CommittedEntry, isLea
// Ignore for now.
} else {
buf := e.Data
if len(buf) == 0 {
return errBadEntryOp
}
switch entryOp(buf[0]) {
case updateDeliveredOp:
dseq, sseq, dc, ts, err := decodeDeliveredUpdate(buf[1:])
@@ -6950,9 +6986,11 @@ func (js *jetStream) applyConsumerEntries(o *consumer, ce *CommittedEntry, isLea
return err
}
case updateSkipOp:
sseq, err := decodeSkipUpdate(buf[1:])
if err != nil {
return err
}
o.mu.Lock()
var le = binary.LittleEndian
sseq := le.Uint64(buf[1:])
if !o.isLeader() && sseq > o.sseq {
o.sseq = sseq
}
@@ -6964,10 +7002,11 @@ func (js *jetStream) applyConsumerEntries(o *consumer, ce *CommittedEntry, isLea
}
o.mu.Unlock()
case resetSeqOp:
sseq, reply, err := decodeResetUpdate(buf[1:])
if err != nil {
return err
}
o.mu.Lock()
var le = binary.LittleEndian
sseq := le.Uint64(buf[1:9])
reply := string(buf[9:])
o.resetLocalStartingSeq(sseq)
if o.store != nil {
o.store.Reset(sseq - 1)
@@ -7086,16 +7125,19 @@ func (o *consumer) processReplicatedAck(dseq, sseq uint64) error {
return nil
}
var errBadEntryOp = errors.New("jetstream cluster bad replicated entry")
var errBadAckUpdate = errors.New("jetstream cluster bad replicated ack update")
var errBadDeliveredUpdate = errors.New("jetstream cluster bad replicated delivered update")
var errBadSkipUpdate = errors.New("jetstream cluster bad replicated skip update")
var errBadResetUpdate = errors.New("jetstream cluster bad replicated reset update")
func decodeAckUpdate(buf []byte) (dseq, sseq uint64, err error) {
var bi, n int
if dseq, n = binary.Uvarint(buf); n < 0 {
if dseq, n = binary.Uvarint(buf); n <= 0 {
return 0, 0, errBadAckUpdate
}
bi += n
if sseq, n = binary.Uvarint(buf[bi:]); n < 0 {
if sseq, n = binary.Uvarint(buf[bi:]); n <= 0 {
return 0, 0, errBadAckUpdate
}
return dseq, sseq, nil
@@ -7103,29 +7145,43 @@ func decodeAckUpdate(buf []byte) (dseq, sseq uint64, err error) {
func decodeDeliveredUpdate(buf []byte) (dseq, sseq, dc uint64, ts int64, err error) {
var bi, n int
if dseq, n = binary.Uvarint(buf); n < 0 {
if dseq, n = binary.Uvarint(buf); n <= 0 {
return 0, 0, 0, 0, errBadDeliveredUpdate
}
bi += n
if sseq, n = binary.Uvarint(buf[bi:]); n < 0 {
if sseq, n = binary.Uvarint(buf[bi:]); n <= 0 {
return 0, 0, 0, 0, errBadDeliveredUpdate
}
bi += n
if dc, n = binary.Uvarint(buf[bi:]); n < 0 {
if dc, n = binary.Uvarint(buf[bi:]); n <= 0 {
return 0, 0, 0, 0, errBadDeliveredUpdate
}
bi += n
if ts, n = binary.Varint(buf[bi:]); n < 0 {
if ts, n = binary.Varint(buf[bi:]); n <= 0 {
return 0, 0, 0, 0, errBadDeliveredUpdate
}
return dseq, sseq, dc, ts, nil
}
func (js *jetStream) processConsumerLeaderChange(o *consumer, isLeader bool) error {
return js.processConsumerLeaderChangeWithAssignment(o, nil, isLeader)
func decodeSkipUpdate(buf []byte) (sseq uint64, err error) {
if len(buf) < 8 {
return 0, errBadSkipUpdate
}
return binary.LittleEndian.Uint64(buf), nil
}
func (js *jetStream) processConsumerLeaderChangeWithAssignment(o *consumer, ca *consumerAssignment, isLeader bool) error {
func decodeResetUpdate(buf []byte) (sseq uint64, reply string, err error) {
if len(buf) < 8 {
return 0, _EMPTY_, errBadResetUpdate
}
return binary.LittleEndian.Uint64(buf[:8]), string(buf[8:]), nil
}
func (js *jetStream) processConsumerLeaderChange(o *consumer, isLeader bool, term uint64) error {
return js.processConsumerLeaderChangeWithAssignment(o, nil, isLeader, term)
}
func (js *jetStream) processConsumerLeaderChangeWithAssignment(o *consumer, ca *consumerAssignment, isLeader bool, term uint64) error {
stepDownIfLeader := func() error {
if node := o.raftNode(); node != nil && isLeader {
node.StepDown()
@@ -7173,7 +7229,7 @@ func (js *jetStream) processConsumerLeaderChangeWithAssignment(o *consumer, ca *
}
// Tell consumer to switch leader status.
if lerr := o.setLeader(isLeader); lerr != nil && err == nil {
if lerr := o.setLeader(isLeader, term); lerr != nil && err == nil {
err = lerr
}
@@ -7356,20 +7412,21 @@ func (js *jetStream) processStreamAssignmentResults(sub *subscription, c *client
// Pick a new preferred leader.
rg.setPreferred(s)
// Get rid of previous attempt.
if err := cc.meta.Propose(encodeDeleteStreamAssignment(sa)); err != nil {
if err := cc.meta.Propose(cc.term, encodeDeleteStreamAssignment(sa)); err != nil {
return
}
cc.trackInflightStreamProposal(result.Account, sa, true)
// Propose new.
sa.Group, sa.err = rg, nil
if err := cc.meta.Propose(encodeAddStreamAssignment(sa)); err != nil {
nsa := sa.copyGroup()
nsa.Group, nsa.err = rg, nil
if err := cc.meta.Propose(cc.term, encodeAddStreamAssignment(nsa)); err != nil {
return
}
cc.trackInflightStreamProposal(result.Account, sa, false)
cc.trackInflightStreamProposal(result.Account, nsa, false)
// When the new stream assignment is processed, sa.reassigning will be
// automatically set back to false. Until then, don't process any more
// assignment results.
sa.reassigning = true
nsa.reassigning = true
return
}
}
@@ -7397,7 +7454,7 @@ func (js *jetStream) processStreamAssignmentResults(sub *subscription, c *client
}
s.Warnf("Stream assignment for '%s > %s' rejected by assigned member: %v", sa.Client.serviceAccount(), sa.Config.Name, apiErr)
sa.err = NewJSClusterNotAssignedError()
if err := cc.meta.Propose(encodeDeleteStreamAssignment(sa)); err != nil {
if err := cc.meta.Propose(cc.term, encodeDeleteStreamAssignment(sa)); err != nil {
return
}
cc.trackInflightStreamProposal(result.Account, sa, true)
@@ -7535,7 +7592,7 @@ func (s *Server) sendDomainLeaderElectAdvisory() {
s.publishAdvisory(nil, JSAdvisoryDomainLeaderElected, adv)
}
func (js *jetStream) processLeaderChange(isLeader bool) {
func (js *jetStream) processLeaderChange(isLeader bool, term uint64) {
if js == nil {
return
}
@@ -7543,8 +7600,6 @@ func (js *jetStream) processLeaderChange(isLeader bool) {
if s == nil {
return
}
// Update our server atomic.
s.isMetaLeader.Store(isLeader)
if isLeader {
s.Noticef("Self is new JetStream cluster metadata leader")
@@ -7568,6 +7623,10 @@ func (js *jetStream) processLeaderChange(isLeader bool) {
js.mu.Lock()
defer js.mu.Unlock()
// Update our server atomic, while holding the lock to not race with API requests.
s.isMetaLeader.Store(isLeader)
js.cluster.term = term
// Clear replies for peer-removes.
js.cluster.peerRemoveReply = nil
@@ -7601,7 +7660,7 @@ func (js *jetStream) processLeaderChange(isLeader bool) {
s.Warnf("Stream assignment corrupt for stream '%s > %s'", acc, sa.Config.Name)
nsa := &streamAssignment{Group: sa.Group, Config: sa.Config, Subject: sa.Subject, Reply: sa.Reply, Client: sa.Client, Created: sa.Created}
nsa.Sync = syncSubjForStream()
if err := cc.meta.Propose(encodeUpdateStreamAssignment(nsa)); err != nil {
if err := cc.meta.Propose(cc.term, encodeUpdateStreamAssignment(nsa)); err != nil {
return
}
cc.trackInflightStreamProposal(acc, nsa, false)
@@ -8239,7 +8298,7 @@ func (s *Server) jsClusteredStreamRequest(ci *ClientInfo, acc *Account, subject,
}
// Sync subject for post snapshot sync.
sa := &streamAssignment{Group: rg, Sync: syncSubject, Config: cfg, Subject: subject, Reply: reply, Client: ci, Created: time.Now().UTC()}
if err := cc.meta.Propose(encodeAddStreamAssignment(sa)); err != nil {
if err := cc.meta.Propose(cc.term, encodeAddStreamAssignment(sa)); err != nil {
return
}
// On success, add this as an inflight proposal so we can apply limits
@@ -8683,14 +8742,14 @@ func (s *Server) jsClusteredStreamUpdateRequest(ci *ClientInfo, acc *Account, su
syncSubject = syncSubjForStream()
}
sa := &streamAssignment{Group: rg, Sync: syncSubject, Created: osa.Created, Config: newCfg, Subject: subject, Reply: reply, Client: ci}
if err := meta.Propose(encodeUpdateStreamAssignment(sa)); err != nil {
if err := meta.Propose(cc.term, encodeUpdateStreamAssignment(sa)); err != nil {
return
}
cc.trackInflightStreamProposal(acc.Name, sa, false)
// Process any staged consumers.
for _, ca := range consumers {
if err := meta.Propose(encodeAddConsumerAssignment(ca)); err != nil {
if err := meta.Propose(cc.term, encodeAddConsumerAssignment(ca)); err != nil {
return
}
cc.trackInflightConsumerProposal(acc.Name, sa.Config.Name, ca, false)
@@ -8719,7 +8778,7 @@ func (s *Server) jsClusteredStreamDeleteRequest(ci *ClientInfo, acc *Account, st
}
sa := &streamAssignment{Group: osa.Group, Config: osa.Config, Subject: subject, Reply: reply, Client: ci, Created: osa.Created}
if err := cc.meta.Propose(encodeDeleteStreamAssignment(sa)); err != nil {
if err := cc.meta.Propose(cc.term, encodeDeleteStreamAssignment(sa)); err != nil {
return
}
cc.trackInflightStreamProposal(acc.Name, sa, true)
@@ -8735,7 +8794,7 @@ func (s *Server) jsClusteredStreamPurgeRequest(
preq *JSApiStreamPurgeRequest,
) {
js, cc := s.getJetStreamCluster()
if js == nil || cc == nil {
if js == nil || cc == nil || mset == nil {
return
}
@@ -8750,17 +8809,16 @@ func (s *Server) jsClusteredStreamPurgeRequest(
}
if n := sa.Group.node; n != nil {
sp := &streamPurge{Stream: stream, LastSeq: mset.state().LastSeq, Subject: subject, Reply: reply, Client: ci, Request: preq}
n.Propose(encodeStreamPurge(sp))
sp := encodeStreamPurge(&streamPurge{Stream: stream, LastSeq: mset.state().LastSeq, Subject: subject, Reply: reply, Client: ci, Request: preq})
js.mu.Unlock()
mset.mu.RLock()
term := mset.term
mset.mu.RUnlock()
n.Propose(term, sp)
return
}
js.mu.Unlock()
if mset == nil {
return
}
var resp = JSApiStreamPurgeResponse{ApiResponse: ApiResponse{Type: JSApiStreamPurgeResponseType}}
purged, err := mset.purge(preq)
if err != nil {
@@ -8824,7 +8882,7 @@ func (s *Server) jsClusteredStreamRestoreRequest(
sa := &streamAssignment{Group: rg, Sync: syncSubjForStream(), Config: &cfg, Subject: subject, Reply: reply, Client: ci, Created: time.Now().UTC()}
// Now add in our restore state and pre-select a peer to handle the actual receipt of the snapshot.
sa.Restore = &req.State
if err := cc.meta.Propose(encodeAddStreamAssignment(sa)); err != nil {
if err := cc.meta.Propose(cc.term, encodeAddStreamAssignment(sa)); err != nil {
return
}
cc.trackInflightStreamProposal(ci.serviceAccount(), sa, false)
@@ -9249,7 +9307,7 @@ func (s *Server) jsClusteredConsumerDeleteRequest(ci *ClientInfo, acc *Account,
return
}
ca := &consumerAssignment{Group: oca.Group, Stream: stream, Name: consumer, Config: oca.Config, Subject: subject, Reply: reply, Client: ci, Created: oca.Created}
if err := cc.meta.Propose(encodeDeleteConsumerAssignment(ca)); err != nil {
if err := cc.meta.Propose(cc.term, encodeDeleteConsumerAssignment(ca)); err != nil {
return
}
cc.trackInflightConsumerProposal(acc.Name, stream, ca, true)
@@ -9284,9 +9342,12 @@ func (s *Server) jsClusteredMsgDeleteRequest(ci *ClientInfo, acc *Account, mset
// Check for single replica items.
if n := sa.Group.node; n != nil {
md := streamMsgDelete{Seq: req.Seq, NoErase: req.NoErase, Stream: stream, Subject: subject, Reply: reply, Client: ci}
n.Propose(encodeMsgDelete(&md))
md := encodeMsgDelete(&streamMsgDelete{Seq: req.Seq, NoErase: req.NoErase, Stream: stream, Subject: subject, Reply: reply, Client: ci})
js.mu.Unlock()
mset.mu.RLock()
term := mset.term
mset.mu.RUnlock()
n.Propose(term, md)
return
}
js.mu.Unlock()
@@ -9393,9 +9454,9 @@ func decodeDeleteRange(buf []byte) (*DeleteRange, error) {
}
// createGroupForConsumer will create a new group from same peer set as the stream.
func (cc *jetStreamCluster) createGroupForConsumer(cfg *ConsumerConfig, sa *streamAssignment) *raftGroup {
func (cc *jetStreamCluster) createGroupForConsumer(cfg *ConsumerConfig, sa *streamAssignment) (*raftGroup, *selectPeerError) {
if len(sa.Group.Peers) == 0 || cfg.Replicas > len(sa.Group.Peers) {
return nil
return nil, &selectPeerError{misc: true}
}
replicas := cfg.replicas(sa.Config)
@@ -9413,14 +9474,14 @@ func (cc *jetStreamCluster) createGroupForConsumer(cfg *ConsumerConfig, sa *stre
}
if quorum := replicas/2 + 1; quorum > len(active) {
// Not enough active to satisfy the request.
return nil
return nil, &selectPeerError{offline: true}
}
// If we want less then our parent stream, select from active.
if replicas > 0 && replicas < len(peers) {
// Pedantic in case stream is say R5 and consumer is R3 and 3 or more offline, etc.
if len(active) < replicas {
return nil
return nil, &selectPeerError{offline: true}
}
// First shuffle the active peers and then select to account for replica = 1.
rand.Shuffle(len(active), func(i, j int) { active[i], active[j] = active[j], active[i] })
@@ -9430,7 +9491,7 @@ func (cc *jetStreamCluster) createGroupForConsumer(cfg *ConsumerConfig, sa *stre
if cfg.MemoryStorage {
storage = MemoryStorage
}
return &raftGroup{Name: groupNameForConsumer(peers, storage), Storage: storage, Peers: peers}
return &raftGroup{Name: groupNameForConsumer(peers, storage), Storage: storage, Peers: peers}, nil
}
// jsClusteredConsumerRequest is first point of entry to create a consumer in clustered mode.
@@ -9615,8 +9676,8 @@ func (s *Server) jsClusteredConsumerRequest(ci *ClientInfo, acc *Account, subjec
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
}
rg := cc.createGroupForConsumer(cfg, sa)
if rg == nil {
rg, err := cc.createGroupForConsumer(cfg, sa)
if err != nil {
resp.Error = NewJSInsufficientResourcesError()
s.sendAPIErrResponse(ci, acc, subject, reply, string(rmsg), s.jsonResponse(&resp))
return
@@ -9792,7 +9853,7 @@ func (s *Server) jsClusteredConsumerRequest(ci *ClientInfo, acc *Account, subjec
}
// Do formal proposal.
if err := cc.meta.Propose(encodeAddConsumerAssignment(ca)); err != nil {
if err := cc.meta.Propose(cc.term, encodeAddConsumerAssignment(ca)); err != nil {
return
}
cc.trackInflightConsumerProposal(acc.Name, stream, ca, false)
@@ -9920,7 +9981,10 @@ func decodeStreamMsg(buf []byte) (subject, reply string, hdr, msg []byte, lseq u
}
ml := int(le.Uint32(buf))
buf = buf[4:]
if len(buf) < ml {
// ml is read as a uint32 but held in an int; on 32-bit builds a length with
// the high bit set becomes negative, which slips past len(buf) < ml and then
// panics on buf[:ml]. Reject a negative length so the bound holds everywhere.
if ml < 0 || len(buf) < ml {
return _EMPTY_, _EMPTY_, nil, nil, 0, 0, false, errBadStreamMsg
}
if msg = buf[:ml]; len(msg) == 0 {
@@ -10141,7 +10205,7 @@ func (mset *stream) processClusteredInboundMsg(subject, reply string, hdr, msg [
canRespond := !mset.cfg.NoAck && len(reply) > 0
name, stype := mset.cfg.Name, mset.cfg.Storage
discard, discardNewPer, maxMsgs, maxMsgsPer, maxBytes := mset.cfg.Discard, mset.cfg.DiscardNewPer, mset.cfg.MaxMsgs, mset.cfg.MaxMsgsPer, mset.cfg.MaxBytes
s, js, jsa, st, r, tierName, outq, node := mset.srv, mset.js, mset.jsa, mset.cfg.Storage, mset.cfg.Replicas, mset.tier, mset.outq, mset.node
s, js, jsa, st, r, tierName, outq, node, term := mset.srv, mset.js, mset.jsa, mset.cfg.Storage, mset.cfg.Replicas, mset.tier, mset.outq, mset.node, mset.term
maxMsgSize, lseq := int(mset.cfg.MaxMsgSize), mset.lseq
isLeader, isSealed, allowRollup, denyPurge, allowTTL, allowMsgCounter, allowMsgSchedules := mset.isLeader(), mset.cfg.Sealed, mset.cfg.AllowRollup, mset.cfg.DenyPurge, mset.cfg.AllowMsgTTL, mset.cfg.AllowMsgCounter, mset.cfg.AllowMsgSchedules
@@ -10266,7 +10330,7 @@ func (mset *stream) processClusteredInboundMsg(subject, reply string, hdr, msg [
return err
}
err = commitSingleMsg(diff, mset, subject, reply, hdr, msg, name, jsa, mt, node, r, lseq)
err = commitSingleMsg(diff, mset, subject, reply, hdr, msg, name, jsa, mt, node, term, r, lseq)
mset.clMu.Unlock()
return err
}
@@ -10666,7 +10730,7 @@ RETRY:
sreq = nil
// Run our own select loop here.
for qch, lch := n.QuitC(), n.LeadChangeC(); ; {
for qch := n.QuitC(); ; {
select {
case <-msgsQ.ch:
notActive.Reset(activityInterval)
@@ -10754,16 +10818,16 @@ RETRY:
msgsQ.recycle(&mrecs)
}
s.Warnf("Catchup for stream '%s > %s' stalled", mset.account(), mset.name())
// Sanity check that we've not become leader. Shouldn't be possible
// since we haven't applied the snapshot yet.
if n.State() == Leader {
n.StepDown()
}
goto RETRY
case <-s.quitCh:
return ErrServerNotRunning
case <-qch:
return errCatchupStreamStopped
case isLeader := <-lch:
if isLeader {
n.StepDown()
goto RETRY
}
}
}
}
+12 -4
View File
@@ -216,6 +216,12 @@ func validateLeafNode(o *Options) error {
if r.LocalAccount == _EMPTY_ {
r.LocalAccount = globalAccountName
}
if err := checkPermSubjectArray(r.DenyImports, false); err != nil {
return fmt.Errorf("invalid deny_imports for remote %s: %w", r.safeName(), err)
}
if err := checkPermSubjectArray(r.DenyExports, false); err != nil {
return fmt.Errorf("invalid deny_exports for remote %s: %w", r.safeName(), err)
}
rn := r.name()
if _, dup := names[rn]; dup {
return fmt.Errorf("duplicate remote %s", r.safeName())
@@ -2049,7 +2055,7 @@ func (s *Server) addLeafNodeConnection(c *client, srvName, clusterName string, c
meta.setObserver(false, extNotExtended)
c.Debugf("Turning JetStream metadata controller Observer Mode off")
// Take note that the domain was not extended to avoid this state from startup.
writePeerState(js.config.StoreDir, meta.currentPeerState())
writePeerState(c.srv.diskIOSemaphore(), js.config.StoreDir, meta.currentPeerState())
// Meta controller can't be leader yet.
// Yet it is possible that due to observer mode every server already stopped campaigning.
// Therefore this server needs to be kicked into campaigning gear explicitly.
@@ -2284,9 +2290,10 @@ func (c *client) processLeafNodeConnect(s *Server, arg []byte, lang string) erro
if !c.isSolicitedLeafNode() && c.perms != nil {
sp, pp := c.perms.sub, c.perms.pub
c.perms.sub, c.perms.pub = pp, sp
if c.opts.Import != nil {
c.darray = c.opts.Import.Deny
} else {
// setPermissions populated darray from the subscribe permissions,
// which are the import permissions advertised to the spoke. Keep
// those parsed denies after reversing the live permission directions.
if c.opts.Import == nil {
c.darray = nil
}
}
@@ -2959,6 +2966,7 @@ func (c *client) processLeafSub(argo []byte) (err error) {
c.Debugf(fmt.Sprintf("Permissions Violation for Subscription to %q", sub.subject))
return nil
}
c.loadMsgDenyFilterIfNeeded(subj, len(sub.queue) > 0)
}
// Check if we have a maximum on the number of subscriptions.
+33 -14
View File
@@ -22,6 +22,7 @@ import (
"sync"
"time"
"github.com/antithesishq/antithesis-sdk-go/assert"
"github.com/nats-io/nats-server/v2/server/ats"
"github.com/nats-io/nats-server/v2/server/avl"
"github.com/nats-io/nats-server/v2/server/gsl"
@@ -2395,24 +2396,42 @@ func (ms *memStore) EncodedStreamState(failed uint64) ([]byte, error) {
numDeleted = 0
}
// Encoded is Msgs, Bytes, FirstSeq, LastSeq, Failed, NumDeleted and optional DeletedBlocks
var buf [1024]byte
buf[0], buf[1] = streamStateMagic, streamStateVersion
n := hdrLen
n += binary.PutUvarint(buf[n:], ms.state.Msgs)
n += binary.PutUvarint(buf[n:], ms.state.Bytes)
n += binary.PutUvarint(buf[n:], ms.state.FirstSeq)
n += binary.PutUvarint(buf[n:], ms.state.LastSeq)
n += binary.PutUvarint(buf[n:], failed)
n += binary.PutUvarint(buf[n:], uint64(numDeleted))
b := buf[0:n]
// Encoded is Msgs, Bytes, FirstSeq, LastSeq, Failed, NumDeleted and optional DeletedBlocks.
// Calculate the exact encoded size up front so the buffer is allocated once.
total := hdrLen + uvarintLen(ms.state.Msgs) + uvarintLen(ms.state.Bytes) +
uvarintLen(ms.state.FirstSeq) + uvarintLen(ms.state.LastSeq) +
uvarintLen(failed) + uvarintLen(uint64(numDeleted))
if numDeleted > 0 {
buf := ms.dmap.Encode(nil)
b = append(b, buf...)
total += ms.dmap.EncodeLen()
}
b := make([]byte, 0, total)
b = append(b, streamStateMagic, streamStateVersion)
b = binary.AppendUvarint(b, ms.state.Msgs)
b = binary.AppendUvarint(b, ms.state.Bytes)
b = binary.AppendUvarint(b, ms.state.FirstSeq)
b = binary.AppendUvarint(b, ms.state.LastSeq)
b = binary.AppendUvarint(b, failed)
b = binary.AppendUvarint(b, uint64(numDeleted))
if numDeleted > 0 {
enc := ms.dmap.Encode(b[len(b):])
if n := len(b) + len(enc); n <= cap(b) {
b = b[:n]
} else {
// Fallback if the buffer didn't have spare capacity.
b = append(b, enc...)
}
}
if len(b) != total {
assert.Unreachable("Memstore EncodedStreamState size accounting mismatch", map[string]any{
"name": ms.cfg.Name,
"total": total,
"length": len(b),
})
}
return b, nil
}
+78 -1
View File
@@ -21,6 +21,7 @@ import (
"crypto/x509"
"encoding/hex"
"encoding/json"
"errors"
"expvar"
"fmt"
"maps"
@@ -1290,6 +1291,7 @@ type Varz struct {
OCSPResponseCache *OCSPResponseCacheVarz `json:"ocsp_peer_cache,omitempty"` // OCSPResponseCache is the state of the OCSP cache
SlowConsumersStats *SlowConsumersStats `json:"slow_consumer_stats"` // SlowConsumersStats are statistics about all detected Slow Consumer
StaleConnectionStats *StaleConnectionStats `json:"stale_connection_stats,omitempty"` // StaleConnectionStats are statistics about all detected Stale Connections
DiskIOWaitStats *DiskIOWaitStats `json:"disk_io_wait_stats"` // DiskIOWaitStats are statistics about disk I/O semaphore contention
Proxies *ProxiesOptsVarz `json:"proxies,omitempty"` // Proxies hold information about network proxy devices
TLSCertNotAfter time.Time `json:"tls_cert_not_after,omitzero"` // TLSCertNotAfter is the expiration date of the TLS certificate of this server
}
@@ -1449,6 +1451,14 @@ type StaleConnectionStats struct {
Leafs uint64 `json:"leafs"` // Leafs is how many Leafnode connections became stale connections
}
// DiskIOWaitStats contains information about disk I/O semaphore contention.
type DiskIOWaitStats struct {
Waiters int64 `json:"waiters"` // Waiters is the number of goroutines waiting on the dios
Waits uint64 `json:"waits"` // Waits is the number of dios acquires that had to wait
WaitTime uint64 `json:"wait_time"` // WaitTime is the cumulative time spent waiting for dios
MaxWaitTime uint64 `json:"max_wait_time"` // MaxWaitTime is the longest observed wait
}
func myUptime(d time.Duration) string {
// Just use total seconds for uptime, and display days / years
tsecs := d / time.Second
@@ -1845,6 +1855,15 @@ func (s *Server) updateVarzConfigReloadableFields(v *Varz) {
} else {
v.Proxies = nil
}
if cfg := v.JetStream.Config; cfg != nil {
if opts.JetStreamMaxMemory > 0 {
cfg.MaxMemory = opts.JetStreamMaxMemory
}
if opts.JetStreamMaxStore > 0 {
cfg.MaxStore = opts.JetStreamMaxStore
}
}
}
func getPinnedCertsAsSlice(certs PinnedCertSet) []string {
@@ -1969,6 +1988,19 @@ func (s *Server) updateVarzRuntimeFields(v *Varz, forceUpdate bool, pcpu float64
}
}
}
v.DiskIOWaitStats = diskIOWaitStats(s.dios)
}
func diskIOWaitStats(d *diskIOSemaphore) *DiskIOWaitStats {
if d == nil {
return &DiskIOWaitStats{}
}
return &DiskIOWaitStats{
Waiters: d.waiters.Load(),
Waits: d.waits.Load(),
WaitTime: d.waitNanos.Load(),
MaxWaitTime: d.maxWaitNanos.Load(),
}
}
// HandleVarz will process HTTP requests for server information.
@@ -3691,6 +3723,29 @@ func (s *Server) healthz(opts *HealthzOptions) *HealthStatus {
accFound = true
}
acc, err := s.LookupAccount(fi.Name())
// Expired accounts are not a JetStream health problem; skip them when
// scanning all accounts. Still surface an error if this account was
// explicitly requested — including the err==nil + IsExpired() case.
expired := (err != nil && errors.Is(err, ErrAccountExpired)) || (err == nil && acc.IsExpired())
if expired {
if opts.Account == _EMPTY_ {
continue
}
msg := fmt.Sprintf("JetStream account '%s' is expired", fi.Name())
if !details {
health.Status = na
health.Error = msg
return health
}
health.Errors = append(health.Errors, HealthzError{
Type: HealthzErrorAccount,
Account: fi.Name(),
Error: msg,
})
// Return so later stream/consumer not-found checks do not
// replace this with a misleading 404 for assets we skipped.
return health
}
if err != nil {
if !details {
health.Status = na
@@ -3986,6 +4041,28 @@ func (s *Server) healthz(opts *HealthzOptions) *HealthStatus {
// Use our copy to traverse so we do not need to hold the js lock.
for accName, asa := range streams {
acc, err := s.LookupAccount(accName)
// Expired accounts are not a JetStream health problem; skip them when
// scanning all accounts. Still surface an error if this account was
// explicitly requested — including the err==nil + IsExpired() case.
expired := (err != nil && errors.Is(err, ErrAccountExpired)) || (err == nil && acc.IsExpired())
if expired {
if opts.Account == _EMPTY_ {
continue
}
msg := fmt.Sprintf("JetStream account %q is expired", accName)
if !details {
health.Status = na
health.Error = msg
return health
}
health.Errors = append(health.Errors, HealthzError{
Type: HealthzErrorAccount,
Account: accName,
Error: msg,
})
// Return so later health checks do not obscure the expired account.
return health
}
if err != nil && len(asa) > 0 {
if !details {
health.Status = na
@@ -4245,7 +4322,7 @@ func (s *Server) Raftz(opts *RaftzOptions) *RaftzStatus {
PTerm: n.pterm,
PIndex: n.pindex,
SystemAcc: n.IsSystemAccount(),
TrafficAcc: n.acc.GetName(),
TrafficAcc: n.t.Account().GetName(),
IPQPropLen: n.prop.len(),
IPQEntryLen: n.entry.len(),
IPQRespLen: n.resp.len(),
+228 -52
View File
@@ -72,6 +72,7 @@ const (
mqttPubFlagRetain = byte(0x01)
mqttPubFlagQoS = byte(0x06)
mqttPubFlagDup = byte(0x08)
mqttPubFlags = mqttPubFlagRetain | mqttPubFlagQoS | mqttPubFlagDup // 0x0f, the fixed-header flags nibble
mqttPubQos1 = byte(0x1 << 1)
mqttPubQoS2 = byte(0x2 << 1)
@@ -242,6 +243,7 @@ var (
errMQTTUnsupportedCharacters = errors.New("character not supported for MQTT topics")
errMQTTInvalidSession = errors.New("invalid MQTT session")
errMQTTInvalidRetainFlags = errors.New("invalid retained message flags")
errMQTTInvalidRetainedMessage = errors.New("invalid retained message")
errMQTTSessionCollision = errors.New("stored session does not match client ID")
)
@@ -379,6 +381,12 @@ type mqttSub struct {
qos byte
jsDur string
// closed marks the subscription as torn down (QoS downgrade to 0, or
// unsubscribe) so QoS 1/2 delivery callbacks stop tracking new messages for
// it. Guarded like qos/jsDur (sess.mu or sess.subsMu). Unlike clearing
// sub.mqtt, this keeps the struct valid for an in-flight enqueue.
closed bool
// Pending serialization of retained messages to be sent when subscription
// is registered. The sub's delivery callbacks must wait until `prm` is
// ready (can block on sess.mu for that, too).
@@ -475,6 +483,13 @@ const (
// NATS header that indicates that the message originated from MQTT and
// stores the published message QOS.
mqttNatsHeader = "Nmqtt-Pub"
// A staged QoS2 message's mqttNatsHeader value carries a second byte after
// the QoS: the MQTT PUBLISH flags nibble (mqttPubFlags) as one hex char,
// e.g. "25" for a retained QoS2 message (0x5 = retain|QoS2). The value is a
// persisted, cross-version contract: byte 0 stays the bare QoS forever
// (older servers read only it), a missing flags byte reads as no flags, and
// extensions may only append bytes (a second hex char = a full private
// byte), never change the meaning of existing ones.
// NATS headers to store retained message metadata (along with the original
// message as binary).
@@ -493,9 +508,10 @@ const (
)
type mqttParsedPublishNATSHeader struct {
qos byte
subject []byte
mapped []byte
qos byte
retained bool
subject []byte
mapped []byte
}
func (s *Server) startMQTT() {
@@ -1127,6 +1143,28 @@ func (s *Server) mqttStoreQoSMsgForAccountOnNewSubject(hdr int, msg []byte, acc,
jsa.storeMsg(mqttStreamSubjectPrefix+subject, hdr, msg)
}
// Encodes the MQTT PUBLISH flags nibble (mqttPubFlags) as one hex char, the
// flags byte that follows the QoS in a mqttNatsHeader value.
func mqttNatsHeaderEncodeFlags(ppFlags byte) byte {
return "0123456789abcdef"[ppFlags&mqttPubFlags]
}
// Decodes the MQTT flags nibble carried after the QoS in a mqttNatsHeader
// value; values without the flags byte read as no flags set. Callers test the
// result with the mqttPubFlag* bits.
func mqttNatsHeaderDecodeFlags(value []byte) byte {
if len(value) < 2 {
return 0
}
switch c := value[1]; {
case c >= '0' && c <= '9':
return c - '0'
case c >= 'a' && c <= 'f':
return c - 'a' + 10
}
return 0
}
func mqttParsePublishNATSHeader(headerBytes []byte) *mqttParsedPublishNATSHeader {
if len(headerBytes) == 0 {
return nil
@@ -1137,9 +1175,10 @@ func mqttParsePublishNATSHeader(headerBytes []byte) *mqttParsedPublishNATSHeader
return nil
}
return &mqttParsedPublishNATSHeader{
qos: pubValue[0] - '0',
subject: getHeader(mqttNatsHeaderSubject, headerBytes),
mapped: getHeader(mqttNatsHeaderMapped, headerBytes),
qos: pubValue[0] - '0',
retained: mqttIsRetained(mqttNatsHeaderDecodeFlags(pubValue)),
subject: getHeader(mqttNatsHeaderSubject, headerBytes),
mapped: getHeader(mqttNatsHeaderMapped, headerBytes),
}
}
@@ -1467,6 +1506,10 @@ func (s *Server) mqttCreateAccountSessionManager(acc *Account, quitCh chan struc
default:
needToTransfer = si.Config.MaxMsgsPer != 1
}
// Guard before dereferencing si.Config below.
if si == nil {
return nil, fmt.Errorf("could not look up or create the retained messages stream for account %q", accName)
}
// Doing this check outside of above if/else due to possible race when
// creating the stream.
@@ -1503,6 +1546,10 @@ func (s *Server) mqttCreateAccountSessionManager(acc *Account, quitCh chan struc
if err = transferRMS(); err != nil {
return nil, err
}
// Guard before dereferencing si.Config below.
if si == nil {
return nil, fmt.Errorf("could not look up the retained messages stream for account %q", accName)
}
// Now, if the stream does not have MaxMsgsPer set to 1, and there are no
// more messages on the single $MQTT.rmsgs subject, update the stream again.
@@ -1764,7 +1811,13 @@ func (jsa *mqttJSA) createStream(cfg *StreamConfig) (*StreamInfo, bool, error) {
return nil, false, err
}
scr := scri.(*JSApiStreamCreateResponse)
return scr.StreamInfo, scr.DidCreate, scr.ToError()
if err = scr.ToError(); err != nil {
return nil, false, err
}
if scr.StreamInfo == nil {
return nil, false, fmt.Errorf("invalid stream create response: missing stream info")
}
return scr.StreamInfo, scr.DidCreate, nil
}
func (jsa *mqttJSA) updateStream(cfg *StreamConfig) (*StreamInfo, error) {
@@ -1777,7 +1830,13 @@ func (jsa *mqttJSA) updateStream(cfg *StreamConfig) (*StreamInfo, error) {
return nil, err
}
scr := scri.(*JSApiStreamUpdateResponse)
return scr.StreamInfo, scr.ToError()
if err = scr.ToError(); err != nil {
return nil, err
}
if scr.StreamInfo == nil {
return nil, fmt.Errorf("invalid stream update response: missing stream info")
}
return scr.StreamInfo, nil
}
func (jsa *mqttJSA) lookupStream(name string) (*StreamInfo, error) {
@@ -1786,7 +1845,13 @@ func (jsa *mqttJSA) lookupStream(name string) (*StreamInfo, error) {
return nil, err
}
slr := slri.(*JSApiStreamInfoResponse)
return slr.StreamInfo, slr.ToError()
if err = slr.ToError(); err != nil {
return nil, err
}
if slr.StreamInfo == nil {
return nil, NewJSStreamNotFoundError()
}
return slr.StreamInfo, nil
}
func (jsa *mqttJSA) deleteStream(name string) (bool, error) {
@@ -1809,7 +1874,13 @@ func (jsa *mqttJSA) loadLastMsgFor(streamName string, subject string) (*StoredMs
return nil, err
}
lmr := lmri.(*JSApiMsgGetResponse)
return lmr.Message, lmr.ToError()
if err = lmr.ToError(); err != nil {
return nil, err
}
if lmr.Message == nil {
return nil, NewJSNoMessageFoundError()
}
return lmr.Message, nil
}
func (jsa *mqttJSA) loadLastMsgForMulti(streamName string, subjects []string) ([]*JSApiMsgGetResponse, error) {
@@ -1847,7 +1918,13 @@ func (jsa *mqttJSA) loadNextMsgFor(streamName string, subject string) (*StoredMs
return nil, err
}
lmr := lmri.(*JSApiMsgGetResponse)
return lmr.Message, lmr.ToError()
if err = lmr.ToError(); err != nil {
return nil, err
}
if lmr.Message == nil {
return nil, NewJSNoMessageFoundError()
}
return lmr.Message, nil
}
func (jsa *mqttJSA) loadMsg(streamName string, seq uint64) (*StoredMsg, error) {
@@ -1861,7 +1938,13 @@ func (jsa *mqttJSA) loadMsg(streamName string, seq uint64) (*StoredMsg, error) {
return nil, err
}
lmr := lmri.(*JSApiMsgGetResponse)
return lmr.Message, lmr.ToError()
if err := lmr.ToError(); err != nil {
return nil, err
}
if lmr.Message == nil {
return nil, NewJSNoMessageFoundError()
}
return lmr.Message, nil
}
func (jsa *mqttJSA) storeMsgNoWait(subject string, hdrLen int, msg []byte) {
@@ -1963,13 +2046,13 @@ func (as *mqttAccountSessionManager) processJSAPIReplies(_ *subscription, pc *cl
out(resp)
case mqttJSAStreamLookup:
var resp = &JSApiStreamInfoResponse{}
if err := json.Unmarshal(msg, &resp); err != nil {
if err := json.Unmarshal(msg, resp); err != nil {
resp.Error = NewJSInvalidJSONError(err)
}
out(resp)
case mqttJSAStreamDel:
var resp = &JSApiStreamDeleteResponse{}
if err := json.Unmarshal(msg, &resp); err != nil {
if err := json.Unmarshal(msg, resp); err != nil {
resp.Error = NewJSInvalidJSONError(err)
}
out(resp)
@@ -1993,7 +2076,7 @@ func (as *mqttAccountSessionManager) processJSAPIReplies(_ *subscription, pc *cl
out(resp)
case mqttJSAMsgLoad:
var resp = &JSApiMsgGetResponse{}
if err := json.Unmarshal(msg, &resp); err != nil {
if err := json.Unmarshal(msg, resp); err != nil {
resp.Error = NewJSInvalidJSONError(err)
}
out(resp)
@@ -2098,6 +2181,9 @@ func (as *mqttAccountSessionManager) processSessionPersist(_ *subscription, pc *
if err := par.Error; err != nil {
return
}
if par.PubAck == nil {
return
}
as.mu.RLock()
// Note that as.domainTk includes a terminal '.', so strip to compare to PubAck.Domain.
dl := len(as.domainTk)
@@ -2484,6 +2570,8 @@ func (sess *mqttSession) processSub(
// accessing it later requires a lock.
ss.mqtt.qos = qos
ss.mqtt.jsDur = jsDurName
// A (re)configured subscription is live; clear any prior teardown mark.
ss.mqtt.closed = false
}
if len(rms) > 0 {
@@ -2538,13 +2626,10 @@ func (as *mqttAccountSessionManager) processSubs(sess *mqttSession, c *client,
f.qos = 1
}
// Do not allow subscribing to our internal subjects.
//
// TODO: (levb: not sure why since one can subscribe to `#` and it'll
// include everything; I guess this would discourage? Otherwise another
// candidate for DO NOT DELIVER prefix list).
if strings.HasPrefix(f.filter, mqttSubPrefix) ||
strings.HasPrefix(f.filter, mqttPubRelDeliverySubjectPrefix) {
// Do not allow MQTT clients to subscribe directly to internal subjects.
// Otherwise, subjects such as "$MQTT.msgs.*" could be used to bypass
// MQTT subscription permissions.
if strings.HasPrefix(f.filter, mqttPrefix) {
f.qos = mqttSubAckFailure
continue
}
@@ -2703,7 +2788,7 @@ func (as *mqttAccountSessionManager) serializeRetainedMsgsForSub(rms map[string]
}
// A broad wildcard subscription can overlap a subscribe deny clause.
c.mu.Lock()
denied := c.mperms != nil && c.checkDenySub(string(subj))
denied := c.mperms != nil && c.checkDenySub(string(subj), bytesToString(sub.queue))
c.mu.Unlock()
if denied {
return
@@ -2715,7 +2800,7 @@ func (as *mqttAccountSessionManager) serializeRetainedMsgsForSub(rms map[string]
return
}
if qos > 0 {
pi = sess.trackPublishRetained()
pi = sess.trackPublishRetained(string(sub.sid))
// If we failed to get a PI for this message, send it as a QoS0, the
// best we can do?
@@ -2817,6 +2902,10 @@ func (as *mqttAccountSessionManager) loadRetainedMessages(subjects map[string]ui
w.Warnf("failed to load retained message for subject %q: %v", subj, err)
continue
}
// Guard before dereferencing below.
if result.Message == nil {
continue
}
rm, err := mqttDecodeRetainedMessage(result.Message.Subject, result.Message.Header, result.Message.Data)
if err != nil {
// Unlikely that we can recover from that, so remove the message.
@@ -2984,6 +3073,9 @@ func mqttDecodeRetainedMessage(subject string, h, m []byte) (*mqttRetainedMsg, e
if err := json.Unmarshal(m, &rm); err != nil {
return nil, err
}
if rm == nil {
return nil, errMQTTInvalidRetainedMessage
}
}
// Now check that the values are correct.
//
@@ -3038,6 +3130,11 @@ func (as *mqttAccountSessionManager) createOrRestoreSession(clientID string, opt
if ps.ID != clientID {
return nil, false, errMQTTSessionCollision
}
for sid, cc := range ps.Cons {
if cc == nil {
delete(ps.Cons, sid)
}
}
// Restore this session (even if we don't own it), the caller will do the right thing.
sess := mqttSessionCreate(jsa, clientID, hash, smsg.Sequence, opts)
@@ -3291,6 +3388,10 @@ func (sess *mqttSession) save() error {
if err != nil {
return fmt.Errorf("unable to persist session %q (seq=%v): %v", ps.ID, seq, err)
}
// Guard before dereferencing below.
if resp == nil || resp.PubAck == nil {
return fmt.Errorf("unable to persist session %q (seq=%v): invalid pub ack response", ps.ID, seq)
}
sess.mu.Lock()
sess.seq = resp.Sequence
sess.mu.Unlock()
@@ -3326,6 +3427,9 @@ func (sess *mqttSession) clear(noWait bool) error {
sess.pubRelConsumer = nil
sess.seq = 0
sess.tmaxack = 0
// Discarded session: reset the PI counter too so a reused session object
// does not inherit the previous session's identifiers. Spec [MQTT-3.1.2-6].
sess.last_pi = 0
sess.mu.Unlock()
for _, dur := range durs {
@@ -3410,14 +3514,23 @@ func (sess *mqttSession) bumpPI() uint16 {
return sess.last_pi
}
// mqttRetainedPendingDur returns the pseudo consumer-durable key under which a
// subscription's in-flight retained QoS deliveries are tracked in cpending.
// Retained deliveries have no JS consumer, but keying them per subscription
// lets unsubscribe/downgrade teardown purge them like consumer deliveries.
// Cannot collide with real durables (idHash+"_"+nuid, $MQTT_PUBREL_ prefix).
func mqttRetainedPendingDur(sid string) string {
return mqttRetainedMsgsStreamName + "/" + sid
}
// trackPublishRetained is invoked when a retained (QoS) message is published.
// It need a new PI to be allocated, so we add it to the pendingPublish map,
// with an empty value. Since cpending (not pending) is used to serialize the PI
// mappings, we need to add this PI there as well. Make a unique key by using
// mqttRetainedMsgsStreamName for the durable name, and PI for sseq.
// It needs a new PI to be allocated, so we add it to the pendingPublish map,
// and serialize it in cpending under the subscription's pseudo-durable key
// (with the PI as the sequence) so consumer teardown purges it; an ack removes
// both entries via untrackPublish.
//
// Lock held on entry
func (sess *mqttSession) trackPublishRetained() uint16 {
func (sess *mqttSession) trackPublishRetained(sid string) uint16 {
// Make sure we initialize the tracking maps.
if sess.pendingPublish == nil {
sess.pendingPublish = make(map[uint16]*mqttPending)
@@ -3430,7 +3543,14 @@ func (sess *mqttSession) trackPublishRetained() uint16 {
if pi == 0 {
return 0
}
sess.pendingPublish[pi] = &mqttPending{}
dur := mqttRetainedPendingDur(sid)
sseqToPi := sess.cpending[dur]
if sseqToPi == nil {
sseqToPi = make(map[uint64]uint16)
sess.cpending[dur] = sseqToPi
}
sseqToPi[uint64(pi)] = pi
sess.pendingPublish[pi] = &mqttPending{jsDur: dur, sseq: uint64(pi)}
return pi
}
@@ -3527,9 +3647,9 @@ func (sess *mqttSession) untrackPublish(pi uint16) (jsAckSubject string) {
}
delete(sess.pendingPublish, pi)
if len(sess.pendingPublish) == 0 {
sess.last_pi = 0
}
// Do NOT reset last_pi here: it is a monotonic rolling counter (see bumpPI) so
// a just-freed id is not reused within a delivery burst, which a client would
// read as a duplicate. Spec [MQTT-2.3.1-4].
if len(sess.cpending) != 0 && ack.jsDur != _EMPTY_ {
if sseqToPi := sess.cpending[ack.jsDur]; sseqToPi != nil {
@@ -4052,14 +4172,16 @@ func (s *Server) mqttHandleWill(c *client) {
c.mu.Unlock()
return
}
pp := c.mqtt.pp
pp.topic = will.topic
pp.subject = will.subject
pp.mapped = will.mapped
pp.msg = will.message
pp.sz = len(will.message)
pp.pi = 0
pp.flags = will.qos << 1
// Create a synthetic PUBLISH packet to be delivered to the session's
// subscriptions, regardless of what is currently in c.mqtt.pp.
pp := &mqttPublish{
topic: will.topic,
subject: will.subject,
mapped: will.mapped,
msg: will.message,
sz: len(will.message),
flags: will.qos << 1,
}
if will.retain {
pp.flags |= mqttPubFlagRetain
}
@@ -4197,6 +4319,7 @@ func mqttComputeNatsMsgSize(pp *mqttPublish, encodePP bool) int {
2 + // end-of-header CRLF
pp.sz
if encodePP {
size++ // for the flags byte
size += len(mqttNatsHeaderSubject) + 1 + // +1 for ':'
len(pp.subject) + 2 // 2 for CRLF
@@ -4228,6 +4351,9 @@ func mqttNewDeliverableMessage(pp *mqttPublish, encodePP bool) (natsMsg []byte,
buf.WriteString(mqttNatsHeader)
buf.WriteByte(':')
buf.WriteByte(qos + '0')
if encodePP {
buf.WriteByte(mqttNatsHeaderEncodeFlags(pp.flags))
}
buf.WriteString(_CRLF_)
if encodePP {
@@ -4330,7 +4456,13 @@ func (s *Server) mqttProcessPub(c *client, pp *mqttPublish, trace bool) error {
func (s *Server) mqttInitiateMsgDelivery(c *client, pp *mqttPublish) error {
natsMsg, headerLen := mqttNewDeliverableMessage(pp, false)
// Set the client's pubarg for processing.
// The delivered message becomes the client's current publish (it is not
// the last PARSED packet for a PUBREL- or will-initiated delivery), and
// c.pa carries its pubargs; one defer restores both. c.mqtt.pp is
// readLoop-owned, like c.pa.
prevPP := c.mqtt.pp
c.mqtt.pp = pp
c.pa.subject = pp.subject
c.pa.mapped = pp.mapped
c.pa.reply = nil
@@ -4339,6 +4471,7 @@ func (s *Server) mqttInitiateMsgDelivery(c *client, pp *mqttPublish) error {
c.pa.size = len(natsMsg)
c.pa.szb = []byte(strconv.FormatInt(int64(c.pa.size), 10))
defer func() {
c.mqtt.pp = prevPP
c.pa.subject = nil
c.pa.mapped = nil
c.pa.reply = nil
@@ -4426,6 +4559,10 @@ func (s *Server) mqttProcessPubRel(c *client, pi uint16, trace bool) error {
return errors.New("invalid message in QoS2 PUBREL stream")
}
flags := h.qos << 1
if h.retained {
flags |= mqttPubFlagRetain
}
pp := &mqttPublish{
topic: natsSubjectToMQTTTopic(h.subject),
subject: h.subject,
@@ -4433,7 +4570,7 @@ func (s *Server) mqttProcessPubRel(c *client, pi uint16, trace bool) error {
msg: stored.Data,
sz: len(stored.Data),
pi: pi,
flags: h.qos << 1,
flags: flags,
}
return s.mqttInitiateMsgDelivery(c, pp)
@@ -5039,7 +5176,7 @@ func mqttDeliverMsgCbQoS12(sub *subscription, pc *client, _ *Account, subject, r
// track of pending acks, etc. There is no need to acquire the subsMu RLock
// since sess.Lock is overarching for modifying subscriptions.
sess.mu.Lock()
if sess.c != cc || sub.mqtt == nil {
if sess.c != cc || sub.mqtt == nil || sub.mqtt.closed {
sess.mu.Unlock()
return
}
@@ -5070,7 +5207,7 @@ func mqttDeliverMsgCbQoS12(sub *subscription, pc *client, _ *Account, subject, r
// A broad wildcard subscription can overlap a subscribe deny clause.
cc.mu.Lock()
denied := cc.mperms != nil && cc.checkDenySub(strippedSubj)
denied := cc.mperms != nil && cc.checkDenySub(strippedSubj, bytesToString(sub.queue))
cc.mu.Unlock()
if denied {
sess.mu.Unlock()
@@ -5436,8 +5573,32 @@ func (sess *mqttSession) processJSConsumer(c *client, subject, sid string,
sub := c.subs[cc.DeliverSubject]
c.mu.Unlock()
// Delete the consumer entry, mark its delivery subscription closed,
// and purge its pending QoS 1/2 deliveries — all under the session
// lock. Otherwise those packet identifiers leak and count against the
// in-flight cap for the life of the session (as mqttProcessUnsubs
// purges on unsubscribe). deleteConsumer is asynchronous, so an
// in-flight delivery callback could re-populate the maps after the
// purge; marking sub.mqtt.closed (guarded by sess.mu and sess.subsMu,
// same as delivery) makes mqttDeliverMsgCbQoS12 skip instead. The flag
// leaves sub.mqtt valid so an already-committed enqueue does not panic.
sess.mu.Lock()
delete(sess.cons, sid)
if sub != nil && sub.mqtt != nil {
sess.subsMu.Lock()
sub.mqtt.closed = true
sess.subsMu.Unlock()
}
// Also purge this sid's in-flight retained deliveries, tracked
// under a pseudo-durable key (no JS consumer, no redelivery).
for _, dur := range [...]string{cc.Durable, mqttRetainedPendingDur(sid)} {
if seqPis, ok := sess.cpending[dur]; ok {
delete(sess.cpending, dur)
for _, pi := range seqPis {
delete(sess.pendingPublish, pi)
}
}
}
sess.mu.Unlock()
sess.deleteConsumer(cc)
@@ -5586,15 +5747,30 @@ func (c *client) mqttProcessUnsubs(filters []*mqttFilter) error {
if ok {
delete(sess.cons, sid)
sess.deleteConsumer(cc)
c.mu.Lock()
sub := c.subs[cc.DeliverSubject]
c.mu.Unlock()
// Need lock here since these are accessed by callbacks
sess.mu.Lock()
if seqPis, ok := sess.cpending[cc.Durable]; ok {
delete(sess.cpending, cc.Durable)
for _, pi := range seqPis {
delete(sess.pendingPublish, pi)
}
if len(sess.pendingPublish) == 0 {
sess.last_pi = 0
// Mark the delivery sub closed so an in-flight QoS 1/2 callback stops
// tracking new messages after the purge (deleteConsumer is async);
// same barrier as the QoS 0 downgrade path in processJSConsumer.
if sub != nil && sub.mqtt != nil {
sess.subsMu.Lock()
sub.mqtt.closed = true
sess.subsMu.Unlock()
}
// Purge both the consumer's deliveries and this sid's in-flight
// retained deliveries (tracked under a pseudo-durable key).
for _, dur := range [...]string{cc.Durable, mqttRetainedPendingDur(sid)} {
if seqPis, ok := sess.cpending[dur]; ok {
delete(sess.cpending, dur)
for _, pi := range seqPis {
delete(sess.pendingPublish, pi)
}
// last_pi stays monotonic (see untrackPublish); do not reset here.
}
}
sess.mu.Unlock()
+61 -15
View File
@@ -462,6 +462,7 @@ type Options struct {
JetStreamMetaCompact uint64
JetStreamMetaCompactSize uint64
JetStreamMetaCompactSync bool
JetStreamConcurrentIOs int
StreamMaxBufferedMsgs int `json:"-"`
StreamMaxBufferedSize int64 `json:"-"`
StoreDir string `json:"-"`
@@ -2061,6 +2062,10 @@ func parseCluster(v any, opts *Options, errors *[]error, warnings *[]error) erro
opts.Cluster.AuthTimeout = auth.timeout
if auth.defaultPermissions != nil {
if err := checkClusterPermissionSubjects(auth.defaultPermissions); err != nil {
*errors = append(*errors, &configErr{tk, err.Error()})
continue
}
err := &configWarningErr{
field: mk,
configErr: configErr{
@@ -2116,6 +2121,10 @@ func parseCluster(v any, opts *Options, errors *[]error, warnings *[]error) erro
*errors = append(*errors, err)
continue
}
if err := checkClusterPermissionSubjects(perms); err != nil {
*errors = append(*errors, &configErr{tk, err.Error()})
continue
}
// This will possibly override permissions that were define in auth block
setClusterPermissions(&opts.Cluster, perms)
case "pool_size":
@@ -2762,6 +2771,12 @@ func parseJetStream(v any, opts *Options, errors *[]error, warnings *[]error) er
opts.JetStreamMetaCompactSize = uint64(s)
case "meta_compact_sync":
opts.JetStreamMetaCompactSync = mv.(bool)
case "max_concurrent_io":
dios, ok := mv.(int64)
if !ok || dios < minConcurrentIOs || dios > maxConcurrentIOs {
return &configErr{tk, fmt.Sprintf("Expected an absolute size for %q between 4 and 8192, got %v", mk, mv)}
}
opts.JetStreamConcurrentIOs = int(dios)
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
@@ -3127,14 +3142,14 @@ func parseRemoteLeafNodes(v any, errors *[]error, warnings *[]error) ([]*RemoteL
case "hub":
remote.Hub = v.(bool)
case "deny_imports", "deny_import":
subjects, err := parsePermSubjects(tk, errors)
subjects, err := parsePermSubjects(tk, errors, false)
if err != nil {
*errors = append(*errors, err)
continue
}
remote.DenyImports = subjects
case "deny_exports", "deny_export":
subjects, err := parsePermSubjects(tk, errors)
subjects, err := parsePermSubjects(tk, errors, false)
if err != nil {
*errors = append(*errors, err)
continue
@@ -3346,6 +3361,29 @@ func setClusterPermissions(opts *ClusterOpts, perms *Permissions) {
}
}
func checkClusterPermissionSubjects(perms *Permissions) error {
if perms == nil {
return nil
}
if perms.Publish != nil {
if err := checkPermSubjectArray(perms.Publish.Allow, false); err != nil {
return fmt.Errorf("cluster import allow: %w", err)
}
if err := checkPermSubjectArray(perms.Publish.Deny, false); err != nil {
return fmt.Errorf("cluster import deny: %w", err)
}
}
if perms.Subscribe != nil {
if err := checkPermSubjectArray(perms.Subscribe.Allow, false); err != nil {
return fmt.Errorf("cluster export allow: %w", err)
}
if err := checkPermSubjectArray(perms.Subscribe.Deny, false); err != nil {
return fmt.Errorf("cluster export deny: %w", err)
}
}
return nil
}
// Temp structures to hold account import and export defintions since they need
// to be processed after being parsed.
type export struct {
@@ -4787,14 +4825,14 @@ func parseUserPermissions(mv any, errors *[]error) (*Permissions, error) {
// Import is Publish
// Export is Subscribe
case "pub", "publish", "import":
perms, err := parseVariablePermissions(mv, errors)
perms, err := parseVariablePermissions(mv, errors, false)
if err != nil {
*errors = append(*errors, err)
continue
}
p.Publish = perms
case "sub", "subscribe", "export":
perms, err := parseVariablePermissions(mv, errors)
perms, err := parseVariablePermissions(mv, errors, true)
if err != nil {
*errors = append(*errors, err)
continue
@@ -4834,19 +4872,19 @@ func parseUserPermissions(mv any, errors *[]error) (*Permissions, error) {
}
// Top level parser for authorization configurations.
func parseVariablePermissions(v any, errors *[]error) (*SubjectPermission, error) {
func parseVariablePermissions(v any, errors *[]error, allowQueue bool) (*SubjectPermission, error) {
switch vv := v.(type) {
case map[string]any:
// New style with allow and/or deny properties.
return parseSubjectPermission(vv, errors)
return parseSubjectPermission(vv, errors, allowQueue)
default:
// Old style
return parseOldPermissionStyle(v, errors)
return parseOldPermissionStyle(v, errors, allowQueue)
}
}
// Helper function to parse subject singletons and/or arrays
func parsePermSubjects(v any, errors *[]error) ([]string, error) {
func parsePermSubjects(v any, errors *[]error, allowQueue bool) ([]string, error) {
var lt token
defer convertPanicToErrorList(&lt, errors)
@@ -4871,7 +4909,7 @@ func parsePermSubjects(v any, errors *[]error) ([]string, error) {
default:
return nil, &configErr{tk, fmt.Sprintf("Expected subject permissions to be a subject, or array of subjects, got %T", v)}
}
if err := checkPermSubjectArray(subjects); err != nil {
if err := checkPermSubjectArray(subjects, allowQueue); err != nil {
return nil, &configErr{tk, err.Error()}
}
return subjects, nil
@@ -4936,8 +4974,8 @@ func parseAllowResponses(v any, errors *[]error) *ResponsePermission {
}
// Helper function to parse old style authorization configs.
func parseOldPermissionStyle(v any, errors *[]error) (*SubjectPermission, error) {
subjects, err := parsePermSubjects(v, errors)
func parseOldPermissionStyle(v any, errors *[]error, allowQueue bool) (*SubjectPermission, error) {
subjects, err := parsePermSubjects(v, errors, allowQueue)
if err != nil {
return nil, err
}
@@ -4945,7 +4983,7 @@ func parseOldPermissionStyle(v any, errors *[]error) (*SubjectPermission, error)
}
// Helper function to parse new style authorization into a SubjectPermission with Allow and Deny.
func parseSubjectPermission(v any, errors *[]error) (*SubjectPermission, error) {
func parseSubjectPermission(v any, errors *[]error, allowQueue bool) (*SubjectPermission, error) {
var lt token
defer convertPanicToErrorList(&lt, errors)
@@ -4958,14 +4996,14 @@ func parseSubjectPermission(v any, errors *[]error) (*SubjectPermission, error)
tk, _ := unwrapValue(v, &lt)
switch strings.ToLower(k) {
case "allow":
subjects, err := parsePermSubjects(tk, errors)
subjects, err := parsePermSubjects(tk, errors, allowQueue)
if err != nil {
*errors = append(*errors, err)
continue
}
p.Allow = subjects
case "deny":
subjects, err := parsePermSubjects(tk, errors)
subjects, err := parsePermSubjects(tk, errors, allowQueue)
if err != nil {
*errors = append(*errors, err)
continue
@@ -4982,15 +5020,20 @@ func parseSubjectPermission(v any, errors *[]error) (*SubjectPermission, error)
}
// Helper function to validate permissions subjects.
func checkPermSubjectArray(sa []string) error {
func checkPermSubjectArray(sa []string, allowQueue bool) error {
for _, s := range sa {
if !IsValidSubject(s) {
if !allowQueue {
return fmt.Errorf("subject %q is not a valid subject", s)
}
// Check here if this is a queue group qualified subject.
elements := strings.Fields(s)
if len(elements) != 2 {
return fmt.Errorf("subject %q is not a valid subject", s)
} else if !IsValidSubject(elements[0]) {
return fmt.Errorf("subject %q is not a valid subject", elements[0])
} else if !IsValidSubject(elements[1]) {
return fmt.Errorf("queue %q is not a valid queue", elements[1])
}
}
}
@@ -6122,6 +6165,9 @@ func setBaselineOptions(opts *Options) {
if opts.JetStreamInfoQueueLimit <= 0 {
opts.JetStreamInfoQueueLimit = opts.JetStreamRequestQueueLimit
}
if opts.JetStreamConcurrentIOs <= 0 {
opts.JetStreamConcurrentIOs = defaultConcurrentIOs
}
}
func getDefaultAuthTimeout(tls *tls.Config, tlsTimeout float64) float64 {
Loaded 100 of 525 files, more files were not shown because too many files have changed in this diff. Show more